├── .gitignore ├── run ├── src ├── kernel │ ├── src │ │ ├── string.c │ │ ├── port_io.c │ │ ├── include │ │ │ ├── string.h │ │ │ ├── port_io.h │ │ │ ├── boot.h │ │ │ ├── uart.h │ │ │ ├── graphics.h │ │ │ └── vga.h │ │ ├── kernel.ld │ │ ├── graphics.c │ │ ├── uart.c │ │ ├── kernel.c │ │ └── vga.c │ └── makefile ├── bootloader │ ├── src │ │ ├── fs.c │ │ ├── include │ │ │ ├── fs.h │ │ │ ├── error.h │ │ │ ├── debug.h │ │ │ ├── memory_map.h │ │ │ ├── loader.h │ │ │ ├── serial.h │ │ │ ├── graphics.h │ │ │ ├── bootloader.h │ │ │ └── elf.h │ │ ├── error.c │ │ ├── memory_map.c │ │ ├── debug.c │ │ ├── serial.c │ │ ├── graphics.c │ │ ├── main.c │ │ ├── loader.c │ │ └── elf.c │ └── makefile └── makefile ├── README.md ├── STYLEGUIDE.md └── LICENCE /.gitignore: -------------------------------------------------------------------------------- 1 | build 2 | *.EFI 3 | *.efi 4 | *.o 5 | *.so 6 | *.img 7 | *.swo 8 | *.swp 9 | -------------------------------------------------------------------------------- /run: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Cleans, builds and runs the OS image. 4 | make clean -C "src" 5 | make -C "src" && make -C "src" emu 6 | -------------------------------------------------------------------------------- /src/kernel/src/string.c: -------------------------------------------------------------------------------- 1 | /** 2 | * @file string.c 3 | * @author ajxs 4 | * @date Aug 2019 5 | * @brief String functionality. 6 | * Contains implementation for string functions. 7 | */ 8 | 9 | #include 10 | 11 | /** 12 | * strlen 13 | */ 14 | size_t strlen(const char* str) 15 | { 16 | /** The length of the string to be output. */ 17 | size_t len = 0; 18 | while(str[len]) { 19 | len++; 20 | } 21 | 22 | return len; 23 | } 24 | -------------------------------------------------------------------------------- /src/kernel/src/port_io.c: -------------------------------------------------------------------------------- 1 | /** 2 | * @file port_io.c 3 | * @author ajxs 4 | * @date Aug 2019 5 | * @brief Port IO functionality. 6 | * Contains implementation for port IO. 7 | */ 8 | 9 | #include 10 | 11 | /** 12 | * inb 13 | */ 14 | uint8_t inb(uint16_t port) 15 | { 16 | uint8_t ret; 17 | asm volatile("inb %1, %0" : "=a"(ret) : "Nd"(port)); 18 | return ret; 19 | } 20 | 21 | 22 | /** 23 | * outb 24 | */ 25 | void outb(uint16_t port, uint8_t val) 26 | { 27 | asm volatile("outb %0, %1" : : "a"(val), "Nd"(port)); 28 | } 29 | -------------------------------------------------------------------------------- /src/kernel/src/include/string.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file string.h 3 | * @author ajxs 4 | * @date Aug 2019 5 | * @brief String functionality. 6 | * Contains definitions for string functions. 7 | */ 8 | 9 | #ifndef STRING_H 10 | #define STRING_H 11 | 12 | #include 13 | 14 | /** 15 | * @brief Gets the size of a string. 16 | * Returns the number of chars making up a constant string. 17 | * @param str[in] The string to get the length of. 18 | * @return The size of the string. 19 | */ 20 | size_t strlen(const char* str); 21 | 22 | #endif 23 | -------------------------------------------------------------------------------- /src/kernel/src/include/port_io.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file port_io.h 3 | * @author ajxs 4 | * @date Aug 2019 5 | * @brief Port IO functionality. 6 | * Contains definitions for port IO functions. 7 | */ 8 | 9 | #ifndef PORT_IO_H 10 | #define PORT_IO_H 11 | 12 | #include 13 | 14 | /** 15 | * @brief Reads a byte from an IO port. 16 | * Reads a byte from a specified IO port. 17 | * @param port[in] The port to read the byte from. 18 | * @return The byte read from the port. 19 | */ 20 | uint8_t inb(uint16_t port); 21 | 22 | /** 23 | * @brief Writes a byte to an IO port. 24 | * Writes a byte to a specified IO port. 25 | * @param port[in] The port to write the byte to. 26 | * @param val[in] The byte to write. 27 | */ 28 | void outb(uint16_t port, uint8_t val); 29 | 30 | #endif 31 | -------------------------------------------------------------------------------- /src/bootloader/src/fs.c: -------------------------------------------------------------------------------- 1 | /** 2 | * @file fs.c 3 | * @author ajxs 4 | * @date Aug 2019 5 | * @brief Filesystem functionality. 6 | * Contains functionality for interacting with the filesystem via EFI services. 7 | */ 8 | 9 | #include 10 | #include 11 | 12 | #include 13 | #include 14 | #include 15 | #include 16 | 17 | 18 | /** 19 | * init_file_system_service 20 | */ 21 | EFI_STATUS init_file_system_service(void) 22 | { 23 | #ifdef DEBUG 24 | debug_print_line(L"Debug: Initialising File System service\n"); 25 | #endif 26 | 27 | EFI_STATUS status = uefi_call_wrapper(gBS->LocateProtocol, 3, 28 | &gEfiSimpleFileSystemProtocolGuid, NULL, &file_system_service.protocol); 29 | if(EFI_ERROR(status)) { 30 | debug_print_line(L"Fatal Error: Error locating Simple File System Protocol: %s\n", 31 | get_efi_error_message(status)); 32 | 33 | return status; 34 | } 35 | 36 | #ifdef DEBUG 37 | debug_print_line(L"Debug: Located Simple File System Protocol\n"); 38 | #endif 39 | 40 | return status; 41 | } 42 | -------------------------------------------------------------------------------- /src/kernel/src/kernel.ld: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2019, AJXS. 3 | * This program is free software; you can redistribute it and/or modify it 4 | * under the terms of the GNU General Public License as published by the 5 | * Free Software Foundation; either version 3 of the License, or 6 | * (at your option) any later version. 7 | * 8 | * Authors: 9 | * Anthony 10 | */ 11 | 12 | /** The physical starting address of the kernel. */ 13 | KERNEL_PHYS_START = 1M; 14 | /** The size of the kernel stack. */ 15 | KERNEL_STACK_SIZE = 0x4000; 16 | 17 | ENTRY (kernel_main) 18 | 19 | SECTIONS 20 | { 21 | . = KERNEL_PHYS_START; 22 | kernel_start = .; 23 | 24 | .text : ALIGN (4K) 25 | { 26 | *(.text*) 27 | } 28 | 29 | .rodata : ALIGN (4K) 30 | { 31 | *(.rodata*) 32 | } 33 | 34 | .data : ALIGN (4K) 35 | { 36 | *(.data*) 37 | } 38 | 39 | .bss : ALIGN (4K) 40 | { 41 | *(COMMON) 42 | *(.bss*) 43 | 44 | . = ALIGN (16); 45 | stack_bottom = .; 46 | . += KERNEL_STACK_SIZE; 47 | stack_top = .; 48 | } 49 | 50 | kernel_end = .; 51 | } 52 | -------------------------------------------------------------------------------- /src/bootloader/src/include/fs.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file fs.h 3 | * @author ajxs 4 | * @date Aug 2019 5 | * @brief Functionality for working with the file system. 6 | * Contains functionality for initiating and working with the file system service. 7 | */ 8 | 9 | #ifndef BOOTLOADER_FS_H 10 | #define BOOTLOADER_FS_H 1 11 | 12 | #include 13 | #include 14 | 15 | /** 16 | * @brief The file system service. 17 | * Holds the protocol variables necessary to use the simple file system protocol. 18 | */ 19 | typedef struct s_uefi_simple_file_system_service { 20 | EFI_SIMPLE_FILE_SYSTEM_PROTOCOL* protocol; 21 | } Uefi_File_System_Service; 22 | 23 | /** 24 | * @brief Initialise the file system service. 25 | * Initialises the UEFI simple file system service, used for interacting with 26 | * the file system. 27 | * Refer to: https://mjg59.dreamwidth.org/18773.html?thread=768085#cmt768085 28 | * @return The program status. 29 | * @retval EFI_SUCCESS If the function executed successfully. 30 | * @retval other Any other value is an EFI error code. 31 | */ 32 | EFI_STATUS init_file_system_service(void); 33 | 34 | #endif 35 | -------------------------------------------------------------------------------- /src/kernel/src/graphics.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | /** 5 | * draw_rect 6 | */ 7 | void draw_rect(uint32_t* framebuffer_pointer, 8 | const uint32_t pixels_per_scaline, 9 | const uint16_t _x, 10 | const uint16_t _y, 11 | const uint16_t width, 12 | const uint16_t height, 13 | const uint32_t color) 14 | { 15 | /** Pointer to the current pixel in the buffer. */ 16 | uint32_t* at; 17 | 18 | uint16_t row = 0; 19 | uint16_t col = 0; 20 | for(row = 0; row < height; row++) { 21 | for(col = 0; col < width; col++) { 22 | at = framebuffer_pointer + _x + col; 23 | at += ((_y + row) * pixels_per_scaline); 24 | 25 | *at = color; 26 | } 27 | } 28 | } 29 | 30 | void draw_pixel(uint32_t* framebuffer_pointer, 31 | const uint32_t pixels_per_scaline, 32 | const uint16_t _x, 33 | const uint16_t _y, 34 | const uint32_t color) 35 | { 36 | /** Pointer to the current pixel in the buffer. */ 37 | uint32_t* at = framebuffer_pointer + _x + (_y * pixels_per_scaline); 38 | *at = color; 39 | } 40 | 41 | uint32_t convert_rgb_to_32bit_colour(const uint8_t r, 42 | const uint8_t g, 43 | const uint8_t b) 44 | { 45 | return (r << 16) | (g << 8) | b; 46 | } 47 | -------------------------------------------------------------------------------- /src/kernel/src/include/boot.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file boot.h 3 | * @author ajxs 4 | * @date Aug 2019 5 | * @brief Boot functionality. 6 | * Contains definitions for boot structures. 7 | */ 8 | 9 | #ifndef BOOT_H 10 | #define BOOT_H 11 | 12 | #include 13 | 14 | /** 15 | * @brief Memory region descriptor. 16 | * Describes a region of memory. This is passed to the kernel by the bootloader. 17 | */ 18 | typedef struct s_memory_region_desc { 19 | uint32_t type; 20 | uintptr_t physical_start; 21 | uintptr_t virtual_start; 22 | uint64_t count; 23 | uint64_t attributes; 24 | } Memory_Map_Descriptor; 25 | 26 | typedef struct s_boot_video_info { 27 | uint32_t* framebuffer_pointer; 28 | uint32_t horizontal_resolution; 29 | uint32_t vertical_resolution; 30 | uint32_t pixels_per_scaline; 31 | } Kernel_Boot_Video_Mode_Info; 32 | 33 | /** 34 | * @brief Boot info struct. 35 | * Contains information passed to the kernel at boot time by the bootloader. 36 | */ 37 | typedef struct s_boot_info { 38 | Memory_Map_Descriptor* memory_map; 39 | uint64_t mmap_size; 40 | uint64_t mmap_descriptor_size; 41 | Kernel_Boot_Video_Mode_Info video_mode_info; 42 | } Boot_Info; 43 | 44 | #endif 45 | 46 | -------------------------------------------------------------------------------- /src/bootloader/src/include/error.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file error.h 3 | * @author ajxs 4 | * @date Aug 2019 5 | * @brief Functionality for printing error messages. 6 | * Contains functionality for printing error messages that occur within the application 7 | * and assisting with error handling. 8 | */ 9 | 10 | #ifndef BOOTLOADER_ERROR_H 11 | #define BOOTLOADER_ERROR_H 1 12 | 13 | #include 14 | #include 15 | #include 16 | 17 | /** 18 | * @brief Gets a formatted string explaining an EFI error. 19 | * Returns a C string representing an EFI error encountered in a human 20 | * interpretable format. 21 | * @param[in] status The EFI_STATUS encountered. 22 | * @return A const string explaining the error message. 23 | */ 24 | const CHAR16* get_efi_error_message(IN EFI_STATUS const status); 25 | 26 | /** 27 | * @brief Tests a status variable to determine whether an EFI error has occurred, and 28 | * prints the specified error message if so. 29 | * @param[in] status The status code to test. 30 | * @param[in] error_message The error message to print in the case that the status 31 | * code represents an error. 32 | * @return A boolean indicating whether an error has occurred. 33 | */ 34 | bool check_for_fatal_error(IN EFI_STATUS const status, 35 | IN const CHAR16* error_message); 36 | 37 | #endif 38 | -------------------------------------------------------------------------------- /src/bootloader/src/include/debug.h: -------------------------------------------------------------------------------- 1 | #ifndef DEBUG_H 2 | #define DEBUG_H 3 | 4 | /** 5 | * @brief Prints to the default debug output. 6 | * Prints a null terminated format string to a the default debug output device. 7 | * If the serial service has been initialised, this will be used by default, 8 | * otherwise the default GNU-EFI `Print` function will be used. 9 | * Accepts all standard format specifiers as used in `string.h` functions. 10 | * @param[in] fmt The format line to print. 11 | * @param[in] ... Arguments for the format line. 12 | * @return The program status. 13 | * @retval EFI_SUCCESS If the function executed successfully. 14 | * @retval EFI_INVALID_PARAMETER If the supplied protocol is not properly 15 | * loaded or the supplied string is empty. 16 | * @retval EFI_BAD_BUFFER_SIZE If the string is over the maximum length or 17 | * not properly null terminated. 18 | * @retval other Any other value is an EFI error code. 19 | * @warn If the string is not null terminated, this will result in an error. 20 | */ 21 | EFI_STATUS debug_print_line(IN CHAR16* fmt, ...); 22 | 23 | void debug_print_memory_map( 24 | IN EFI_MEMORY_DESCRIPTOR* memory_map, 25 | IN UINTN memory_map_size, 26 | IN UINTN descriptor_size 27 | ); 28 | 29 | #endif 30 | -------------------------------------------------------------------------------- /src/kernel/src/include/uart.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file uart.h 3 | * @author ajxs 4 | * @date Aug 2019 5 | * @brief UART functionality. 6 | * Contains definitions for serial IO. 7 | */ 8 | 9 | #ifndef UART_H 10 | #define UART_H 11 | 12 | #include 13 | 14 | /** 15 | * @brief Initialises the UART. 16 | * Initialises the system UART for output. 17 | */ 18 | void uart_initialize(void); 19 | 20 | /** 21 | * @brief Checks whether the UART receive buffer is empty. 22 | * This function checks whether the UART receive buffer is empty. 23 | * @return A boolean indicating whether the recieve buffer is empty. 24 | */ 25 | bool uart_is_recieve_buffer_empty(void); 26 | 27 | /** 28 | * @brief UART getchar. 29 | * Gets a character from the UART input buffer. 30 | * @return The read character. 31 | */ 32 | char uart_getchar(void); 33 | 34 | /** 35 | * @brief Checks whether the UART transmit buffer is empty. 36 | * This function checks whether the UART transmit buffer is empty. 37 | * @return A boolean indicating whether the transmit buffer is empty. 38 | */ 39 | bool uart_is_transmit_buffer_empty(void); 40 | 41 | /** 42 | * @brief UART putchar. 43 | * Writes a character to the UART. 44 | * @param a[in] The char to write. 45 | */ 46 | void uart_putchar(char a); 47 | 48 | /** 49 | * @brief UART puts. 50 | * Writes a string to the UART. 51 | * @param str[in] The string to write to the UART. 52 | */ 53 | void uart_puts(const char* str); 54 | 55 | #endif 56 | -------------------------------------------------------------------------------- /src/bootloader/src/error.c: -------------------------------------------------------------------------------- 1 | /** 2 | * @file error.c 3 | * @author ajxs 4 | * @date Aug 2019 5 | * @brief Functionality for printing error messages. 6 | * Contains functionality for printing error messages that occur within the 7 | * application and assisting with error handling. 8 | */ 9 | 10 | #include 11 | #include 12 | 13 | #include 14 | #include 15 | #include 16 | 17 | /** 18 | * @brief Error message string buffer. 19 | * This is used for storing the error message string returned from the 20 | * `get_efi_error_message` function. 21 | * @note 256 is a more-than-suitable length for this buffer since we know 22 | * ahead of time the lengths of all of the GNU EFI error messages. Refer 23 | * to the GNU-EFI source: 24 | * `https://sourceforge.net/p/gnu-efi/code/ci/master/tree/lib/error.c` 25 | */ 26 | CHAR16 error_message_buffer[256]; 27 | 28 | 29 | /** 30 | * get_efi_error_message 31 | */ 32 | const CHAR16* get_efi_error_message(IN EFI_STATUS const status) 33 | { 34 | // Copy the status into the error message buffer. 35 | StatusToString(error_message_buffer, status); 36 | return error_message_buffer; 37 | } 38 | 39 | /** 40 | * check_for_fatal_error 41 | */ 42 | bool check_for_fatal_error(IN EFI_STATUS const status, 43 | IN const CHAR16* error_message) 44 | { 45 | if(EFI_ERROR(status)) { 46 | /** Input key type used to capture user input. */ 47 | EFI_INPUT_KEY input_key; 48 | 49 | debug_print_line(L"Fatal Error: %s: %s\n", error_message, 50 | get_efi_error_message(status)); 51 | 52 | #if PROMPT_FOR_INPUT_BEFORE_REBOOT_ON_FATAL_ERROR 53 | debug_print_line(L"Press any key to reboot..."); 54 | wait_for_input(&input_key); 55 | #endif 56 | 57 | return TRUE; 58 | } 59 | 60 | return FALSE; 61 | } 62 | -------------------------------------------------------------------------------- /src/bootloader/src/include/memory_map.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file graphics.h 3 | * @author ajxs 4 | * @date Aug 2019 5 | * @brief Functionality for working with the graphics protocol. 6 | * Contains functionality for initiating and working with the graphics protocol and 7 | * its associated framebuffers. 8 | */ 9 | 10 | #ifndef BOOTLOADER_MEMORY_MAP_H 11 | #define BOOTLOADER_MEMORY_MAP_H 1 12 | 13 | #include 14 | #include 15 | 16 | /** 17 | * @brief Allocates the memory map. 18 | * Allocates the memory map. This function needs to be run prior to exiting 19 | * UEFI boot services. 20 | * @param[out] memory_map A pointer to pointer to the memory map 21 | * buffer to be allocated in this function. 22 | * @param[out] memory_map_size The size of the allocated buffer. 23 | * @param[out] memory_map_key They key of the allocated memory map. 24 | * @param[out] descriptor_size A pointer to the size of an individual 25 | * EFI_MEMORY_DESCRIPTOR. 26 | * @param[out] descriptor_version A pointer to the version number associated 27 | * with the EFI_MEMORY_DESCRIPTOR. 28 | * @return The program status. 29 | * @retval EFI_SUCCESS The function executed successfully. 30 | * @retval other A fatal error occurred getting the memory map. 31 | * @warn After this function has been run, no other boot services may be used 32 | * otherwise the memory map key will have changed, and the memory map 33 | * will be considered invalid. 34 | */ 35 | EFI_STATUS get_memory_map(OUT VOID** memory_map, 36 | OUT UINTN* memory_map_size, 37 | OUT UINTN* memory_map_key, 38 | OUT UINTN* descriptor_size, 39 | OUT UINT32* descriptor_version); 40 | 41 | #endif 42 | -------------------------------------------------------------------------------- /src/kernel/src/uart.c: -------------------------------------------------------------------------------- 1 | /** 2 | * @file uart.c 3 | * @author ajxs 4 | * @date Aug 2019 5 | * @brief UART functionality. 6 | * Contains the implementation of the UART. 7 | */ 8 | 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | /* COM1 Port address*/ 17 | #define UART_PORT_COM1 0x3f8 18 | 19 | 20 | /** 21 | * uart_initialize 22 | */ 23 | void uart_initialize(void) 24 | { 25 | outb(UART_PORT_COM1 + 1, 0x00); // Disable all interrupts 26 | outb(UART_PORT_COM1 + 3, 0x80); // Enable DLAB (set baud rate divisor) 27 | outb(UART_PORT_COM1 + 0, 0x03); // Set divisor to 3 (lo byte) 38400 baud 28 | outb(UART_PORT_COM1 + 1, 0x00); // (hi byte) 29 | outb(UART_PORT_COM1 + 3, 0x03); // 8 bits, no parity, one stop bit 30 | outb(UART_PORT_COM1 + 2, 0xC7); // Enable FIFO, clear them, with 14-byte threshold 31 | outb(UART_PORT_COM1 + 4, 0x0B); // IRQs enabled, RTS/DSR set 32 | } 33 | 34 | 35 | /** 36 | * uart_is_recieve_buffer_empty 37 | */ 38 | bool uart_is_recieve_buffer_empty(void) 39 | { 40 | return inb(UART_PORT_COM1 + 5) & 1; 41 | } 42 | 43 | 44 | /** 45 | * uart_getchar 46 | */ 47 | char uart_getchar(void) 48 | { 49 | while(!uart_is_recieve_buffer_empty()); 50 | 51 | return inb(UART_PORT_COM1); 52 | } 53 | 54 | 55 | /** 56 | * uart_is_transmit_buffer_empty 57 | */ 58 | bool uart_is_transmit_buffer_empty(void) 59 | { 60 | return (inb(UART_PORT_COM1 + 5) & 0x20) != 0; 61 | } 62 | 63 | 64 | /** 65 | * uart_putchar 66 | */ 67 | void uart_putchar(char a) 68 | { 69 | while(!uart_is_transmit_buffer_empty()); 70 | 71 | outb(UART_PORT_COM1, a); 72 | } 73 | 74 | 75 | /** 76 | * uart_puts 77 | */ 78 | void uart_puts(const char* str) 79 | { 80 | /** The length of the string being written to serial out. */ 81 | size_t str_len = strlen(str); 82 | for(size_t i = 0; i < str_len; i++) { 83 | uart_putchar(str[i]); 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/kernel/makefile: -------------------------------------------------------------------------------- 1 | ##################################################################### 2 | # Copyright (c) 2019, AJXS. 3 | # This program is free software; you can redistribute it and/or modify it 4 | # under the terms of the GNU General Public License as published by the 5 | # Free Software Foundation; either version 3 of the License, or 6 | # (at your option) any later version. 7 | # 8 | # Authors: 9 | # Anthony 10 | ##################################################################### 11 | 12 | .POSIX: 13 | .DELETE_ON_ERROR: 14 | MAKEFLAGS += --warn-undefined-variables 15 | MAKEFLAGS += --no-builtin-rules 16 | 17 | ARCH := x86_64 18 | CC := ${ARCH}-elf-gcc 19 | 20 | SRC_DIR := src 21 | 22 | INCLUDE_DIRS := ${SRC_DIR}/include 23 | INCLUDE_FLAG := ${foreach d, ${INCLUDE_DIRS}, -I$d} 24 | 25 | CFLAGS := \ 26 | -std=gnu99 \ 27 | -ffreestanding \ 28 | -fno-common \ 29 | -O2 \ 30 | -Wall \ 31 | -Wextra \ 32 | -Wmissing-prototypes \ 33 | -Wstrict-prototypes 34 | 35 | LDFLAGS := \ 36 | -ffreestanding \ 37 | -O2 \ 38 | -nostdlib \ 39 | -z max-page-size=0x1000 40 | 41 | LIBS := -lgcc 42 | 43 | 44 | AS_SOURCES := 45 | 46 | C_SOURCES := \ 47 | ${SRC_DIR}/graphics.c \ 48 | ${SRC_DIR}/kernel.c \ 49 | ${SRC_DIR}/port_io.c \ 50 | ${SRC_DIR}/string.c \ 51 | ${SRC_DIR}/uart.c \ 52 | ${SRC_DIR}/vga.c 53 | 54 | OBJECTS := ${AS_SOURCES:.S=.o} 55 | OBJECTS += ${C_SOURCES:.c=.o} 56 | 57 | BUILD_DIR := build 58 | BINARY := ${BUILD_DIR}/kernel.elf 59 | 60 | 61 | .PHONY: all clean 62 | 63 | all: ${BINARY} 64 | 65 | ${BINARY}: ${BUILD_DIR} ${OBJECTS} 66 | ${CC} -T ${SRC_DIR}/kernel.ld -g3 -o ${BINARY} ${LDFLAGS} ${OBJECTS} ${LIBS} 67 | 68 | %.o: %.S 69 | ${CC} ${INCLUDE_FLAG} -g -c $< -o $@ ${CFLAGS} 70 | 71 | %.o: %.c 72 | ${CC} ${INCLUDE_FLAG} -g -c $< -o $@ ${CFLAGS} 73 | 74 | ${BUILD_DIR}: 75 | mkdir -p ${BUILD_DIR} 76 | 77 | clean: 78 | rm -f ${OBJECTS} 79 | rm -f ${BINARY} 80 | -------------------------------------------------------------------------------- /src/kernel/src/kernel.c: -------------------------------------------------------------------------------- 1 | /** 2 | * @file kernel.c 3 | * @author ajxs 4 | * @date Aug 2019 5 | * @brief Kernel entry. 6 | * Contains the kernel entry point. 7 | */ 8 | 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | /** Whether to draw a test pattern to video output. */ 17 | #define DRAW_TEST_SCREEN 1 18 | 19 | #define TEST_SCREEN_COL_NUM 4 20 | #define TEST_SCREEN_ROW_NUM 3 21 | #define TEST_SCREEN_TOTAL_TILES TEST_SCREEN_COL_NUM * TEST_SCREEN_ROW_NUM 22 | #define TEST_SCREEN_PRIMARY_COLOUR 0x00FF40FF 23 | #define TEST_SCREEN_SECONDARY_COLOUR 0x00FF00CF 24 | 25 | /** 26 | * @brief Draws a test screen to the framebuffer. 27 | * Paints the XOR test texture to the screen. 28 | * Refer to: https://lodev.org/cgtutor/xortexture.html 29 | * @param[in] boot_info The boot information passed to the kernel. This contains 30 | * a pointer to the framebuffer, and the associated video mode information 31 | * needed to draw the test screen. 32 | */ 33 | static void draw_test_screen(Boot_Info* boot_info); 34 | 35 | /** 36 | * @brief The kernel main program. 37 | * This is the kernel main entry point and its main program. 38 | */ 39 | void kernel_main(Boot_Info* boot_info); 40 | 41 | 42 | /** 43 | * draw_test_screen 44 | */ 45 | static void draw_test_screen(Boot_Info* boot_info) 46 | { 47 | uint8_t c = 0; 48 | uint32_t colour = 0; 49 | uint16_t x = 0; 50 | uint16_t y = 0; 51 | 52 | for(y = 0; y < boot_info->video_mode_info.vertical_resolution; y++) { 53 | for(x = 0; x < boot_info->video_mode_info.horizontal_resolution; x++) { 54 | c = (x ^ y) % 256; 55 | colour = convert_rgb_to_32bit_colour(255 - (c % 128), c, c % 128); 56 | 57 | draw_pixel( 58 | boot_info->video_mode_info.framebuffer_pointer, 59 | boot_info->video_mode_info.pixels_per_scaline, 60 | x, 61 | y, 62 | colour 63 | ); 64 | } 65 | } 66 | } 67 | 68 | 69 | /** 70 | * kernel_main 71 | */ 72 | void kernel_main(Boot_Info* boot_info) 73 | { 74 | // Initialise the UART. 75 | uart_initialize(); 76 | uart_puts("Kernel: Initialised.\n"); 77 | 78 | #if DRAW_TEST_SCREEN 79 | draw_test_screen(boot_info); 80 | #endif 81 | 82 | while(1); 83 | } 84 | -------------------------------------------------------------------------------- /src/kernel/src/include/graphics.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file graphics.h 3 | * @author ajxs 4 | * @date Aug 2022 5 | * @brief Functionality for working with the framebuffer. 6 | * Contains functionality for working with the framebuffer. 7 | */ 8 | 9 | #ifndef GRAPHICS_H 10 | #define GRAPHICS_H 1 11 | 12 | #include 13 | 14 | /** 15 | * @brief Draws a rectangle onto the framebuffer. 16 | * Draws a rectangle onto the video frame buffer. 17 | * @param[in] framebuffer_pointer A pointer to the video framebuffer. 18 | * @param[in] pixels_per_scaline The number of pixels per scanline. Also known as 'pitch'. 19 | * In some more exotic video modes this may be different to the visible screen width. 20 | * @param[in] _x The x coordinate to draw the rect to. 21 | * @param[in] _y The y coordinate to draw the rect to. 22 | * @param[in] width The width of the rectangle to draw. 23 | * @param[in] height The height of the rectangle to draw. 24 | * @param[in] color The color to draw. 25 | */ 26 | void draw_rect(uint32_t* framebuffer_pointer, 27 | const uint32_t pixels_per_scaline, 28 | const uint16_t _x, 29 | const uint16_t _y, 30 | const uint16_t width, 31 | const uint16_t height, 32 | const uint32_t color); 33 | 34 | /** 35 | * @brief Paints a pixel of a certain colour onto the framebuffer. 36 | * @param[in] framebuffer_pointer A pointer to the video framebuffer. 37 | * @param[in] pixels_per_scaline The number of pixels per scanline. Also known as 'pitch'. 38 | * In some more exotic video modes this may be different to the visible screen width. 39 | * @param[in] _x The x coordinate to pixel. 40 | * @param[in] _y The y coordinate to pixel. 41 | * @param[in] color The color to draw. 42 | */ 43 | void draw_pixel(uint32_t* framebuffer_pointer, 44 | const uint32_t pixels_per_scaline, 45 | const uint16_t _x, 46 | const uint16_t _y, 47 | const uint32_t color); 48 | 49 | /** 50 | * @brief Converts an RGB colour to a 32-bit colour suitable for using with 51 | * a framebuffer using the UEFI Graphics Output Protocol. 52 | * @param[in] r The red component. 53 | * @param[in] g The green component. 54 | * @param[in] b The blue component. 55 | * @return The colour encoded as a 32-bit integer. 56 | */ 57 | uint32_t convert_rgb_to_32bit_colour(const uint8_t r, 58 | const uint8_t g, 59 | const uint8_t b); 60 | 61 | #endif 62 | -------------------------------------------------------------------------------- /src/bootloader/src/include/loader.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file loader.h 3 | * @author ajxs 4 | * @date Aug 2019 5 | * @brief Functionality for loading the Kernel executable. 6 | * Contains functionality for loading the Kernel ELF executable. 7 | */ 8 | 9 | #ifndef BOOTLOADER_LOADER_H 10 | #define BOOTLOADER_LOADER_H 1 11 | 12 | #include 13 | #include 14 | 15 | /** 16 | * @brief Loads an ELF segment. 17 | * Loads an ELF program segment into memory. 18 | * This will read the ELF segment from the kernel binary, allocate the pages 19 | * necessary to load the segment into memory and then copy the segment to its 20 | * required physical memory address. 21 | * @param[in] kernel_img_file The Kernel EFI file entity to read from. 22 | * @param[in] segment_file_offset The segment's offset into the ELF binary. 23 | * @param[in] segment_file_size The segment's size in the ELF binary. 24 | * @param[in] segment_memory_size The size of the segment loaded into memory. 25 | * @param[in] segment_physical_address The physical memory address to load the segment to. 26 | * @return The program status. 27 | * @retval EFI_SUCCESS If the function executed successfully. 28 | * @retval other Any other value is an EFI error code. 29 | */ 30 | EFI_STATUS load_segment(IN EFI_FILE* const kernel_img_file, 31 | IN EFI_PHYSICAL_ADDRESS const segment_file_offset, 32 | IN UINTN const segment_file_size, 33 | IN UINTN const segment_memory_size, 34 | IN EFI_PHYSICAL_ADDRESS const segment_physical_address); 35 | 36 | /** 37 | * @brief Loads the ELF program segments. 38 | * Loads the Kernel ELF binary's program segments into memory. 39 | * @param[in] kernel_img_file The Kernel EFI file entity to read from. 40 | * @param[in] file_class The ELF file class, whether the program is 32 or 64bit. 41 | * @param[in] kernel_header_buffer The Kernel header buffer. 42 | * @param[in] kernel_program_headers_buffer The kernel program headers buffer. 43 | * @return The program status. 44 | * @retval EFI_SUCCESS If the function executed successfully. 45 | * @retval other Any other value is an EFI error code. 46 | */ 47 | EFI_STATUS load_program_segments(IN EFI_FILE* const kernel_img_file, 48 | IN Elf_File_Class const file_class, 49 | IN VOID* const kernel_header_buffer, 50 | IN VOID* const kernel_program_headers_buffer); 51 | 52 | #endif 53 | -------------------------------------------------------------------------------- /src/kernel/src/include/vga.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file vga.h 3 | * @author ajxs 4 | * @date Aug 2019 5 | * @brief VGA functionality. 6 | * Contains definitions for VGA functionality. 7 | */ 8 | 9 | #ifndef VGA_H 10 | #define VGA_H 11 | 12 | #include 13 | 14 | /** 15 | * @brief VGA Colors. 16 | * VGA Color codes. These are combined together to form a VGA color entry. 17 | */ 18 | enum vga_color { 19 | VGA_COLOR_BLACK = 0, 20 | VGA_COLOR_BLUE = 1, 21 | VGA_COLOR_GREEN = 2, 22 | VGA_COLOR_CYAN = 3, 23 | VGA_COLOR_RED = 4, 24 | VGA_COLOR_MAGENTA = 5, 25 | VGA_COLOR_BROWN = 6, 26 | VGA_COLOR_LIGHT_GREY = 7, 27 | VGA_COLOR_DARK_GREY = 8, 28 | VGA_COLOR_LIGHT_BLUE = 9, 29 | VGA_COLOR_LIGHT_GREEN = 10, 30 | VGA_COLOR_LIGHT_CYAN = 11, 31 | VGA_COLOR_LIGHT_RED = 12, 32 | VGA_COLOR_LIGHT_MAGENTA = 13, 33 | VGA_COLOR_LIGHT_BROWN = 14, 34 | VGA_COLOR_WHITE = 15, 35 | }; 36 | 37 | 38 | /** 39 | * @brief Creates a VGA color entry. 40 | * Encodes two color codes into a VGA color entry, consisting of a fore 41 | * and background color. 42 | * @param fg[in] The foreground color. 43 | * @param bg[in] The background color. 44 | * @return The encoded VGA color entry. 45 | */ 46 | uint8_t create_vga_color_entry(enum vga_color fg, 47 | enum vga_color bg); 48 | 49 | /** 50 | * @brief Creates a VGA character entry. 51 | * Encodes a VGA character entry, consisting of a character and its color entry. 52 | * @param uc[in] The character to encode. 53 | * @param color[in] The color to encode into the entry. 54 | * @return The encoded VGA entry. 55 | */ 56 | uint16_t create_vga_entry(unsigned char uc, 57 | uint8_t color); 58 | 59 | /** 60 | * @brief Initialises VGA for the system. 61 | * Initialises the VGA buffer. 62 | */ 63 | void vga_initialize(void); 64 | 65 | /** 66 | * @brief Sets the VGA color. 67 | * Sets the VGA terminal color. 68 | * @param color[in] The encoded VGA color code to set the terminalk to. 69 | */ 70 | void vga_set_color(uint8_t color); 71 | 72 | /** 73 | * @brief Prints a char to the screen. 74 | * Prints a char to the VGA buffer. 75 | * @param c[in] The char to print to the VGA buffer. 76 | */ 77 | void vga_putchar(char c); 78 | 79 | /** 80 | * @brief Writes a string to screen. 81 | * Writes a string to the VGA buffer. 82 | * @param str[in] The string to write to the buffer. 83 | */ 84 | void vga_puts(const char* str); 85 | 86 | #endif 87 | -------------------------------------------------------------------------------- /src/kernel/src/vga.c: -------------------------------------------------------------------------------- 1 | /** 2 | * @file vga.h 3 | * @author ajxs 4 | * @date Aug 2019 5 | * @brief VGA functionality. 6 | * Contains definitions for VGA functionality. 7 | */ 8 | 9 | #include 10 | #include 11 | #include 12 | #include 13 | 14 | /** VGA Screen dimensions. */ 15 | static const size_t VGA_WIDTH = 80; 16 | static const size_t VGA_HEIGHT = 25; 17 | 18 | /** The VGA row cursor. */ 19 | static size_t vga_row; 20 | /** The VGA column cursor. */ 21 | static size_t vga_column; 22 | /** The currently selected VGA color. */ 23 | static uint8_t vga_color; 24 | /** Pointer to the machine's VGA buffer. */ 25 | static uint16_t* vga_buffer; 26 | 27 | 28 | /** 29 | * create_vga_color_entry 30 | */ 31 | inline uint8_t create_vga_color_entry(enum vga_color fg, 32 | enum vga_color bg) 33 | { 34 | return fg | bg << 4; 35 | } 36 | 37 | 38 | /** 39 | * create_vga_entry 40 | */ 41 | inline uint16_t create_vga_entry(unsigned char uc, 42 | uint8_t color) 43 | { 44 | return (uint16_t) uc | (uint16_t) color << 8; 45 | } 46 | 47 | 48 | /** 49 | * vga_initialize 50 | */ 51 | void vga_initialize(void) 52 | { 53 | vga_row = 0; 54 | vga_column = 0; 55 | vga_color = create_vga_color_entry(VGA_COLOR_LIGHT_GREY, VGA_COLOR_BLACK); 56 | vga_buffer = (uint16_t*)0xC03FF000; 57 | 58 | for(size_t y = 0; y < VGA_HEIGHT; y++) { 59 | for(size_t x = 0; x < VGA_WIDTH; x++) { 60 | const size_t index = y * VGA_WIDTH + x; 61 | vga_buffer[index] = create_vga_entry(' ', vga_color); 62 | } 63 | } 64 | } 65 | 66 | 67 | /** 68 | * vga_set_color 69 | */ 70 | void vga_set_color(uint8_t color) 71 | { 72 | vga_color = color; 73 | } 74 | 75 | 76 | /** 77 | * vga_putchar 78 | */ 79 | void vga_putchar(char c) 80 | { 81 | /** The index into the VGA buffer to place the entry at. */ 82 | const size_t index = vga_row * VGA_WIDTH + vga_column; 83 | vga_buffer[index] = create_vga_entry(c, vga_color); 84 | 85 | if(++vga_column == VGA_WIDTH) { 86 | vga_column = 0; 87 | 88 | if(++vga_row == VGA_HEIGHT) { 89 | vga_row = 0; 90 | } 91 | } 92 | } 93 | 94 | 95 | /** 96 | * vga_puts 97 | */ 98 | void vga_puts(const char* str) 99 | { 100 | /** The length of the string. */ 101 | const size_t len = strlen(str); 102 | 103 | for (size_t i = 0; i < len; i++) { 104 | vga_putchar(str[i]); 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /src/makefile: -------------------------------------------------------------------------------- 1 | ##################################################################### 2 | # Copyright (c) 2019, AJXS. 3 | # This program is free software; you can redistribute it and/or modify it 4 | # under the terms of the GNU General Public License as published by the 5 | # Free Software Foundation; either version 3 of the License, or 6 | # (at your option) any later version. 7 | # 8 | # Authors: 9 | # Anthony 10 | ##################################################################### 11 | 12 | .POSIX: 13 | .DELETE_ON_ERROR: 14 | MAKEFLAGS += --warn-undefined-variables 15 | MAKEFLAGS += --no-builtin-rules 16 | 17 | KERNEL_DIR := kernel 18 | KERNEL_BINARY := ${KERNEL_DIR}/build/kernel.elf 19 | 20 | BOOTLOADER_DIR := bootloader 21 | BOOTLOADER_BINARY := ${BOOTLOADER_DIR}/build/bootx64.efi 22 | 23 | BUILD_DIR := ../build 24 | DISK_IMG := ${BUILD_DIR}/kernel.img 25 | DISK_IMG_SIZE := 2880 26 | 27 | QEMU_FLAGS := \ 28 | -bios OVMF.fd \ 29 | -drive if=none,id=uas-disk1,file=${DISK_IMG},format=raw \ 30 | -device usb-storage,drive=uas-disk1 \ 31 | -serial stdio \ 32 | -usb \ 33 | -net none \ 34 | -vga std 35 | 36 | .PHONY: all clean emu 37 | 38 | all: ${DISK_IMG} 39 | 40 | bootloader: ${BOOTLOADER_BINARY} 41 | 42 | debug: ${DISK_IMG} 43 | qemu-system-x86_64 \ 44 | ${QEMU_FLAGS} \ 45 | -S \ 46 | -gdb tcp::1234 47 | 48 | emu: ${DISK_IMG} 49 | qemu-system-x86_64 \ 50 | ${QEMU_FLAGS} 51 | 52 | kernel: ${KERNEL_BINARY} 53 | 54 | ${DISK_IMG}: ${BUILD_DIR} ${BOOTLOADER_BINARY} ${KERNEL_BINARY} 55 | # Create UEFI boot disk image in DOS format. 56 | dd if=/dev/zero of=${DISK_IMG} bs=1k count=${DISK_IMG_SIZE} 57 | mformat -i ${DISK_IMG} -f ${DISK_IMG_SIZE} :: 58 | mmd -i ${DISK_IMG} ::/EFI 59 | mmd -i ${DISK_IMG} ::/EFI/BOOT 60 | # Copy the bootloader to the boot partition. 61 | mcopy -i ${DISK_IMG} ${BOOTLOADER_BINARY} ::/efi/boot/bootx64.efi 62 | mcopy -i ${DISK_IMG} ${KERNEL_BINARY} ::/kernel.elf 63 | 64 | ${BOOTLOADER_BINARY}: 65 | make -C ${BOOTLOADER_DIR} 66 | 67 | ${BUILD_DIR}: 68 | mkdir -p ${BUILD_DIR} 69 | 70 | ${KERNEL_BINARY}: 71 | make -C ${KERNEL_DIR} 72 | 73 | clean: 74 | make clean -C ${BOOTLOADER_DIR} 75 | make clean -C ${KERNEL_DIR} 76 | rm -f ${DISK_IMG} 77 | rm -rf ${BUILD_DIR} 78 | -------------------------------------------------------------------------------- /src/bootloader/src/include/serial.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file serial.h 3 | * @author ajxs 4 | * @date Aug 2019 5 | * @brief Functionality for working with the serial port. 6 | * Contains functionality for initiating and working with the serial IO service. 7 | */ 8 | 9 | #ifndef BOOTLOADER_SERIAL_H 10 | #define BOOTLOADER_SERIAL_H 1 11 | 12 | #include 13 | #include 14 | 15 | /** The maximum string length able to be printed to the serial. */ 16 | #define MAX_SERIAL_OUT_STRING_LENGTH 512 17 | 18 | /** 19 | * @brief The serial service. 20 | * Contains the variables necessary to use the UEFI serial service. 21 | */ 22 | typedef struct s_uefi_serial_service { 23 | EFI_SERIAL_IO_PROTOCOL* protocol; 24 | } Uefi_Serial_Service; 25 | 26 | /** 27 | * @brief Configures an individual Serial IO protocol instance. 28 | * Configures an individual Serial IO protocol instance. Sets the baud rate and 29 | * other device-specific options. 30 | * @param[in] protocol The serial IO protocol instance to configure. 31 | * @return The program status. 32 | * @retval EFI_SUCCESS If the function executed successfully. 33 | * @retval other Any other value is an EFI error code. 34 | */ 35 | EFI_STATUS configure_serial_protocol(IN EFI_SERIAL_IO_PROTOCOL* const protocol); 36 | 37 | /** 38 | * @brief Initialise the serial service. 39 | * Initialises the serial IO service, used for interacting with serial devices. 40 | * @return The program status. 41 | * @retval EFI_SUCCESS If the function executed successfully. 42 | * @retval other Any other value is an EFI error code. 43 | */ 44 | EFI_STATUS init_serial_service(void); 45 | 46 | /** 47 | * @brief Prints to a serial protocol. 48 | * Prints a null terminated string to a particular serial protocol. 49 | * @param[in] protocol The serial IO protocol instance to configure. 50 | * @param[in] line The line to print. 51 | * @return The program status. 52 | * @retval EFI_SUCCESS If the function executed successfully. 53 | * @retval EFI_INVALID_PARAMETER If the supplied protocol is not properly 54 | * loaded or the supplied string is empty. 55 | * @retval EFI_BAD_BUFFER_SIZE If the string is over the maximum length or 56 | * not properly null terminated. 57 | * @retval other Any other value is an EFI error code. 58 | * @warn If the string is not null terminated, this will result in an error. 59 | */ 60 | EFI_STATUS print_to_serial_out(IN EFI_SERIAL_IO_PROTOCOL* const protocol, 61 | IN CHAR16* line); 62 | 63 | #endif 64 | -------------------------------------------------------------------------------- /src/bootloader/src/memory_map.c: -------------------------------------------------------------------------------- 1 | /** 2 | * @file main.c 3 | * @author ajxs 4 | * @date Aug 2019 5 | * @brief Bootloader entry point and main application. 6 | * The entry point for the application. Contains the main bootloader code that 7 | * initiates the loading of the Kernel executable. The main application is 8 | * contained within the `efi_main` function. 9 | */ 10 | 11 | #include 12 | #include 13 | #include 14 | 15 | #include 16 | #include 17 | #include 18 | #include 19 | 20 | /** 21 | * get_memory_map 22 | */ 23 | EFI_STATUS get_memory_map(OUT VOID** memory_map, 24 | OUT UINTN* memory_map_size, 25 | OUT UINTN* memory_map_key, 26 | OUT UINTN* descriptor_size, 27 | OUT UINT32* descriptor_version) 28 | { 29 | /** Program status. */ 30 | EFI_STATUS status; 31 | /** Input key type used to capture user input. */ 32 | EFI_INPUT_KEY input_key; 33 | 34 | #ifdef DEBUG 35 | debug_print_line(L"Debug: Allocating memory map\n"); 36 | #endif 37 | 38 | status = uefi_call_wrapper(gBS->GetMemoryMap, 5, 39 | memory_map_size, NULL, memory_map_key, 40 | descriptor_size, NULL); 41 | if(EFI_ERROR(status)) { 42 | // This will always fail on the first attempt, this call will return the 43 | // required buffer size. 44 | if(status != EFI_BUFFER_TOO_SMALL) { 45 | debug_print_line(L"Fatal Error: Error getting memory map size: %s\n", 46 | get_efi_error_message(status)); 47 | 48 | #if PROMPT_FOR_INPUT_BEFORE_REBOOT_ON_FATAL_ERROR 49 | debug_print_line(L"Press any key to reboot..."); 50 | wait_for_input(&input_key); 51 | #endif 52 | 53 | return status; 54 | } 55 | } 56 | 57 | #ifdef DEBUG 58 | debug_print_line(L"Debug: Memory map required size: %u\n", *memory_map_size); 59 | #endif 60 | 61 | // According to: https://stackoverflow.com/a/39674958/5931673 62 | // Up to two new descriptors may be created in the process of allocating the 63 | // new pool memory. 64 | *memory_map_size += (2 * (*descriptor_size)); 65 | 66 | #ifdef DEBUG 67 | debug_print_line(L"Debug: Allocating memory map with size: %u\n", 68 | *memory_map_size); 69 | #endif 70 | 71 | status = uefi_call_wrapper(gBS->AllocatePool, 3, 72 | EfiLoaderData, *memory_map_size, (VOID**)memory_map); 73 | if(check_for_fatal_error(status, L"Error allocating memory map buffer")) { 74 | return status; 75 | } 76 | 77 | status = uefi_call_wrapper(gBS->GetMemoryMap, 5, 78 | memory_map_size, *memory_map, memory_map_key, 79 | descriptor_size, descriptor_version); 80 | if(check_for_fatal_error(status, L"Error getting memory map")) { 81 | return status; 82 | } 83 | 84 | return EFI_SUCCESS; 85 | } 86 | -------------------------------------------------------------------------------- /src/bootloader/src/debug.c: -------------------------------------------------------------------------------- 1 | /** 2 | * @file debug.c 3 | * @author ajxs 4 | * @date Jul 2024 5 | * @brief Bootloader debug functions. 6 | */ 7 | 8 | #include 9 | #include 10 | #include 11 | 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | 18 | EFI_STATUS debug_print_line(IN CHAR16* fmt, 19 | ...) 20 | { 21 | /** Main bootloader application status. */ 22 | EFI_STATUS status; 23 | /** The variadic argument list passed to the VSPrintf function. */ 24 | va_list args; 25 | /** 26 | * The output message buffer. 27 | * The string content is copied into this buffer. The maximum length is set 28 | * to the maximum serial buffer length. 29 | */ 30 | CHAR16 output_message[MAX_SERIAL_OUT_STRING_LENGTH]; 31 | 32 | va_start(args, fmt); 33 | 34 | // If the serial service has been initialised, use this as the output medium. 35 | // Otherwise use the default GNU-EFI output. 36 | if(serial_service.protocol) { 37 | VSPrint(output_message, MAX_SERIAL_OUT_STRING_LENGTH, fmt, args); 38 | 39 | status = print_to_serial_out(serial_service.protocol, output_message); 40 | if(EFI_ERROR(status)) { 41 | Print(L"Error: Error printing to serial output: %s\n", 42 | get_efi_error_message(status)); 43 | 44 | return status; 45 | } 46 | } else { 47 | VPrint(fmt, args); 48 | } 49 | 50 | va_end(args); 51 | 52 | return EFI_SUCCESS; 53 | }; 54 | 55 | void debug_print_memory_map( 56 | IN EFI_MEMORY_DESCRIPTOR* memory_map, 57 | IN UINTN memory_map_size, 58 | IN UINTN descriptor_size 59 | ) 60 | { 61 | /** The number of UEFI memory descriptors. */ 62 | const UINT16 n_descriptors = memory_map_size / descriptor_size; 63 | /** Pointer used to iterate through the descriptors. */ 64 | EFI_MEMORY_DESCRIPTOR* current_descriptor = NULL; 65 | 66 | // The firmware will likely not return descriptors in the same format as 67 | // GNU-EFI's definition, so it's necessary to iterate through them using 68 | // pointer arithmetic. 69 | // Refer to: https://stackoverflow.com/a/39674958/5931673 70 | for (UINTN i = 0; i < n_descriptors; i++) { 71 | // The cast here is to ensure that the pointer arithmetic works correctly. 72 | // Refer to: https://stackoverflow.com/a/74791136/5931673 73 | current_descriptor = (VOID*)memory_map + (i * descriptor_size); 74 | 75 | if (current_descriptor->Attribute > 16) { 76 | #ifdef DEBUG 77 | debug_print_line( 78 | L"Descriptor:\n" 79 | L" Type: %u\n" 80 | L" Physical Address: 0x%llx\n" 81 | L" Virtual Address: 0x%llx\n" 82 | L" Size In Pages: %u\n" 83 | L" Attributes: 0x%llx\n\n", 84 | current_descriptor->Type, 85 | current_descriptor->PhysicalStart, 86 | current_descriptor->VirtualStart, 87 | current_descriptor->NumberOfPages, 88 | current_descriptor->Attribute 89 | ); 90 | #endif 91 | } 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/bootloader/makefile: -------------------------------------------------------------------------------- 1 | .POSIX: 2 | .DELETE_ON_ERROR: 3 | MAKEFLAGS += --warn-undefined-variables 4 | MAKEFLAGS += --no-builtin-rules 5 | 6 | ARCH := x86_64 7 | CC := ${ARCH}-unknown-elf-gcc 8 | 9 | BUILD_DIR := build 10 | SRC_DIR := src 11 | 12 | EFI_INC_DIR := /usr/include/efi 13 | INCLUDE_DIRS := ${EFI_INC_DIR} \ 14 | ${EFI_INC_DIR}/${ARCH} \ 15 | ${EFI_INC_DIR}/protocol \ 16 | ${SRC_DIR}/include 17 | 18 | # The full list of includes in correct format for gcc. 19 | INCLUDE_FLAG := $(foreach d, $(INCLUDE_DIRS), -I$d) 20 | 21 | 22 | CFLAGS := ${INCLUDE_FLAG} \ 23 | -ffreestanding \ 24 | -fno-common \ 25 | -fno-stack-protector \ 26 | -fpic \ 27 | -fshort-wchar \ 28 | -mno-red-zone \ 29 | -Wall \ 30 | -Wextra \ 31 | -Wmissing-prototypes \ 32 | -Wstrict-prototypes \ 33 | -DEFI_FUNCTION_WRAPPER 34 | 35 | LIB := /usr/lib 36 | EFI_LIB := /usr/lib 37 | EFI_CRT_OBJS := ${EFI_LIB}/crt0-efi-${ARCH}.o 38 | EFI_LDS := ${EFI_LIB}/elf_${ARCH}_efi.lds 39 | LDFLAGS := -nostdlib \ 40 | -znocombreloc \ 41 | -T ${EFI_LDS} \ 42 | -shared \ 43 | -Bsymbolic \ 44 | -L ${EFI_LIB} \ 45 | -L ${LIB} ${EFI_CRT_OBJS} 46 | 47 | 48 | C_SOURCES := ${SRC_DIR}/elf.c \ 49 | ${SRC_DIR}/debug.c \ 50 | ${SRC_DIR}/error.c \ 51 | ${SRC_DIR}/fs.c \ 52 | ${SRC_DIR}/graphics.c \ 53 | ${SRC_DIR}/loader.c \ 54 | ${SRC_DIR}/memory_map.c \ 55 | ${SRC_DIR}/main.c \ 56 | ${SRC_DIR}/serial.c 57 | 58 | AS_SOURCES := 59 | 60 | 61 | OBJECTS := ${C_SOURCES:.c=.o} 62 | OBJECTS += ${AS_SOURCES:.S=.o} 63 | 64 | # The bootloader is initially compiled into a shared lib in ELF format. GNU-EFI links 65 | # the lib in a special format as to be easily copied into a PE32+ compatible executable 66 | # suitable for use as a UEFI bootloader. 67 | BINARY_ELF := ${BUILD_DIR}/bootx64.so 68 | # This is the ELF shared lib copied into the PE32+ format. 69 | BINARY_EFI := ${BUILD_DIR}/bootx64.efi 70 | 71 | 72 | .PHONY: all clean emu 73 | 74 | all: ${BINARY_EFI} 75 | 76 | ${BINARY_EFI}: ${BINARY_ELF} 77 | objcopy -j .text \ 78 | -j .sdata \ 79 | -j .data \ 80 | -j .dynamic \ 81 | -j .dynsym \ 82 | -j .rel \ 83 | -j .rela \ 84 | -j .reloc \ 85 | --target=efi-app-${ARCH} $^ $@ 86 | 87 | ${BINARY_ELF}: ${OBJECTS} ${BUILD_DIR} 88 | ld ${LDFLAGS} ${OBJECTS} -o $@ -lefi -lgnuefi 89 | 90 | %.o: %.c 91 | ${CC} ${CFLAGS} -o $@ -c $< 92 | 93 | %.o: %.S 94 | ${CC} ${CFLAGS} -o $@ -c $< 95 | 96 | ${BUILD_DIR}: 97 | mkdir -p ${BUILD_DIR} 98 | 99 | clean: 100 | rm -f ${OBJECTS} 101 | rm -f ${BINARY_ELF} 102 | rm -f ${BINARY_EFI} 103 | rm -rf ${BUILD_DIR} 104 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # uefi-elf-bootloader 2 | 3 | This repository contains a simple UEFI ELF bootloader which loads a simple demonstration kernel. It provides an extremely basic example implementation of a UEFI bootloader for a bare-metal x86-64 system, though this example should be portable to other architectures. 4 | 5 | The aim of this repository is to serve as a basic teachable example of how to implement a UEFI bootloader. 6 | 7 | ## Build instructions 8 | This bootloader assumes a GCC cross-compiler toolchain targeting the bare-metal `x86_64-elf` architecture. Instructions for building and obtaining a valid cross-compiler toolchain can be found [here](https://wiki.osdev.org/GCC_Cross-Compiler). 9 | 10 | This bootloader can be built simply by running `make` within the `src` directory. This will create the `build/kernel.img` file, which is a bootable disk image containing the bootloader loading a demonstration kernel. There is a `run` script within the root directory containing a script for testing the bootloader/kernel combination using QEMU. 11 | 12 | ### Build dependencies 13 | - GNU Make 14 | - GNU EFI 15 | - An `x86_64-elf-gcc` cross-compiler toolchain present in `PATH` 16 | 17 | ## Project structure 18 | This project is broken down into two distinct components: The bootloader, and the example kernel. These can be found in the `src/bootloder` and `src/kernel` directories respectively. These can be built and tested individually using the makefiles within their individual directories. Running the makefile within the top level `src` directory will build the entire project. 19 | 20 | ## Bootloader 21 | The bootloader component of this repository, contained within the `src/bootloader` directory, contains the basic implementation of a UEFI ELF bootloader for the x86-64 platform. The bootloader is hardcoded to load and execute a bare-metal x86-64 application located at `/kernel.elf` on the boot media. 22 | This path can be modifid from within the `src/bootloader/src/include/bootloader.h` file by modifying the `KERNEL_INCLUDE_PATH` preprocessor directive. 23 | 24 | The bootloader will output debugging information over the system's serial port, if present. Otherwise VGA output will be used. 25 | 26 | The bootloader passes a `Kernel_Boot_Info` struct to the loaded kernel containing basic system information, such as the memory map. This struct is defined within the `src/bootloader/src/include/bootloader.h` header file. This implementation is not tied to any specific architecture. 27 | 28 | The bootloader will open the Graphics Output Protocol and Serial Protocol. A routine has been provided for drawing a test screen to demonstrate that the graphics output protocol has been loaded correctly. This can be toggled by setting the `DRAW_TEST_SCREEN` preprocessor directive at the top of the `src/bootloader/src/main.c` file. 29 | 30 | ## Kernel 31 | This repository contains a minimal x86-64 kernel for testing purposes. This is located within the `src/kernel` directory. It contains a basic UART implementation suitable for testing that the kernel has been correctly loaded. 32 | 33 | ## Feedback 34 | Feel free to direct any questions or feedback to me directly at `ajxs [at] panoptic.online` 35 | -------------------------------------------------------------------------------- /src/bootloader/src/include/graphics.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file graphics.h 3 | * @author ajxs 4 | * @date Aug 2019 5 | * @brief Functionality for working with the graphics protocol. 6 | * Contains functionality for initiating and working with the graphics protocol and 7 | * its associated framebuffers. 8 | */ 9 | 10 | #ifndef BOOTLOADER_GRAPHICS_H 11 | #define BOOTLOADER_GRAPHICS_H 1 12 | 13 | #include 14 | #include 15 | 16 | /** 17 | * @brief Graphics output service. 18 | * Holds variables necesssary for using the UEFI graphics output service. 19 | */ 20 | typedef struct s_uefi_graphics_service { 21 | EFI_HANDLE* handle_buffer; 22 | UINTN handle_count; 23 | } Uefi_Graphics_Service; 24 | 25 | /** 26 | * @brief Draws a rectangle onto the framebuffer. 27 | * Draws a rectangle onto the frame buffer of a particular protocol. 28 | * @param[in] protocol The protocol containing the framebuffer to draw to. 29 | * @param[in] _x The x coordinate to draw the rect to. 30 | * @param[in] _y The y coordinate to draw the rect to. 31 | * @param[in] width The width of the rectangle to draw. 32 | * @param[in] height The height of the rectangle to draw. 33 | * @param[in] color The color to draw. 34 | */ 35 | VOID draw_rect(IN EFI_GRAPHICS_OUTPUT_PROTOCOL* const protocol, 36 | IN const UINT16 _x, 37 | IN const UINT16 _y, 38 | IN const UINT16 _width, 39 | IN const UINT16 _height, 40 | IN const UINT32 color); 41 | 42 | /** 43 | * @brief Draws a test screen. 44 | * Draws a test screen which can be used to assess that the graphics output 45 | * protocol is functioning correctly. Draws to the provided framebuffer. 46 | * @param[in] protocol The protocol containing the framebuffer to draw to. 47 | */ 48 | VOID draw_test_screen(IN EFI_GRAPHICS_OUTPUT_PROTOCOL* const protocol); 49 | 50 | /** 51 | * @brief Closes the graphics output service. 52 | * Closes the graphics output service, freeing the handle buffer used by the 53 | * service. 54 | * @return The program status. 55 | * @retval EFI_SUCCESS If the function executed successfully. 56 | * @retval other Any other value is an EFI error code. 57 | */ 58 | EFI_STATUS close_graphic_output_service(void); 59 | 60 | /** 61 | * @brief Initialises the Graphics output service. 62 | * Initialises the graphics output service. Populates the handle buffer in the 63 | * graphics output service. 64 | * @return The program status. 65 | * @retval EFI_SUCCESS If the function executed successfully. 66 | * @retval other Any other value is an EFI error code. 67 | */ 68 | EFI_STATUS init_graphics_output_service(void); 69 | 70 | /** 71 | * @brief Set the graphics mode for a particular protocol. 72 | * Sets the graphics mode for a particular protocol handle. Sets the graphics 73 | * mode by searching all available modes on this protocol for one that matches 74 | * the target width/height. 75 | * @param[in] protocol The protocol to set the mode for. 76 | * @param[in] target_width The target width. 77 | * @param[in] target_height The target height. 78 | * @param[in] target_pixel_format The target pixel format. 79 | * @return The program status. 80 | * @retval EFI_SUCCESS If the function executed successfully. 81 | * @retval EFI_UNSUPPORTED if the specified mode cannot be found. 82 | * @retval other Any other value is an EFI error code. 83 | */ 84 | EFI_STATUS set_graphics_mode(IN EFI_GRAPHICS_OUTPUT_PROTOCOL* const protocol, 85 | IN const UINT32 target_width, 86 | IN const UINT32 target_height, 87 | IN const EFI_GRAPHICS_PIXEL_FORMAT target_pixel_format); 88 | 89 | #endif 90 | -------------------------------------------------------------------------------- /src/bootloader/src/serial.c: -------------------------------------------------------------------------------- 1 | /** 2 | * @file serial.c 3 | * @author ajxs 4 | * @date Aug 2019 5 | * @brief Serial IO functionality. 6 | * Contains functionality for serial IO. 7 | */ 8 | 9 | #include 10 | #include 11 | #include 12 | 13 | #include 14 | #include 15 | #include 16 | #include 17 | 18 | 19 | /** 20 | * configure_serial_protocol 21 | */ 22 | EFI_STATUS configure_serial_protocol(IN EFI_SERIAL_IO_PROTOCOL* const protocol) 23 | { 24 | /** The program status. */ 25 | EFI_STATUS status; 26 | 27 | #ifdef DEBUG 28 | debug_print_line(L"Debug: Configuring serial IO protocol\n"); 29 | #endif 30 | 31 | status = uefi_call_wrapper(protocol->SetAttributes, 7, 32 | protocol, 0, 0, 0, 0, 0, DefaultStopBits); 33 | if(EFI_ERROR(status)) { 34 | debug_print_line(L"Error: Error configuring Serial Protocol: %s\n", 35 | get_efi_error_message(status)); 36 | 37 | return status; 38 | } 39 | 40 | return EFI_SUCCESS; 41 | } 42 | 43 | 44 | /** 45 | * init_serial_service 46 | */ 47 | EFI_STATUS init_serial_service(void) 48 | { 49 | /** The program status. */ 50 | EFI_STATUS status; 51 | 52 | #ifdef DEBUG 53 | debug_print_line(L"Debug: Initialising Serial service\n"); 54 | #endif 55 | 56 | status = uefi_call_wrapper(gBS->LocateProtocol, 3, 57 | &gEfiSerialIoProtocolGuid, NULL, &serial_service.protocol); 58 | if(EFI_ERROR(status)) { 59 | debug_print_line(L"Error: Error locating Serial Protocol: %s\n", 60 | get_efi_error_message(status)); 61 | 62 | return status; 63 | } 64 | 65 | #ifdef DEBUG 66 | debug_print_line(L"Debug: Located Serial Protocol\n"); 67 | #endif 68 | 69 | status = configure_serial_protocol(serial_service.protocol); 70 | if(EFI_ERROR(status)) { 71 | return status; 72 | } 73 | 74 | return EFI_SUCCESS; 75 | } 76 | 77 | 78 | /** 79 | * print_to_serial_out 80 | */ 81 | EFI_STATUS print_to_serial_out(IN EFI_SERIAL_IO_PROTOCOL* const protocol, 82 | IN CHAR16* line) 83 | { 84 | /** The program status. */ 85 | EFI_STATUS status; 86 | /** The size of the buffer being printed. */ 87 | UINTN buffer_size = 0; 88 | /** The length of the line to be printed. */ 89 | UINTN line_length = 0; 90 | 91 | // If the supplied protocol has not been loaded properly or the supplied 92 | // string is empty, raise an exception. 93 | if(protocol == NULL || 94 | line == NULL) { 95 | return EFI_INVALID_PARAMETER; 96 | } 97 | 98 | line_length = StrLen(line); 99 | 100 | // Check if the string length will overflowed the maximum buffer size. 101 | if(line_length > MAX_SERIAL_OUT_STRING_LENGTH) { 102 | return EFI_BAD_BUFFER_SIZE; 103 | } 104 | 105 | // If the string is 0 length, raise an exception. 106 | if(line_length == 0) { 107 | return EFI_INVALID_PARAMETER; 108 | } 109 | 110 | // Set the buffer size to be printed to the line length. 111 | // This will be checked afterwards to determine if the full line was printed. 112 | // Buffer size is double the line length to take into account the double 113 | // width unicode characters. 114 | buffer_size = line_length * 2; 115 | 116 | status = uefi_call_wrapper(protocol->Write, 3, 117 | protocol, &buffer_size, (VOID*)line); 118 | if(EFI_ERROR(status)) { 119 | // Fall back to using EFI built-in `debug_print_line` function in this case. 120 | debug_print_line(L"Error: Error writing to serial protocol: %s\n", 121 | get_efi_error_message(status)); 122 | 123 | return status; 124 | } 125 | 126 | // Check if the actual printed length is equal to the expected length. 127 | if(buffer_size != (line_length * 2)) { 128 | debug_print_line(L"Error: Full string not printed to serial protocol\n"); 129 | return EFI_DEVICE_ERROR; 130 | } 131 | 132 | return EFI_SUCCESS; 133 | } 134 | -------------------------------------------------------------------------------- /src/bootloader/src/include/bootloader.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file bootloader.h 3 | * @author ajxs 4 | * @date Aug 2019 5 | * @brief Core bootloader functionality. 6 | * Functions that are part of the core bootloader functionality. 7 | */ 8 | 9 | #ifndef BOOTLOADER_H 10 | #define BOOTLOADER_H 1 11 | 12 | #include 13 | #include 14 | 15 | #include 16 | #include 17 | #include 18 | 19 | /** The path to the kernel executable binary on the bootable media. */ 20 | #define KERNEL_EXECUTABLE_PATH L"\\kernel.elf" 21 | 22 | /** 23 | * Whether to prompt, and wait for user input before rebooting in the case 24 | * of an unrecoverable error. 25 | */ 26 | #define PROMPT_FOR_INPUT_BEFORE_REBOOT_ON_FATAL_ERROR 1 27 | 28 | typedef struct s_boot_video_info { 29 | VOID* framebuffer_pointer; 30 | UINT32 horizontal_resolution; 31 | UINT32 vertical_resolution; 32 | UINT32 pixels_per_scaline; 33 | } Kernel_Boot_Video_Mode_Info; 34 | 35 | /** 36 | * @brief Kernel boot info struct. 37 | * Contains information passed to the kernel at boot time. 38 | * This should be kept separate from the kernel implementation to improve the 39 | * portability of the implementation: 40 | * This definition uses the `EFI_MEMORY_DESCRIPTOR` and `UINTN` types so that it will 41 | * automatically use the correct types for the target architecture. The corresponding 42 | * definition within the kernel should have more architecture-specific types. 43 | */ 44 | typedef struct s_boot_info { 45 | EFI_MEMORY_DESCRIPTOR* memory_map; 46 | UINTN memory_map_size; 47 | UINTN memory_map_descriptor_size; 48 | Kernel_Boot_Video_Mode_Info video_mode_info; 49 | } Kernel_Boot_Info; 50 | 51 | /** 52 | * @brief The main UEFI executable entry. 53 | * The main bootloader entry point. 54 | * @param[in] ImageHandle The firmware allocated handle for the EFI image. 55 | * @param[in] SystemTable A pointer to the EFI System Table. 56 | * @return The program status. 57 | * @retval EFI_SUCCESS The function executed successfully. 58 | * @retval other A fatal error occurred during the execution of the 59 | * main bootloader function. 60 | */ 61 | EFI_STATUS EFIAPI efi_main (EFI_HANDLE ImageHandle, 62 | EFI_SYSTEM_TABLE* SystemTable); 63 | 64 | /** 65 | * @brief Loads the Kernel binary image into memory. 66 | * This will load the Kernel binary image and validates it. If the kernel binary 67 | * is valid its executable program segments are loaded into memory. 68 | * @param[in] root_file_system The root file system FILE entity to load the 69 | * kernel binary from. 70 | * @param[in] kernel_image_filename The kernel filename on the boot partition. 71 | * @param[out] kernel_entry_point The virtual memory address of the kernel's 72 | * entry point. 73 | * @return The program status. 74 | * @retval EFI_SUCCESS If the function executed successfully. 75 | * @retval other Any other value is an EFI error code. 76 | */ 77 | EFI_STATUS load_kernel_image(IN EFI_FILE* const root_file_system, 78 | IN CHAR16* const kernel_image_filename, 79 | OUT EFI_VIRTUAL_ADDRESS* kernel_entry_point); 80 | 81 | /** 82 | * @brief Pauses the program while waiting for input. 83 | * Pauses the program while waiting for a keystroke from console in, capturing 84 | * the input to a key parameter. 85 | * @param[out] key A pointer to the entity to capture the keypress data in. 86 | * @return The program status. 87 | * @retval EFI_SUCCESS If the function executed successfully. 88 | * @retval other Any other value is an EFI error code. 89 | */ 90 | EFI_STATUS wait_for_input(EFI_INPUT_KEY* key); 91 | 92 | /** 93 | * @brief The global graphics service entity. 94 | * Contains a collection of EFI handles supporting the Graphics Output Protocol. 95 | * Used for accessing the framebuffers of each supporting device. 96 | */ 97 | extern Uefi_Graphics_Service graphics_service; 98 | /** 99 | * @brief The Simple File System service. 100 | * Contains the Simple File System protocol, used to interact with file system entities. 101 | */ 102 | extern Uefi_File_System_Service file_system_service; 103 | /** 104 | * @brief The Serial IO service. 105 | * The Serial IO. Used for outputting text to a serial port. 106 | */ 107 | extern Uefi_Serial_Service serial_service; 108 | 109 | #endif 110 | -------------------------------------------------------------------------------- /STYLEGUIDE.md: -------------------------------------------------------------------------------- 1 | # Coding Styleguide 2 | 3 | 4 | **Rule:** Use snake case for variables. 5 | 6 | **Rationale:** Improves ease of reading variable names quickly. 7 | 8 | **Rule:** Observe `const` correctness at all times. 9 | 10 | **Rule:** Provide initial values for declared variables where possible. 11 | 12 | **Rule:** Only create a single variable per line. 13 | 14 | **Rationale:** Resolves ambiguity of asterix position when declaring multiple pointer variables on a single line. Ensures a predictable standard for documentation of variables. 15 | 16 | **Rule:** Never return in-band error indicators. Instead use either booleans to indicate the success of the function, or better yet use dedicated enumerated types to return detailed status information. Instead of returning a value directly, use a pointer to return the value instead. 17 | **Rationale:** In-band error indicators returned from functions are prone to misinterpretation and are inflexible. Using dedicated types allows for the returning of detailed statuses if needed. 18 | **Example:** 19 | ```c 20 | // NO. 21 | int32_t read_number_from_port() 22 | { 23 | if(!port_ready()) { 24 | return -1; 25 | } 26 | 27 | return (int32_t)*port_ptr; 28 | } 29 | 30 | // YES. 31 | bool read_number_from_port(uint32_t* output) 32 | { 33 | if(!port_ready()) { 34 | return false; 35 | } 36 | 37 | *output = (uint32_t)*port_ptr; 38 | 39 | return true; 40 | } 41 | 42 | // BETTER. 43 | typedef enum { 44 | STATUS_SUCCESS, 45 | STATUS_FAILURE, 46 | STATUS_BUSY 47 | } Program_Status; 48 | 49 | Program_Status read_number_from_port(uint32_t* output) 50 | { 51 | if(!port_ready()) { 52 | return STATUS_BUSY; 53 | } 54 | 55 | *output = (uint32_t)*port_ptr; 56 | 57 | return STATUS_SUCCESS; 58 | } 59 | ``` 60 | 61 | **Rule:** When possible, declare any required variables at the top of each code block. Exception being when this would make the code less readable. 62 | 63 | **Rationale:** This makes it easier for another developer to gauge what variables are used in a given area of the code. As well as providing for consistent documentation. 64 | 65 | **Rule:** Document each variable above its declaration. 66 | 67 | **Rationale:** Provides a useful introduction to the use of each variable. 68 | 69 | **Example:** 70 | ```c 71 | /** The file being loaded by the application. */ 72 | FILE* file; 73 | ``` 74 | 75 | **Rule:** Use descriptive names with minimal use of abbreviations. When abbreviating names, use standard common abbreviations only. Such as: 76 | - `dir` = Directory 77 | - `idx` = Index 78 | - `n_` = Number of ( prefix ) 79 | - `_t` = Type of ( suffix ) 80 | - `_len` = Length of ( suffix ) 81 | - `_addr` = Address of ( suffix ) 82 | - `_ptr` = Pointer to ( suffix ) 83 | 84 | **Exception:** Conventional usage of simple identifiers (i, x, y, p, etc.) in small scopes and for iterator variables generally leads to cleaner code. 85 | 86 | **Rationale:** Eases the burden of understanding a variable's usage. Together with declaring each variable at the top of the scope block, this makes understanding the flow of data much easier. 87 | 88 | **Example:** 89 | ```c 90 | // YES. 91 | uint8_t n_dir_entries = 0; 92 | uint32_t entry_name_len = 255; 93 | uintptr_t uart_addr = 0x800000C0; 94 | ``` 95 | 96 | **Rule:** For qualifying a type as a pointer, attach the asterix to the type, not the variable name. 97 | 98 | **Rationale:** This allows for a consistent style when casting `void` data into structs. 99 | 100 | **Example:** 101 | ```c 102 | // YES 103 | FILE* file; 104 | // NO 105 | FILE *file; 106 | ``` 107 | 108 | **Rule:** Place comments above the relevant line of code where possible. If placing a comment on the same line that it documents, use space characters to align the comment, not TABs. 109 | 110 | **Rule:** Use two line breaks after the end of a function body before the next line of code. 111 | 112 | **Rule:** Use Doxygen-style inline documentation on all function declarations. Apply documentation to the declaration in the header files. 113 | **Example:** 114 | ```c 115 | /** 116 | * @brief brief description. 117 | * 118 | * Longer description 119 | * @param thing_ptr A pointer to the thing. 120 | * @return The status of the program. 121 | * @warning This function modifies the sections. 122 | */ 123 | Program_Status do_the_thing(Pointer_Type* thing_ptr); 124 | 125 | ``` 126 | 127 | **Rule:** In function declarations, place each parameter on a new line and the brace on the following line. 128 | 129 | **Example:** 130 | ```c 131 | /** retro_encabulate */ 132 | Program_Status retro_encabulate(uint8_t number, 133 | const char *string, 134 | bool flag) 135 | { 136 | // ... 137 | } 138 | ``` 139 | 140 | **Rule:** Use a standalone variable for a conditional if it is over 100 chars in length. 141 | 142 | **Rationale:** This ensures that conditional branching logic is legible. 143 | 144 | **Example:** 145 | ```c 146 | // NO 147 | if((something_long_and_complicated == (thing->bit_field & LONG_DESCRIPTIVE_BIT_MASK)) && 148 | (another_sentinel_var == 16)) { 149 | //... 150 | } 151 | 152 | // YES 153 | /** Condition deciding whether to branch. */ 154 | bool shouldEncabulate = (something_long_and_complicated == 155 | (thing->bit_field & LONG_DESCRIPTIVE_BIT_MASK)) && (another_sentinel_var == 16); 156 | 157 | if(shouldEncabulate) { 158 | //... 159 | } 160 | ``` 161 | -------------------------------------------------------------------------------- /src/bootloader/src/include/elf.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file elf.h 3 | * @author ajxs 4 | * @date Aug 2019 5 | * @brief Functionality for working with ELF executable files. 6 | * Contains functionality to assist in loading and validating ELF executable 7 | * files. This functionality is essential to the ELF executable loader. 8 | */ 9 | 10 | #ifndef BOOTLOADER_ELF_H 11 | #define BOOTLOADER_ELF_H 1 12 | 13 | #include 14 | #include 15 | 16 | 17 | #define EI_NIDENT 16 18 | 19 | #define EI_MAG0 0 20 | #define EI_MAG1 0x1 21 | #define EI_MAG2 0x2 22 | #define EI_MAG3 0x3 23 | #define EI_CLASS 0x4 24 | #define EI_DATA 0x5 25 | #define EI_VERSION 0x6 26 | #define EI_OSABI 0x7 27 | #define EI_ABIVERSION 0x8 28 | 29 | #define PT_NULL 0 30 | #define PT_LOAD 1 31 | #define PT_DYNAMIC 2 32 | #define PT_INTERP 3 33 | #define PT_NOTE 4 34 | #define PT_SHLIB 5 35 | #define PT_PHDR 6 36 | #define PT_TLS 7 37 | 38 | 39 | /** 40 | * @brief The ELF file class. 41 | */ 42 | typedef enum e_file_class { 43 | ELF_FILE_CLASS_NONE = 0, 44 | ELF_FILE_CLASS_32 = 1, 45 | ELF_FILE_CLASS_64 = 2, 46 | } Elf_File_Class; 47 | 48 | /** 49 | * @brief The 32-bit ELF header. 50 | */ 51 | typedef struct s_elf32_hdr { 52 | unsigned char e_ident[EI_NIDENT]; 53 | UINT16 e_type; 54 | UINT16 e_machine; 55 | UINT32 e_version; 56 | UINT32 e_entry; 57 | UINT32 e_phoff; 58 | UINT32 e_shoff; 59 | UINT32 e_flags; 60 | UINT16 e_ehsize; 61 | UINT16 e_phentsize; 62 | UINT16 e_phnum; 63 | UINT16 e_shentsize; 64 | UINT16 e_shnum; 65 | UINT16 e_shstrndx; 66 | } Elf32_Ehdr; 67 | 68 | /** 69 | * @brief The 64-bit ELF header. 70 | */ 71 | typedef struct s_elf64_hdr { 72 | unsigned char e_ident[EI_NIDENT]; 73 | UINT16 e_type; 74 | UINT16 e_machine; 75 | UINT32 e_version; 76 | UINT64 e_entry; 77 | UINT64 e_phoff; 78 | UINT64 e_shoff; 79 | UINT32 e_flags; 80 | UINT16 e_ehsize; 81 | UINT16 e_phentsize; 82 | UINT16 e_phnum; 83 | UINT16 e_shentsize; 84 | UINT16 e_shnum; 85 | UINT16 e_shstrndx; 86 | } Elf64_Ehdr; 87 | 88 | /** 89 | * @brief The 32-bit ELF program header. 90 | */ 91 | typedef struct s_elf32_phdr { 92 | UINT32 p_type; 93 | UINT32 p_offset; 94 | UINT32 p_vaddr; 95 | UINT32 p_paddr; 96 | UINT32 p_filesz; 97 | UINT32 p_memsz; 98 | UINT32 p_flags; 99 | UINT32 p_align; 100 | } Elf32_Phdr; 101 | 102 | /** 103 | * @brief The 64-bit ELF program header. 104 | */ 105 | typedef struct s_elf64_phdr { 106 | UINT32 p_type; 107 | UINT32 p_flags; 108 | UINT64 p_offset; 109 | UINT64 p_vaddr; 110 | UINT64 p_paddr; 111 | UINT64 p_filesz; 112 | UINT64 p_memsz; 113 | UINT64 p_align; 114 | } Elf64_Phdr; 115 | 116 | /** 117 | * @brief Prints ELF file information. 118 | * Prints information on the ELF file, as well as its program headers. 119 | * @param[in] header_ptr A pointer to the ELF header buffer. 120 | * @param[in] program_headers_ptr A pointer to the ELF program headers buffer. 121 | */ 122 | VOID print_elf_file_info(IN VOID* const header_ptr, 123 | IN VOID* const program_headers_ptr); 124 | 125 | /** 126 | * @brief Reads the ELF file headers. 127 | * Reads the ELF file header and program headers into memory. 128 | * @param[in] kernel_img_file The Kernel EFI file entity to read from. 129 | * @param[in] file_class The ELF file class, whether the program 130 | * is 32 or 64bit. 131 | * @param[out] kernel_header_buffer The buffer to read the kernel header into. 132 | * @param[out] kernel_program_headers_buffer The buffer to read the 133 | * kernel program headers into. 134 | * @return The program status. 135 | * @retval EFI_SUCCESS If the function executed successfully. 136 | * @retval other Any other value is an EFI error code. 137 | */ 138 | EFI_STATUS read_elf_file(IN EFI_FILE* const kernel_img_file, 139 | IN Elf_File_Class const file_class, 140 | OUT VOID** kernel_header_buffer, 141 | OUT VOID** kernel_program_headers_buffer); 142 | 143 | /** 144 | * @brief Reads the identity buffer of an ELF file. 145 | * Reads the identity buffer from the ELF header, which is used to both validate 146 | * that the file is a valid ELF executable, as well as read the ELF file class 147 | * value. 148 | * @param[in] kernel_img_file The kernel binary to read the file class from. 149 | * @param[out] elf_identity_buffer A pointer-to-pointer to the identity buffer 150 | * to read the buffer into. 151 | * @return The program status. 152 | * @retval EFI_SUCCESS If the function executed successfully. 153 | * @retval other Any other value is an EFI error code. 154 | */ 155 | EFI_STATUS read_elf_identity(IN EFI_FILE* const kernel_img_file, 156 | OUT UINT8** elf_identity_buffer); 157 | 158 | /** 159 | * @brief Validates the ELF file identity. 160 | * Validates whether the ELF identity correctly identifies an ELF file. 161 | * @param[in] elf_identity_buffer The ELF identity buffer to validate. 162 | * @return The result of the validation. 163 | * @retval EFI_SUCCESS Indicates a valid ELF file. 164 | * @retval EFI_INVALID_PARAMETER If the ELF file identity buffer is invalid. 165 | * @retval EFI_UNSUPPORTED If the identity buffer indicates an unsupported 166 | * filetype. 167 | * @retval EFI_INCOMPATIBLE_VERSION If the identity buffer indicates an unsupported 168 | * file type. 169 | */ 170 | EFI_STATUS validate_elf_identity(IN UINT8* const elf_identity_buffer); 171 | 172 | #endif 173 | -------------------------------------------------------------------------------- /src/bootloader/src/graphics.c: -------------------------------------------------------------------------------- 1 | /** 2 | * @file graphics.c 3 | * @author ajxs 4 | * @date Aug 2019 5 | * @brief Functionality for working with the graphics protocol. 6 | * Contains functionality for initiating and working with the graphics protocol and 7 | * its associated framebuffers. 8 | */ 9 | 10 | #include 11 | #include 12 | 13 | #include 14 | #include 15 | #include 16 | #include 17 | 18 | #define TEST_SCREEN_COL_NUM 4 19 | #define TEST_SCREEN_ROW_NUM 3 20 | #define TEST_SCREEN_TOTAL_TILES TEST_SCREEN_COL_NUM * TEST_SCREEN_ROW_NUM 21 | #define TEST_SCREEN_PRIMARY_COLOUR 0x00FF4000 22 | #define TEST_SCREEN_SECONDARY_COLOUR 0x00FF80BF 23 | 24 | /** 25 | * @brief Finds a video mode. 26 | * Finds a particular video mode by its width, height and pixel format. 27 | * Tests all video modes copatible with the provided protocol, populating the 28 | * `video_mode` variable on success. 29 | * @param[in] protocol The protocol to find the video mode in. 30 | * @param[in] target_width The target width to search for. 31 | * @param[in] target_height The target height to search for. 32 | * @param[in] target_pixel_format The target pixel format to search for. 33 | * @param[out] video_mode The video mode variable to populate. 34 | * @return The program status. 35 | * @retval EFI_SUCCESS If the function executed successfully. 36 | * @retval other Any other value is an EFI error code. 37 | */ 38 | EFI_STATUS find_video_mode(IN EFI_GRAPHICS_OUTPUT_PROTOCOL* const protocol, 39 | IN const UINT32 target_width, 40 | IN const UINT32 target_height, 41 | IN const EFI_GRAPHICS_PIXEL_FORMAT target_pixel_format, 42 | OUT UINTN* video_mode); 43 | 44 | 45 | /** 46 | * close_graphic_output_service 47 | */ 48 | EFI_STATUS close_graphic_output_service() 49 | { 50 | EFI_STATUS status = uefi_call_wrapper(gBS->FreePool, 1, 51 | graphics_service.handle_buffer); 52 | 53 | return status; 54 | } 55 | 56 | 57 | /** 58 | * draw_rect 59 | */ 60 | VOID draw_rect(IN EFI_GRAPHICS_OUTPUT_PROTOCOL* const protocol, 61 | IN const UINT16 _x, 62 | IN const UINT16 _y, 63 | IN const UINT16 width, 64 | IN const UINT16 height, 65 | IN const UINT32 color) 66 | { 67 | /** Pointer to the current pixel in the buffer. */ 68 | UINT32* at; 69 | 70 | UINT16 row = 0; 71 | UINT16 col = 0; 72 | for(row = 0; row < height; row++) { 73 | for(col = 0; col < width; col++) { 74 | at = (UINT32*)protocol->Mode->FrameBufferBase + _x + col; 75 | at += ((_y + row) * protocol->Mode->Info->PixelsPerScanLine); 76 | 77 | *at = color; 78 | } 79 | } 80 | } 81 | 82 | 83 | /** 84 | * draw_test_screen 85 | */ 86 | VOID draw_test_screen(IN EFI_GRAPHICS_OUTPUT_PROTOCOL* const protocol) 87 | { 88 | const UINT16 tile_width = protocol->Mode->Info->HorizontalResolution / 89 | TEST_SCREEN_COL_NUM; 90 | const UINT16 tile_height = protocol->Mode->Info->VerticalResolution / 91 | TEST_SCREEN_ROW_NUM; 92 | 93 | UINT8 p = 0; 94 | for(p = 0; p < TEST_SCREEN_TOTAL_TILES; p++) { 95 | UINT8 _x = p % TEST_SCREEN_COL_NUM; 96 | UINT8 _y = p / TEST_SCREEN_COL_NUM; 97 | 98 | UINT32 color = TEST_SCREEN_PRIMARY_COLOUR; 99 | if(((_y % 2) + _x) % 2) { 100 | color = TEST_SCREEN_SECONDARY_COLOUR; 101 | } 102 | 103 | draw_rect(protocol, tile_width * _x, tile_height * _y, 104 | tile_width, tile_height, color); 105 | } 106 | } 107 | 108 | 109 | /** 110 | * find_video_mode 111 | */ 112 | EFI_STATUS find_video_mode(IN EFI_GRAPHICS_OUTPUT_PROTOCOL* const protocol, 113 | IN const UINT32 target_width, 114 | IN const UINT32 target_height, 115 | IN const EFI_GRAPHICS_PIXEL_FORMAT target_pixel_format, 116 | OUT UINTN* video_mode) 117 | { 118 | /** Program status. */ 119 | EFI_STATUS status; 120 | /** The size of the video mode info struct. */ 121 | UINTN size_of_mode_info; 122 | /** The video mode info struct. */ 123 | EFI_GRAPHICS_OUTPUT_MODE_INFORMATION* mode_info; 124 | 125 | UINTN i = 0; 126 | for(i = 0; i < protocol->Mode->MaxMode; i++) { 127 | #ifdef DEBUG 128 | debug_print_line(L"Debug: Testing video mode: '%llu'\n", i); 129 | #endif 130 | 131 | status = uefi_call_wrapper(protocol->QueryMode, 4, 132 | protocol, i, &size_of_mode_info, &mode_info); 133 | if(EFI_ERROR(status)) { 134 | debug_print_line(L"Error: Error querying video mode: %s\n", 135 | get_efi_error_message(status)); 136 | 137 | return status; 138 | } 139 | 140 | if(mode_info->HorizontalResolution == target_width && 141 | mode_info->VerticalResolution == target_height && 142 | mode_info->PixelFormat == target_pixel_format) { 143 | 144 | #ifdef DEBUG 145 | debug_print_line(L"Debug: Matched video mode: '%llu' for '%lu*%lu*%u'\n", i, 146 | target_width, target_height, target_pixel_format); 147 | #endif 148 | 149 | *video_mode = i; 150 | return EFI_SUCCESS; 151 | } 152 | } 153 | 154 | return EFI_UNSUPPORTED; 155 | } 156 | 157 | 158 | /** 159 | * init_graphics_output_service 160 | */ 161 | EFI_STATUS init_graphics_output_service(void) 162 | { 163 | /** Program status. */ 164 | EFI_STATUS status; 165 | 166 | #ifdef DEBUG 167 | debug_print_line(L"Debug: Initialising Graphics Output Service\n"); 168 | #endif 169 | 170 | // Populate graphics service handle buffer. 171 | status = uefi_call_wrapper(gBS->LocateHandleBuffer, 5, 172 | ByProtocol, &gEfiGraphicsOutputProtocolGuid, NULL, 173 | &graphics_service.handle_count, &graphics_service.handle_buffer); 174 | if(EFI_ERROR(status)) { 175 | debug_print_line(L"Error: Error locating GOP handle buffer: %s\n", 176 | get_efi_error_message(status)); 177 | 178 | return status; 179 | } 180 | 181 | #ifdef DEBUG 182 | debug_print_line(L"Debug: Located GOP handle buffer with %u handles\n", 183 | graphics_service.handle_count); 184 | #endif 185 | 186 | return EFI_SUCCESS; 187 | } 188 | 189 | 190 | /** 191 | * set_graphics_mode 192 | */ 193 | EFI_STATUS set_graphics_mode(IN EFI_GRAPHICS_OUTPUT_PROTOCOL* const protocol, 194 | IN const UINT32 target_width, 195 | IN const UINT32 target_height, 196 | IN const EFI_GRAPHICS_PIXEL_FORMAT target_pixel_format) 197 | { 198 | /** Program status. */ 199 | EFI_STATUS status; 200 | /** The graphics mode number. */ 201 | UINTN graphics_mode_num = 0; 202 | 203 | status = find_video_mode(protocol, target_width, target_height, 204 | target_pixel_format, &graphics_mode_num); 205 | if(EFI_ERROR(status)) { 206 | // Error will already have been printed. 207 | return status; 208 | } 209 | 210 | status = uefi_call_wrapper(protocol->SetMode, 2, 211 | protocol, graphics_mode_num); 212 | if(EFI_ERROR(status)) { 213 | debug_print_line(L"Error: Error setting graphics mode: %s\n", 214 | get_efi_error_message(status)); 215 | 216 | return status; 217 | } 218 | 219 | return EFI_SUCCESS; 220 | } 221 | -------------------------------------------------------------------------------- /src/bootloader/src/main.c: -------------------------------------------------------------------------------- 1 | /** 2 | * @file main.c 3 | * @author ajxs 4 | * @date Aug 2019 5 | * @brief Bootloader entry point and main application. 6 | * The entry point for the application. Contains the main bootloader code that 7 | * initiates the loading of the Kernel executable. The main application is 8 | * contained within the `efi_main` function. 9 | */ 10 | 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | 24 | #define TARGET_SCREEN_WIDTH 1024 25 | #define TARGET_SCREEN_HEIGHT 768 26 | #define TARGET_PIXEL_FORMAT PixelBlueGreenRedReserved8BitPerColor 27 | 28 | /** 29 | * Graphics Service instance. 30 | * Refer to definition in bootloader.h 31 | */ 32 | Uefi_Graphics_Service graphics_service; 33 | /** 34 | * File System Service instance. 35 | * Refer to definition in bootloader.h 36 | */ 37 | Uefi_File_System_Service file_system_service; 38 | /** 39 | * Serial IO Service instance. 40 | * Refer to definition in bootloader.h 41 | */ 42 | Uefi_Serial_Service serial_service; 43 | 44 | /** 45 | * Whether to draw a test pattern to video output to test the graphics output 46 | * service. 47 | */ 48 | #define DRAW_TEST_SCREEN 1 49 | 50 | 51 | /** 52 | * efi_main 53 | */ 54 | EFI_STATUS EFIAPI efi_main(EFI_HANDLE ImageHandle, 55 | EFI_SYSTEM_TABLE* SystemTable) 56 | { 57 | /** Main bootloader application status. */ 58 | EFI_STATUS status; 59 | /** 60 | * Graphics output protocol instance. 61 | * This protocol instance will be opened from the active console out handle. 62 | */ 63 | EFI_GRAPHICS_OUTPUT_PROTOCOL* graphics_output_protocol = NULL; 64 | /** 65 | * The root file system entity. 66 | * This is the file root from which the kernel binary will be loaded. 67 | */ 68 | EFI_FILE* root_file_system; 69 | /** The kernel entry point address. */ 70 | EFI_PHYSICAL_ADDRESS* kernel_entry_point = 0; 71 | /** The EFI memory map descriptor. */ 72 | EFI_MEMORY_DESCRIPTOR* memory_map = NULL; 73 | /** The memory map key. */ 74 | UINTN memory_map_key = 0; 75 | /** The size of the memory map buffer. */ 76 | UINTN memory_map_size = 0; 77 | /** The memory map descriptor size. */ 78 | UINTN descriptor_size; 79 | /** The memory map descriptor. */ 80 | UINT32 descriptor_version; 81 | /** Function pointer to the kernel entry point. */ 82 | void (*kernel_entry)(Kernel_Boot_Info* boot_info); 83 | /** Boot info struct, passed to the kernel. */ 84 | Kernel_Boot_Info boot_info; 85 | /** Input key type used to capture user input. */ 86 | EFI_INPUT_KEY input_key; 87 | 88 | // Initialise service protocols to NULL, so that we can detect if they are 89 | // properly initialised in service functions. 90 | serial_service.protocol = NULL; 91 | file_system_service.protocol = NULL; 92 | 93 | // Initialise the UEFI lib. 94 | InitializeLib(ImageHandle, SystemTable); 95 | 96 | // Disable the watchdog timer. 97 | status = uefi_call_wrapper(gBS->SetWatchdogTimer, 4, 0, 0, 0, NULL); 98 | if(check_for_fatal_error(status, L"Error setting watchdog timer")) { 99 | return status; 100 | } 101 | 102 | // Reset console input. 103 | status = uefi_call_wrapper(ST->ConIn->Reset, 2, SystemTable->ConIn, FALSE); 104 | if(check_for_fatal_error(status, L"Error resetting console input")) { 105 | return status; 106 | } 107 | 108 | // Initialise the serial service. 109 | status = init_serial_service(); 110 | if(EFI_ERROR(status)) { 111 | if(status == EFI_NOT_FOUND) { 112 | #ifdef DEBUG 113 | debug_print_line(L"Debug: No serial device found\n"); 114 | #endif 115 | } else { 116 | debug_print_line(L"Fatal Error: Error initialising Serial IO service\n"); 117 | 118 | #if PROMPT_FOR_INPUT_BEFORE_REBOOT_ON_FATAL_ERROR 119 | debug_print_line(L"Press any key to reboot..."); 120 | wait_for_input(&input_key); 121 | #endif 122 | 123 | return status; 124 | } 125 | } 126 | 127 | // Initialise the graphics output service. 128 | status = init_graphics_output_service(); 129 | if(EFI_ERROR(status)) { 130 | if(status == EFI_NOT_FOUND) { 131 | #ifdef DEBUG 132 | debug_print_line(L"Debug: No graphics device found\n"); 133 | #endif 134 | } else { 135 | debug_print_line(L"Fatal Error: Error initialising Graphics service\n"); 136 | 137 | #if PROMPT_FOR_INPUT_BEFORE_REBOOT_ON_FATAL_ERROR 138 | debug_print_line(L"Press any key to reboot..."); 139 | wait_for_input(&input_key); 140 | #endif 141 | 142 | return status; 143 | } 144 | } 145 | 146 | 147 | // Open the graphics output protocol from the handle for the active console 148 | // output device and use it to draw the boot screen. 149 | // The console out handle exposed by the System Table is documented in the 150 | // UEFI Spec page 92. 151 | status = uefi_call_wrapper(gBS->OpenProtocol, 6, 152 | ST->ConsoleOutHandle, &gEfiGraphicsOutputProtocolGuid, 153 | &graphics_output_protocol, ImageHandle, 154 | NULL, EFI_OPEN_PROTOCOL_BY_HANDLE_PROTOCOL); 155 | if(EFI_ERROR(status)) { 156 | debug_print_line(L"Error: Failed to open the graphics output protocol on " 157 | L"the active console output device: %s\n", get_efi_error_message(status)); 158 | } 159 | 160 | // If we were able to obtain a protocol on the current output device handle 161 | // set the graphics mode to the target and draw the boot screen. 162 | if(graphics_output_protocol) { 163 | status = set_graphics_mode(graphics_output_protocol, TARGET_SCREEN_WIDTH, 164 | TARGET_SCREEN_HEIGHT, TARGET_PIXEL_FORMAT); 165 | if(EFI_ERROR(status)) { 166 | // Error has already been printed. 167 | return status; 168 | } 169 | 170 | #if DRAW_TEST_SCREEN != 0 171 | draw_test_screen(graphics_output_protocol); 172 | #endif 173 | } 174 | 175 | // Initialise the simple file system service. 176 | // This will be used to load the kernel binary. 177 | status = init_file_system_service(); 178 | if(EFI_ERROR(status)) { 179 | // Error has already been printed. 180 | return status; 181 | } 182 | 183 | status = uefi_call_wrapper(file_system_service.protocol->OpenVolume, 2, 184 | file_system_service.protocol, &root_file_system); 185 | if(check_for_fatal_error(status, L"Error opening root volume")) { 186 | return status; 187 | } 188 | 189 | #ifdef DEBUG 190 | debug_print_line(L"Debug: Loading Kernel image\n"); 191 | #endif 192 | 193 | status = load_kernel_image(root_file_system, KERNEL_EXECUTABLE_PATH, 194 | kernel_entry_point); 195 | if(EFI_ERROR(status)) { 196 | // In the case that loading the kernel image failed, the error message will 197 | // have already been printed. 198 | return status; 199 | } 200 | 201 | #ifdef DEBUG 202 | debug_print_line(L"Debug: Set Kernel Entry Point to: '0x%llx'\n", 203 | *kernel_entry_point); 204 | #endif 205 | 206 | boot_info.video_mode_info.framebuffer_pointer = 207 | (VOID*)graphics_output_protocol->Mode->FrameBufferBase; 208 | boot_info.video_mode_info.horizontal_resolution = 209 | graphics_output_protocol->Mode->Info->HorizontalResolution; 210 | boot_info.video_mode_info.vertical_resolution = 211 | graphics_output_protocol->Mode->Info->VerticalResolution; 212 | boot_info.video_mode_info.pixels_per_scaline = 213 | graphics_output_protocol->Mode->Info->PixelsPerScanLine; 214 | 215 | #ifdef DEBUG 216 | debug_print_line(L"Debug: Closing Graphics Output Service handles\n"); 217 | #endif 218 | 219 | status = close_graphic_output_service(); 220 | if(check_for_fatal_error(status, L"Error closing Graphics Output service")) { 221 | return status; 222 | } 223 | 224 | #ifdef DEBUG 225 | debug_print_line(L"Debug: Getting memory map and exiting boot services\n"); 226 | #endif 227 | 228 | // Get the memory map prior to exiting the boot service. 229 | status = get_memory_map((VOID**)&memory_map, &memory_map_size, 230 | &memory_map_key, &descriptor_size, &descriptor_version); 231 | if(EFI_ERROR(status)) { 232 | // Error has already been printed. 233 | return status; 234 | } 235 | 236 | debug_print_memory_map(memory_map, memory_map_size, descriptor_size); 237 | 238 | // Get the memory map prior to exiting the boot service. 239 | status = get_memory_map((VOID**)&memory_map, &memory_map_size, 240 | &memory_map_key, &descriptor_size, &descriptor_version); 241 | if(EFI_ERROR(status)) { 242 | // Error has already been printed. 243 | return status; 244 | } 245 | 246 | status = uefi_call_wrapper(gBS->ExitBootServices, 2, 247 | ImageHandle, memory_map_key); 248 | if(check_for_fatal_error(status, L"Error exiting boot services")) { 249 | return status; 250 | } 251 | 252 | // Set kernel boot info. 253 | boot_info.memory_map = memory_map; 254 | boot_info.memory_map_size = memory_map_size; 255 | boot_info.memory_map_descriptor_size = descriptor_size; 256 | 257 | // Cast pointer to kernel entry. 258 | kernel_entry = (void (*)(Kernel_Boot_Info*))*kernel_entry_point; 259 | // Jump to kernel entry. 260 | kernel_entry(&boot_info); 261 | 262 | // Return an error if this code is ever reached. 263 | return EFI_LOAD_ERROR; 264 | } 265 | 266 | 267 | /** 268 | * wait_for_input 269 | */ 270 | EFI_STATUS wait_for_input(OUT EFI_INPUT_KEY* key) { 271 | /** The program status. */ 272 | EFI_STATUS status; 273 | do { 274 | status = uefi_call_wrapper(ST->ConIn->ReadKeyStroke, 2, ST->ConIn, key); 275 | } while(status == EFI_NOT_READY); 276 | 277 | return status; 278 | } 279 | -------------------------------------------------------------------------------- /src/bootloader/src/loader.c: -------------------------------------------------------------------------------- 1 | /** 2 | * @file loader.c 3 | * @author ajxs 4 | * @date Aug 2019 5 | * @brief Functionality for loading the Kernel executable. 6 | * Contains functionality for loading the Kernel ELF executable. 7 | */ 8 | 9 | #include 10 | #include 11 | 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | 19 | /** 20 | * Whether to prompt, and wait for user input before rebooting in the case 21 | * of an unrecoverable error. 22 | */ 23 | #define PROMPT_FOR_INPUT_BEFORE_REBOOT_ON_FATAL_ERROR 1 24 | 25 | /** 26 | * load_segment 27 | */ 28 | EFI_STATUS load_segment(IN EFI_FILE* const kernel_img_file, 29 | IN EFI_PHYSICAL_ADDRESS const segment_file_offset, 30 | IN UINTN const segment_file_size, 31 | IN UINTN const segment_memory_size, 32 | IN EFI_PHYSICAL_ADDRESS const segment_physical_address) 33 | { 34 | /** Program status. */ 35 | EFI_STATUS status; 36 | /** Buffer to hold the segment data. */ 37 | VOID* program_data = NULL; 38 | /** The amount of data to read into the buffer. */ 39 | UINTN buffer_read_size = 0; 40 | /** The number of pages to allocate. */ 41 | UINTN segment_page_count = EFI_SIZE_TO_PAGES(segment_memory_size); 42 | /** The memory location to begin zero filling empty segment space. */ 43 | EFI_PHYSICAL_ADDRESS zero_fill_start = 0; 44 | /** The number of bytes to zero fill. */ 45 | UINTN zero_fill_count = 0; 46 | 47 | #ifdef DEBUG 48 | debug_print_line(L"Debug: Setting file pointer to segment " 49 | "offset '0x%llx'\n", segment_file_offset); 50 | #endif 51 | 52 | status = uefi_call_wrapper(kernel_img_file->SetPosition, 2, 53 | kernel_img_file, segment_file_offset); 54 | if(check_for_fatal_error(status, L"Error setting file pointer to segment offset")) { 55 | return status; 56 | } 57 | 58 | #ifdef DEBUG 59 | debug_print_line(L"Debug: Allocating %lu pages at address '0x%llx'\n", 60 | segment_page_count, segment_physical_address); 61 | #endif 62 | 63 | status = uefi_call_wrapper(gBS->AllocatePages, 4, 64 | AllocateAddress, EfiLoaderData, segment_page_count, 65 | (EFI_PHYSICAL_ADDRESS*)&segment_physical_address); 66 | if(check_for_fatal_error(status, L"Error allocating pages for ELF segment")) { 67 | return status; 68 | } 69 | 70 | if(segment_file_size > 0) { 71 | buffer_read_size = segment_file_size; 72 | 73 | #ifdef DEBUG 74 | debug_print_line(L"Debug: Allocating segment buffer with size '0x%llx'\n", 75 | buffer_read_size); 76 | #endif 77 | 78 | status = uefi_call_wrapper(gBS->AllocatePool, 3, 79 | EfiLoaderCode, buffer_read_size, (VOID**)&program_data); 80 | if(check_for_fatal_error(status, L"Error allocating kernel segment buffer")) { 81 | return status; 82 | } 83 | 84 | #ifdef DEBUG 85 | debug_print_line(L"Debug: Reading segment data with file size '0x%llx'\n", 86 | buffer_read_size); 87 | #endif 88 | 89 | status = uefi_call_wrapper(kernel_img_file->Read, 3, 90 | kernel_img_file, &buffer_read_size, (VOID*)program_data); 91 | if(check_for_fatal_error(status, L"Error reading segment data")) { 92 | return status; 93 | } 94 | 95 | #ifdef DEBUG 96 | debug_print_line(L"Debug: Copying segment to memory address '0x%llx'\n", 97 | segment_physical_address); 98 | #endif 99 | 100 | status = uefi_call_wrapper(gBS->CopyMem, 3, 101 | segment_physical_address, program_data, segment_file_size); 102 | if(check_for_fatal_error(status, L"Error copying program section into memory")) { 103 | return status; 104 | } 105 | 106 | #ifdef DEBUG 107 | debug_print_line(L"Debug: Freeing program section data buffer\n"); 108 | #endif 109 | 110 | status = uefi_call_wrapper(gBS->FreePool, 1, program_data); 111 | if(check_for_fatal_error(status, L"Error freeing program section")) { 112 | return status; 113 | } 114 | } 115 | 116 | // As per ELF Standard, if the size in memory is larger than the file size 117 | // the segment is mandated to be zero filled. 118 | // For more information on Refer to ELF standard page 34. 119 | zero_fill_start = segment_physical_address + segment_file_size; 120 | zero_fill_count = segment_memory_size - segment_file_size; 121 | 122 | if(zero_fill_count > 0) { 123 | #ifdef DEBUG 124 | debug_print_line(L"Debug: Zero-filling %llu bytes at address '0x%llx'\n", 125 | zero_fill_count, zero_fill_start); 126 | #endif 127 | 128 | status = uefi_call_wrapper(gBS->SetMem, 3, 129 | zero_fill_start, zero_fill_count, 0); 130 | if(check_for_fatal_error(status, L"Error zero filling segment")) { 131 | return status; 132 | } 133 | } 134 | 135 | return EFI_SUCCESS; 136 | } 137 | 138 | 139 | /** 140 | * load_program_segments 141 | */ 142 | EFI_STATUS load_program_segments(IN EFI_FILE* const kernel_img_file, 143 | IN Elf_File_Class const file_class, 144 | IN VOID* const kernel_header_buffer, 145 | IN VOID* const kernel_program_headers_buffer) 146 | { 147 | /** Program status. */ 148 | EFI_STATUS status; 149 | /** The number of program headers. */ 150 | UINT16 n_program_headers = 0; 151 | /** The number of segments loaded. */ 152 | UINT16 n_segments_loaded = 0; 153 | /** Program section iterator. */ 154 | UINTN p = 0; 155 | 156 | if(file_class == ELF_FILE_CLASS_32) { 157 | n_program_headers = ((Elf32_Ehdr*)kernel_header_buffer)->e_phnum; 158 | } else if(file_class == ELF_FILE_CLASS_64) { 159 | n_program_headers = ((Elf64_Ehdr*)kernel_header_buffer)->e_phnum; 160 | } 161 | 162 | // Exit if there are no executable sections in the kernel image. 163 | if(n_program_headers == 0) { 164 | debug_print_line( 165 | L"Fatal Error: No program segments to load in Kernel image\n" 166 | ); 167 | 168 | return EFI_INVALID_PARAMETER; 169 | } 170 | 171 | #ifdef DEBUG 172 | debug_print_line(L"Debug: Loading %u segments\n", n_program_headers); 173 | #endif 174 | 175 | 176 | if(file_class == ELF_FILE_CLASS_32) { 177 | /** Program headers pointer. */ 178 | Elf32_Phdr* program_headers = (Elf32_Phdr*)kernel_program_headers_buffer; 179 | 180 | for(p = 0; p < n_program_headers; p++) { 181 | if(program_headers[p].p_type == PT_LOAD) { 182 | status = load_segment(kernel_img_file, 183 | program_headers[p].p_offset, 184 | program_headers[p].p_filesz, 185 | program_headers[p].p_memsz, 186 | program_headers[p].p_paddr); 187 | if(EFI_ERROR(status)) { 188 | // Error has already been printed in the case that loading an 189 | // individual segment failed. 190 | return status; 191 | } 192 | 193 | // Increment the number of segments lodaed. 194 | n_segments_loaded++; 195 | } 196 | } 197 | } else if(file_class == ELF_FILE_CLASS_64) { 198 | /** Program headers pointer. */ 199 | Elf64_Phdr* program_headers = (Elf64_Phdr*)kernel_program_headers_buffer; 200 | 201 | for(p = 0; p < n_program_headers; p++) { 202 | if(program_headers[p].p_type == PT_LOAD){ 203 | status = load_segment(kernel_img_file, 204 | program_headers[p].p_offset, 205 | program_headers[p].p_filesz, 206 | program_headers[p].p_memsz, 207 | program_headers[p].p_paddr); 208 | if(EFI_ERROR(status)) { 209 | return status; 210 | } 211 | 212 | n_segments_loaded++; 213 | } 214 | } 215 | } 216 | 217 | // If we have found no loadable segments, raise an exception. 218 | if(n_segments_loaded == 0) { 219 | debug_print_line(L"Fatal Error: No loadable program segments "); 220 | debug_print_line(L"found in Kernel image\n"); 221 | 222 | return EFI_NOT_FOUND; 223 | } 224 | 225 | return EFI_SUCCESS; 226 | } 227 | 228 | 229 | /** 230 | * load_kernel_image 231 | */ 232 | EFI_STATUS load_kernel_image(IN EFI_FILE* const root_file_system, 233 | IN CHAR16* const kernel_image_filename, 234 | OUT EFI_VIRTUAL_ADDRESS* kernel_entry_point) 235 | { 236 | /** Program status. */ 237 | EFI_STATUS status; 238 | /** The kernel file handle. */ 239 | EFI_FILE* kernel_img_file; 240 | /** The kernel ELF header buffer. */ 241 | VOID* kernel_header = NULL; 242 | /** The kernel program headers buffer. */ 243 | VOID* kernel_program_headers = NULL; 244 | /** The ELF file identity buffer. */ 245 | UINT8* elf_identity_buffer = NULL; 246 | /** The ELF file class. */ 247 | Elf_File_Class file_class = ELF_FILE_CLASS_NONE; 248 | 249 | #ifdef DEBUG 250 | debug_print_line(L"Debug: Reading kernel image file\n"); 251 | #endif 252 | 253 | status = uefi_call_wrapper(root_file_system->Open, 5, 254 | root_file_system, &kernel_img_file, kernel_image_filename, 255 | EFI_FILE_MODE_READ, EFI_FILE_READ_ONLY); 256 | if(check_for_fatal_error(status, L"Error opening kernel file")) { 257 | return status; 258 | } 259 | 260 | // Read ELF Identity. 261 | // From here we can validate the ELF executable, as well as determine the 262 | // file class. 263 | status = read_elf_identity(kernel_img_file, &elf_identity_buffer); 264 | if(check_for_fatal_error(status, L"Error reading executable identity")) { 265 | return status; 266 | } 267 | 268 | file_class = elf_identity_buffer[EI_CLASS]; 269 | 270 | // Validate the ELF file. 271 | status = validate_elf_identity(elf_identity_buffer); 272 | if(EFI_ERROR(status)) { 273 | // Error message printed in validation function. 274 | return status; 275 | } 276 | 277 | #ifdef DEBUG 278 | debug_print_line(L"Debug: ELF header is valid\n"); 279 | #endif 280 | 281 | // Free identity buffer. 282 | status = uefi_call_wrapper(gBS->FreePool, 1, elf_identity_buffer); 283 | if(check_for_fatal_error(status, L"Error freeing kernel identity buffer")) { 284 | return status; 285 | } 286 | 287 | 288 | // Read the ELF file and program headers. 289 | status = read_elf_file(kernel_img_file, file_class, 290 | &kernel_header, &kernel_program_headers); 291 | if(check_for_fatal_error(status, L"Error reading ELF file")) { 292 | return status; 293 | } 294 | 295 | #ifdef DEBUG 296 | print_elf_file_info(kernel_header, kernel_program_headers); 297 | #endif 298 | 299 | // Set the kernel entry point to the address specified in the ELF header. 300 | if(file_class == ELF_FILE_CLASS_32) { 301 | *kernel_entry_point = ((Elf32_Ehdr*)kernel_header)->e_entry; 302 | } else if(file_class == ELF_FILE_CLASS_64) { 303 | *kernel_entry_point = ((Elf64_Ehdr*)kernel_header)->e_entry; 304 | } 305 | 306 | status = load_program_segments(kernel_img_file, file_class, 307 | kernel_header, kernel_program_headers); 308 | if(EFI_ERROR(status)) { 309 | // In the case that loading the kernel segments failed, the error message will 310 | // have already been printed. 311 | return status; 312 | } 313 | 314 | // Cleanup. 315 | #ifdef DEBUG 316 | debug_print_line(L"Debug: Closing kernel binary\n"); 317 | #endif 318 | 319 | status = uefi_call_wrapper(kernel_img_file->Close, 1, kernel_img_file); 320 | if(check_for_fatal_error(status, L"Error closing kernel image")) { 321 | return status; 322 | } 323 | 324 | #ifdef DEBUG 325 | debug_print_line(L"Debug: Freeing kernel header buffer\n"); 326 | #endif 327 | 328 | status = uefi_call_wrapper(gBS->FreePool, 1, (VOID*)kernel_header); 329 | if(check_for_fatal_error(status, L"Error freeing kernel header buffer")) { 330 | return status; 331 | } 332 | 333 | #ifdef DEBUG 334 | debug_print_line(L"Debug: Freeing kernel program header buffer\n"); 335 | #endif 336 | 337 | status = uefi_call_wrapper(gBS->FreePool, 1, (VOID*)kernel_program_headers); 338 | if(check_for_fatal_error(status, L"Error freeing kernel program headers buffer")) { 339 | return status; 340 | } 341 | 342 | 343 | return status; 344 | } 345 | -------------------------------------------------------------------------------- /src/bootloader/src/elf.c: -------------------------------------------------------------------------------- 1 | /** 2 | * @file elf.c 3 | * @author ajxs 4 | * @date Aug 2019 5 | * @brief Functionality for working with ELF executable files. 6 | * Contains functionality to assist in loading and validating ELF executable 7 | * files. This functionality is essential to the ELF executable loader. 8 | */ 9 | 10 | #include 11 | #include 12 | 13 | #include 14 | #include 15 | #include 16 | #include 17 | 18 | 19 | /** 20 | * print_elf_file_info 21 | */ 22 | VOID print_elf_file_info(IN VOID* const header_ptr, 23 | IN VOID* const program_headers_ptr) 24 | { 25 | /** 26 | * The header pointer cast to a 32bit ELF Header so that we can read the 27 | * header and determine the file type. Then cast to a 64bit header for 28 | * specific fields if necessary. 29 | */ 30 | Elf32_Ehdr* header = (Elf32_Ehdr*)header_ptr; 31 | Elf64_Ehdr* header64 = (Elf64_Ehdr*)header_ptr; 32 | 33 | debug_print_line(L"Debug: ELF Header Info:\n"); 34 | 35 | debug_print_line(L" Magic: "); 36 | UINTN i = 0; 37 | for(i = 0; i < 4; i++) { 38 | debug_print_line(L"0x%x ", header->e_ident[i]); 39 | } 40 | debug_print_line(L"\n"); 41 | 42 | debug_print_line(L" Class: "); 43 | if(header->e_ident[EI_CLASS] == ELF_FILE_CLASS_32) { 44 | debug_print_line(L"32bit"); 45 | } else if(header->e_ident[EI_CLASS] == ELF_FILE_CLASS_64) { 46 | debug_print_line(L"64bit"); 47 | } 48 | debug_print_line(L"\n"); 49 | 50 | debug_print_line(L" Endianness: "); 51 | if(header->e_ident[EI_DATA] == 1) { 52 | debug_print_line(L"Little-Endian"); 53 | } else if(header->e_ident[EI_DATA] == 2) { 54 | debug_print_line(L"Big-Endian"); 55 | } 56 | debug_print_line(L"\n"); 57 | 58 | debug_print_line(L" Version: 0x%x\n", 59 | header->e_ident[EI_VERSION]); 60 | 61 | debug_print_line(L" OS ABI: "); 62 | if(header->e_ident[EI_OSABI] == 0x00) { 63 | debug_print_line(L"System V"); 64 | } else if(header->e_ident[EI_OSABI] == 0x01) { 65 | debug_print_line(L"HP-UX"); 66 | } else if(header->e_ident[EI_OSABI] == 0x02) { 67 | debug_print_line(L"NetBSD"); 68 | } else if(header->e_ident[EI_OSABI] == 0x03) { 69 | debug_print_line(L"Linux"); 70 | } else if(header->e_ident[EI_OSABI] == 0x04) { 71 | debug_print_line(L"GNU Hurd"); 72 | } else if(header->e_ident[EI_OSABI] == 0x06) { 73 | debug_print_line(L"Solaris"); 74 | } else if(header->e_ident[EI_OSABI] == 0x07) { 75 | debug_print_line(L"AIX"); 76 | } else if(header->e_ident[EI_OSABI] == 0x08) { 77 | debug_print_line(L"IRIX"); 78 | } else if(header->e_ident[EI_OSABI] == 0x09) { 79 | debug_print_line(L"FreeBSD"); 80 | } else if(header->e_ident[EI_OSABI] == 0x0A) { 81 | debug_print_line(L"Tru64"); 82 | } else if(header->e_ident[EI_OSABI] == 0x0B) { 83 | debug_print_line(L"Novell Modesto"); 84 | } else if(header->e_ident[EI_OSABI] == 0x0C) { 85 | debug_print_line(L"OpenBSD"); 86 | } else if(header->e_ident[EI_OSABI] == 0x0D) { 87 | debug_print_line(L"OpenVMS"); 88 | } else if(header->e_ident[EI_OSABI] == 0x0E) { 89 | debug_print_line(L"NonStop Kernel"); 90 | } else if(header->e_ident[EI_OSABI] == 0x0F) { 91 | debug_print_line(L"AROS"); 92 | } else if(header->e_ident[EI_OSABI] == 0x10) { 93 | debug_print_line(L"Fenix OS"); 94 | } else if(header->e_ident[EI_OSABI] == 0x11) { 95 | debug_print_line(L"CloudABI"); 96 | } 97 | debug_print_line(L"\n"); 98 | 99 | debug_print_line(L" File Type: "); 100 | if(header->e_type == 0x00) { 101 | debug_print_line(L"None"); 102 | } else if(header->e_type == 0x01) { 103 | debug_print_line(L"Relocatable"); 104 | } else if(header->e_type == 0x02) { 105 | debug_print_line(L"Executable"); 106 | } else if(header->e_type == 0x03) { 107 | debug_print_line(L"Dynamic"); 108 | } else { 109 | debug_print_line(L"Other"); 110 | } 111 | debug_print_line(L"\n"); 112 | 113 | debug_print_line(L" Machine Type: "); 114 | if(header->e_machine == 0x00) { 115 | debug_print_line(L"No specific instruction set"); 116 | } else if(header->e_machine == 0x02) { 117 | debug_print_line(L"SPARC"); 118 | } else if(header->e_machine == 0x03) { 119 | debug_print_line(L"x86"); 120 | } else if(header->e_machine == 0x08) { 121 | debug_print_line(L"MIPS"); 122 | } else if(header->e_machine == 0x14) { 123 | debug_print_line(L"PowerPC"); 124 | } else if(header->e_machine == 0x16) { 125 | debug_print_line(L"S390"); 126 | } else if(header->e_machine == 0x28) { 127 | debug_print_line(L"ARM"); 128 | } else if(header->e_machine == 0x2A) { 129 | debug_print_line(L"SuperH"); 130 | } else if(header->e_machine == 0x32) { 131 | debug_print_line(L"IA-64"); 132 | } else if(header->e_machine == 0x3E) { 133 | debug_print_line(L"x86-64"); 134 | } else if(header->e_machine == 0xB7) { 135 | debug_print_line(L"AArch64"); 136 | } else if(header->e_machine == 0xF3) { 137 | debug_print_line(L"RISC-V"); 138 | } 139 | debug_print_line(L"\n"); 140 | 141 | if(header->e_ident[EI_CLASS] == ELF_FILE_CLASS_32) { 142 | debug_print_line(L" Entry point: 0x%lx\n", header->e_entry); 143 | debug_print_line(L" Program header offset: 0x%lx\n", header->e_phoff); 144 | debug_print_line(L" Section header offset: 0x%lx\n", header->e_shoff); 145 | debug_print_line(L" Program header count: %u\n", header->e_phnum); 146 | debug_print_line(L" Section header count: %u\n", header->e_shnum); 147 | 148 | Elf32_Phdr* program_headers = program_headers_ptr; 149 | 150 | debug_print_line(L"\nProgram Headers:\n"); 151 | UINTN p = 0; 152 | for(p = 0; p < header->e_phnum; p++) { 153 | debug_print_line(L"[%u]:\n", p); 154 | debug_print_line(L" p_type: 0x%lx\n", program_headers[p].p_type); 155 | debug_print_line(L" p_offset: 0x%lx\n", program_headers[p].p_offset); 156 | debug_print_line(L" p_vaddr: 0x%lx\n", program_headers[p].p_vaddr); 157 | debug_print_line(L" p_paddr: 0x%lx\n", program_headers[p].p_paddr); 158 | debug_print_line(L" p_filesz: 0x%lx\n", program_headers[p].p_filesz); 159 | debug_print_line(L" p_memsz: 0x%lx\n", program_headers[p].p_memsz); 160 | debug_print_line(L" p_flags: 0x%lx\n", program_headers[p].p_flags); 161 | debug_print_line(L" p_align: 0x%lx\n", program_headers[p].p_align); 162 | debug_print_line(L"\n"); 163 | } 164 | } else if(header->e_ident[EI_CLASS] == ELF_FILE_CLASS_64) { 165 | debug_print_line(L" Entry point: 0x%llx\n", header64->e_entry); 166 | debug_print_line(L" Program header offset: 0x%llx\n", header64->e_phoff); 167 | debug_print_line(L" Section header offset: 0x%llx\n", header64->e_shoff); 168 | debug_print_line(L" Program header count: %u\n", header64->e_phnum); 169 | debug_print_line(L" Section header count: %u\n", header64->e_shnum); 170 | 171 | Elf64_Phdr* program_headers = program_headers_ptr; 172 | 173 | debug_print_line(L"\nDebug: Program Headers:\n"); 174 | UINTN p = 0; 175 | for(p = 0; p < header64->e_phnum; p++) { 176 | debug_print_line(L"[%u]:\n", p); 177 | debug_print_line(L" p_type: 0x%lx\n", program_headers[p].p_type); 178 | debug_print_line(L" p_flags: 0x%lx\n", program_headers[p].p_flags); 179 | debug_print_line(L" p_offset: 0x%llx\n", program_headers[p].p_offset); 180 | debug_print_line(L" p_vaddr: 0x%llx\n", program_headers[p].p_vaddr); 181 | debug_print_line(L" p_paddr: 0x%llx\n", program_headers[p].p_paddr); 182 | debug_print_line(L" p_filesz: 0x%llx\n", program_headers[p].p_filesz); 183 | debug_print_line(L" p_memsz: 0x%llx\n", program_headers[p].p_memsz); 184 | debug_print_line(L" p_align: 0x%llx\n", program_headers[p].p_align); 185 | debug_print_line(L"\n"); 186 | } 187 | } 188 | } 189 | 190 | 191 | /** 192 | * read_elf_file 193 | */ 194 | EFI_STATUS read_elf_file(IN EFI_FILE* const kernel_img_file, 195 | IN Elf_File_Class const file_class, 196 | OUT VOID** kernel_header_buffer, 197 | OUT VOID** kernel_program_headers_buffer) 198 | { 199 | /** The number of bytes to read into the read buffers. */ 200 | UINTN buffer_read_size = 0; 201 | /** The offset of the program headers in the executable. */ 202 | UINTN program_headers_offset = 0; 203 | 204 | // Reset to start of file. 205 | #ifdef DEBUG 206 | debug_print_line(L"Debug: Setting file pointer to " 207 | "read executable header\n"); 208 | #endif 209 | 210 | EFI_STATUS status = uefi_call_wrapper(kernel_img_file->SetPosition, 2, 211 | kernel_img_file, 0); 212 | if(EFI_ERROR(status)) { 213 | debug_print_line(L"Error: Error setting file pointer position: %s\n", 214 | get_efi_error_message(status)); 215 | 216 | return status; 217 | } 218 | 219 | if(file_class == ELF_FILE_CLASS_32) { 220 | buffer_read_size = sizeof(Elf32_Ehdr); 221 | } else if(file_class == ELF_FILE_CLASS_64) { 222 | buffer_read_size = sizeof(Elf64_Ehdr); 223 | } else { 224 | debug_print_line(L"Error: Invalid file class\n", status); 225 | return EFI_INVALID_PARAMETER; 226 | } 227 | 228 | #ifdef DEBUG 229 | debug_print_line(L"Debug: Allocating '0x%lx' for ", buffer_read_size); 230 | debug_print_line(L"kernel executable header buffer\n"); 231 | #endif 232 | 233 | status = uefi_call_wrapper(gBS->AllocatePool, 3, 234 | EfiLoaderData, buffer_read_size, kernel_header_buffer); 235 | if(EFI_ERROR(status)) { 236 | debug_print_line(L"Error: Error allocating kernel header buffer: %s\n", 237 | get_efi_error_message(status)); 238 | 239 | return status; 240 | } 241 | 242 | #ifdef DEBUG 243 | debug_print_line(L"Debug: Reading kernel executable header\n"); 244 | #endif 245 | 246 | status = uefi_call_wrapper(kernel_img_file->Read, 3, 247 | kernel_img_file, &buffer_read_size, *kernel_header_buffer); 248 | if(EFI_ERROR(status)) { 249 | debug_print_line(L"Error: Error reading kernel header: %s\n", 250 | get_efi_error_message(status)); 251 | 252 | return status; 253 | } 254 | 255 | 256 | if(file_class == ELF_FILE_CLASS_32) { 257 | program_headers_offset = ((Elf32_Ehdr*)*kernel_header_buffer)->e_phoff; 258 | buffer_read_size = sizeof(Elf32_Phdr) * 259 | ((Elf32_Ehdr*)*kernel_header_buffer)->e_phnum; 260 | } else if(file_class == ELF_FILE_CLASS_64) { 261 | program_headers_offset = ((Elf64_Ehdr*)*kernel_header_buffer)->e_phoff; 262 | buffer_read_size = sizeof(Elf64_Phdr) * 263 | ((Elf64_Ehdr*)*kernel_header_buffer)->e_phnum; 264 | } 265 | 266 | // Read program headers. 267 | #ifdef DEBUG 268 | debug_print_line(L"Debug: Setting file offset to '0x%lx' " 269 | "to read program headers\n", program_headers_offset); 270 | #endif 271 | 272 | status = uefi_call_wrapper(kernel_img_file->SetPosition, 2, 273 | kernel_img_file, program_headers_offset); 274 | if(EFI_ERROR(status)) { 275 | debug_print_line(L"Error: Error setting file pointer position: %s\n", 276 | get_efi_error_message(status)); 277 | 278 | return status; 279 | } 280 | 281 | // Allocate memory for program headers. 282 | #ifdef DEBUG 283 | debug_print_line(L"Debug: Allocating '0x%lx' for program headers buffer\n", 284 | buffer_read_size); 285 | #endif 286 | 287 | status = uefi_call_wrapper(gBS->AllocatePool, 3, 288 | EfiLoaderData, buffer_read_size, kernel_program_headers_buffer); 289 | if(EFI_ERROR(status)) { 290 | debug_print_line(L"Error: Error allocating kernel " 291 | "program header buffer: %s\n", get_efi_error_message(status)); 292 | 293 | return status; 294 | } 295 | 296 | #ifdef DEBUG 297 | debug_print_line(L"Debug: Reading program headers\n"); 298 | #endif 299 | 300 | status = uefi_call_wrapper(kernel_img_file->Read, 3, 301 | kernel_img_file, &buffer_read_size, *kernel_program_headers_buffer); 302 | if(EFI_ERROR(status)) { 303 | debug_print_line(L"Error: Error reading kernel program headers: %s\n", 304 | get_efi_error_message(status)); 305 | 306 | return status; 307 | } 308 | 309 | return EFI_SUCCESS; 310 | } 311 | 312 | 313 | /** 314 | * read_elf_identity 315 | */ 316 | EFI_STATUS read_elf_identity(IN EFI_FILE* const kernel_img_file, 317 | OUT UINT8** elf_identity_buffer) 318 | { 319 | /** The amount of bytes to read into the buffer. */ 320 | UINTN buffer_read_size = EI_NIDENT; 321 | 322 | #ifdef DEBUG 323 | debug_print_line(L"Debug: Setting file pointer position " 324 | "to read ELF identity\n"); 325 | #endif 326 | 327 | // Reset to the start of the file. 328 | EFI_STATUS status = uefi_call_wrapper(kernel_img_file->SetPosition, 2, 329 | kernel_img_file, 0); 330 | if(EFI_ERROR(status)) { 331 | debug_print_line(L"Error: Error resetting file pointer position: %s\n", 332 | get_efi_error_message(status)); 333 | 334 | return status; 335 | } 336 | 337 | #ifdef DEBUG 338 | debug_print_line(L"Debug: Allocating buffer for ELF identity\n"); 339 | #endif 340 | 341 | status = uefi_call_wrapper(gBS->AllocatePool, 3, 342 | EfiLoaderData, EI_NIDENT, (VOID**)elf_identity_buffer); 343 | if(EFI_ERROR(status)) { 344 | debug_print_line(L"Error: Error allocating kernel identity buffer: %s\n", 345 | get_efi_error_message(status)); 346 | 347 | return status; 348 | } 349 | 350 | #ifdef DEBUG 351 | debug_print_line(L"Debug: Reading ELF identity\n"); 352 | #endif 353 | 354 | status = uefi_call_wrapper(kernel_img_file->Read, 3, 355 | kernel_img_file, &buffer_read_size, (VOID*)*elf_identity_buffer); 356 | if(EFI_ERROR(status)) { 357 | debug_print_line(L"Error: Error reading kernel identity: %s\n", 358 | get_efi_error_message(status)); 359 | 360 | return status; 361 | } 362 | 363 | return EFI_SUCCESS; 364 | } 365 | 366 | 367 | /** 368 | * validate_elf_identity 369 | */ 370 | EFI_STATUS validate_elf_identity(IN UINT8* const elf_identity_buffer) 371 | { 372 | if((elf_identity_buffer[EI_MAG0] != 0x7F) || 373 | (elf_identity_buffer[EI_MAG1] != 0x45) || 374 | (elf_identity_buffer[EI_MAG2] != 0x4C) || 375 | (elf_identity_buffer[EI_MAG3] != 0x46)) { 376 | debug_print_line(L"Fatal Error: Invalid ELF header\n"); 377 | return EFI_INVALID_PARAMETER; 378 | } 379 | 380 | if(elf_identity_buffer[EI_CLASS] == ELF_FILE_CLASS_32) { 381 | #ifdef DEBUG 382 | debug_print_line(L"Debug: Found 32bit executable\n"); 383 | #endif 384 | } else if(elf_identity_buffer[EI_CLASS] == ELF_FILE_CLASS_64) { 385 | #ifdef DEBUG 386 | debug_print_line(L"Debug: Found 64bit executable\n"); 387 | #endif 388 | } else { 389 | debug_print_line(L"Fatal Error: Invalid executable\n"); 390 | 391 | return EFI_UNSUPPORTED; 392 | } 393 | 394 | if(elf_identity_buffer[EI_DATA] != 1) { 395 | debug_print_line(L"Fatal Error: Only LSB ELF executables " 396 | "current supported\n"); 397 | 398 | return EFI_INCOMPATIBLE_VERSION; 399 | } 400 | 401 | return EFI_SUCCESS; 402 | } 403 | -------------------------------------------------------------------------------- /LICENCE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------