From bbcf34f1f65a6558dd5c5150fdf28153d5958474 Mon Sep 17 00:00:00 2001 From: Alex Kotov Date: Sun, 16 Jan 2022 20:14:56 +0500 Subject: [PATCH] Write MBR --- .gitignore | 1 + configure.ac | 2 +- src/main.c | 61 +++++++++++++++++++++++++++++++++++++++++-- src/x86_boot_sector.S | 3 --- 4 files changed, 61 insertions(+), 6 deletions(-) diff --git a/.gitignore b/.gitignore index 829b309..b2b801b 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,7 @@ *.a *.bin *.c.d +*.img *.o .deps/ diff --git a/configure.ac b/configure.ac index 0f6e626..1c94a14 100644 --- a/configure.ac +++ b/configure.ac @@ -27,6 +27,6 @@ AC_PROG_CC_C99 AC_PROG_RANLIB AC_C_INLINE AC_CHECK_HEADER_STDBOOL -AC_CHECK_HEADERS([stdarg.h stddef.h stdint.h stdio.h]) +AC_CHECK_HEADERS([stdarg.h stddef.h stdint.h stdio.h string.h]) AC_OUTPUT diff --git a/src/main.c b/src/main.c index cf08d55..923535e 100644 --- a/src/main.c +++ b/src/main.c @@ -18,8 +18,10 @@ #include #include +#include #define MBR_SIZE 512 +#define MBR_BOOTSTRAP_SIZE (MBR_SIZE - sizeof(struct MbrInfo)) #define MBR_ENTRIES 4 #define MBR_MAGIC 0xAA55 @@ -42,13 +44,68 @@ struct MbrInfo { __attribute__((packed)); struct Mbr { - uint8_t bootstrap[MBR_SIZE - sizeof(struct MbrInfo)]; + uint8_t bootstrap[MBR_BOOTSTRAP_SIZE]; struct MbrInfo info; } __attribute__((packed)); int main() { - printf("Hello, World!\n"); + struct Mbr mbr; + + { + memset(&mbr, 0, sizeof(mbr)); + + mbr.info.magic = MBR_MAGIC; + mbr.info.disk_id = 0; + mbr.info.reserved = 0; + } + + { + FILE *fd = fopen("src/x86_boot_sector.bin", "r"); + if (fd == NULL) { + fprintf(stderr, "Can't open bootstrap file\n"); + return 1; + } + + const size_t size = fread(&mbr.bootstrap, 1, MBR_BOOTSTRAP_SIZE, fd); + if (size == 0) { + fprintf(stderr, "Empty bootstrap file\n"); + return 1; + } + if (!feof(fd)) { + fprintf(stderr, "Too long bootstrap file\n"); + return 1; + } + + fclose(fd); + } + + uint8_t *mbr_ptr = (uint8_t*)&mbr; + + for (size_t i = 0; i < 512 / 16; ++i) { + printf("%02x", mbr_ptr[i * 16]); + for (size_t j = 1; j < 16; ++j) { + printf(" %02x", mbr_ptr[i * 16 + j]); + } + printf("\n"); + } + + { + FILE *fd = fopen("disk.img", "wb"); + if (fd == NULL) { + fprintf(stderr, "Can't open image file\n"); + return 1; + } + + const size_t size = fwrite(mbr_ptr, 1, sizeof(mbr), fd); + if (size != sizeof(mbr)) { + fprintf(stderr, "Can't write image file\n"); + return 1; + } + + fclose(fd); + } + return 0; } diff --git a/src/x86_boot_sector.S b/src/x86_boot_sector.S index 58e1c20..392ae60 100644 --- a/src/x86_boot_sector.S +++ b/src/x86_boot_sector.S @@ -37,6 +37,3 @@ _start: int $0x10 _loop: jmp _loop -_end: -.fill 510 - (_end - _start), 1, 0 -.byte 0x55, 0xAA