Transcription of Writing a Simple Operating System | from Scratch
1 IWriting a Simple Operating System from ScratchbyNick BlundellSchool of Computer Science, University of Birmingham,UKDraft: December 2, 2010 Copyrightc 2009 2010 Nick BlundellContentsContentsii1 Introduction12 Computer Architecture and the Boot Boot Process .. , Boot Blocks, and the Magic Number .. Emulation .. : A x86 CPU Emulator .. Usefulness of Hexadecimal Notation ..63 Boot Sector Programming (in 16-bit Real Mode) Sector Re-visited .. Real Mode .. , Hello? .. Registers .. it all Together .. , World! .. , Addresses, and Labels .. X Marks the Spot .. 13 Question 1 .. Strings .. the Stack .. 17 Question 2 .. Structures .. 17 Question 3 .. Functions .. Files .. it all Together .. 21 Question 4 .. , Fetch me my Steth-o-scope .. 5 (Advanced) .. the Disk.
2 Memory Access Using Segments .. Disk Drives Work .. BIOS to Read the Disk .. it all Together .. 284 Entering 32-bit Protected to Life Without BIOS .. the Global Descriptor Table .. the GDT in Assembly .. the Switch .. it all Together .. 395 Writing , Building, and Loading Your C Compilation .. Raw Machine Code .. Variables .. Functions .. , Addresses, and Data .. our Kernel Code .. our Kernel .. a Boot Sector to Bootstrap our Kernel .. Our Way into the Kernel .. Builds with Make .. Our Operating System s Code Base .. Primer .. Pre-processor and Directives .. Declarations and Header Files .. 606 Developing Essential Device Drivers and a Input/Output .. Buses .. Programming .. Memory Access .. Driver.
3 The Display Device .. Screen Driver Implementation .. the Screen .. Interrupts .. Driver .. Driver .. System .. 707 Implementing Processing .. 71 CONTENTSiv8 Summary72 Bibliography73 Chapter1 IntroductionWe ve all used an Operating System (OS) before ( Windows XP, linux , etc.), andperhaps we have even written some programs to run on one; but what is an OS actuallythere for? how much of what I see when I use a computer is done by hardware and howmuch is done by software? and how does the computer actually work?The late Prof. Doug Shepherd, a lively teacher of mine at Lancaster University,once reminded me amid my grumbling about some annoying programming problem that,back in the day, before he could evenbeginto attempt any research, he had to writehis own Operating System , from Scratch . So it seems that, today, we take a lot forgranted about how these wonderful machines actually work underneith all those layersof software that commonly come bundled with them and which are required for theirday-to-day , concentrating on the widely used x86 architecture CPU, we will strip bare ourcomputer ofallsoftware and follow in Doug s early footsteps, learning along the wayabout.
4 How a computer boots How to write low-level programs in the barren landscape where no operatingsystem yet exists How to configure the CPU so that we can begin to use its extended functionality How to bootstrap code written in a higher-level language, so that we can reallystart to make some progress towards our own Operating System How to create some fundamental Operating System services, such as device drivers,file systems, multi-tasking that, in terms of practical Operating System functionality, this guide does notaim to be extensive, but instead aims to pool together snippets of information frommany sources into a self-contained and coherent document, that will give you a hands-onexperience of low-level programming, how Operating systems are written, and the kindof problems they must solve. The approach taken by this guide is unique in that theparticular languages and tools ( assembly, C, Make, etc.)
5 Are not the focus butinstead are treated as a means to an end: we will learn what we need to about thesethings to help us achieve our main 1. INTRODUCTION2 This work is not intended as a replacement but rather as a stepping stone to excellentwork such as the Minix project [?] and to Operating System development in Architecture and theBoot The Boot ProcessNow, we begin our we reboot our computer, it must start up again, initially without any notion ofan Operating System . Somehow, it must load the Operating System --- whatever variantthat may be --- from some permanent storage device that is currently attached to thecomputer ( a floppy disk, a hard disk, a USB dongle, etc.).As we will shortly discover, the pre-OS environment of your computer offers little inthe way of rich services: at this stage even a Simple file System would be a luxury ( and write logical files to a disk), but we have none of that.
6 Luckily, what we do haveis the Basic Input/Output Software (BIOS), a collection of software routines that areinitially loaded from a chip into memory and initialised when the computer is switchedon. BIOS provides auto-detection and basic control of your computer s essential devices,such as the screen, keyboard, and hard BIOS completes some low-level tests of the hardware, particularly whether ornot the installed memory is working correctly, it must boot the Operating System storedon one of your devices. Here, we are reminded, though, that BIOS cannot simply load afile that represents your Operating System from a disk, since BIOS has no notion of a file- System . BIOS must read specific sectors of data (usually 512 bytes in size) from specificphysical locations of the disk devices, such as Cylinder 2, Head 3, Sector 5 (details ofdisk addressing are described later, in Section XXX).
7 So, the easiest place for BIOS to find our OS is in the first sector of one of the disks( Cylinder 0, Head 0, Sector 0), known as theboot sector. Since some of our disks maynot contain an Operating systems (they may simply be connected for additional storage),then it is important that BIOS can determine whether the boot sector of a particulardisk is boot code that is intended for execution or simply data. Note that the CPU doesnot differentiate between code and data: both can be interpreted as CPU instructions,where code is simply instructions that have been crafted by a programmer into someuseful 2. COMPUTER ARCHITECTURE AND THE BOOTPROCESS4 Again, an unsophisticated means is adopted here by BIOS, whereby the last twobytes of an intended boot sector must be set to the magic number0xaa55. So, BIOS loops through each storage device ( floppy drive, hard disk, CD drive, etc.)
8 , readsthe boot sector into memory, and instructs the CPU to begin executing the first bootsector it finds that ends with the magic is where we seize control of the BIOS, Boot Blocks, and the MagicNumberIf we use a binary editor, such as TextPad [?] or GHex [?], that will let us write raw bytevalues to a file --- rather than a standard text editor that will convert characters such as A into ASCII values --- then we can craft ourselves a Simple yet valid boot fd ff 00 00 00 00 00 00 00 00 00 00 00 00 0000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00*00 00 00 00 00 00 00 00 00 00 00 00 00 00 55 aaFigure :A machine code boot sector, with each byte displayed that, in Figure , the three important features are: The initial three bytes, in hexadecimal as0xe9,0xfdand0xff, are actuallymachine code instructions, as defined by the CPU manufacturer, to perform anendless jump.
9 The last two bytes,0x55and0xaa, make up the magic number, which tells BIOS that this is indeed a boot block and not just data that happens to be on a drive sboot sector. The file is padded with zeros ( * indicates zeros omitted for brevity), basically toposition the magic BIOS number at the end of the 512 byte disk important note on endianness. You might be wondering why the magic BIOS number was earlier described as the 16-bit value0xaa55but in our boot sector waswritten as the consecutive bytes0x55and0xaa. This is because the x86 architecturehandles multi-byte values inlittle-endianformat, whereby less significant bytes proceedmore significant bytes, which is contrary to our familiar numbering System --- though ifour System ever switched and I had 0000005 in my bank account, I would be able toretire now, and perhaps donate a couple of quid to the needy Ex-millionaires and assemblers can hide many issues of endianness from us by allowingus to define the types of data, such that, say, a 16-bit value is serialised automaticallyinto machine code with its bytes in the correct order.
10 However, it is sometimes useful,CHAPTER 2. COMPUTER ARCHITECTURE AND THE BOOTPROCESS5especially when looking for bugs, to know exactly where an individual byte will be storedon a storage device or in memory, so endianness is very is possibly the smallest program your computer could run, but it is a validprogram nonetheless, and we can test this in two ways, the second of which is much saferand better suited to our kind of experiments: Using whatever means your current Operating System will allow, write this bootblock to the first sector of a non-essential storage device ( floppy disk or flashdrive), then reboot the computer. Use virtual machine software, such as VMWare or VirtualBox, and set the bootblock code as a disk image of a virtual machine, then start-up the virtual can be sure this code has been loaded and executed if your computer simplyhangs after booting, without a message such as No Operating System found.