Operating System Development Series-bootloaders

Source: Internet
Author: User
Introduction

Welcome! We believe that you have been looking forward to this chapter for a long time. This chapter covers many topics, such:

  • Startup Process -- how it works
  • Bootloader Theory
  • Develop a simple bootloader
  • Use NASM to compile this bootloader.
  • Use VFD (Virtual Floppy Drive) software to create a floppy Image
  • Use partcopy to copy our bootloader to a floppy disk image
  • Use bochs -- Basic installation and use; test this bootloader.

Are you ready?

Press the power button during startup

What happens when you press the power button? When this button is pressed, the wire connected to this button sends an electronic signal to the motherboard. The motherboard only redirects this signal to the power supply (PSU ).

This signal contains a single bit of data. If it is 0, then, of course, there is no power (so the computer is off, or the motherboard is invalid (the motherboard is dead )). If it is 1 (meaning a valid signal), it means that the power supply is already in use.

To better understand it, remember the basis of the binary logic in the computer. The eight "bits" represents only the "line" that can pass through eight current streams ". 0 indicates that there is no current, and 1 indicates that there is current in the current wire. The logic gate is the foundation of digital logic electronics, and computers are built on it.

When the power supply receives an active signal, it begins to power the rest of the system. When the correct amount of voltage is provided to all devices, the power supply will be able to continue to supplement those without major issues.

Next, the power supply sends a signal called "power_good" to the Basic Input/Output System (BiOS) on the motherboard ).

Bios Self-check (post)

When the BIOS receives the "power_good" signal, the BIOS starts a process of becoming a self-check (power on self test. Self-check will test the provided voltage to ensure sufficient, will test the installed device (such as the keyboard, mouse, USB, serial port, etc.), and ensure that the memory is available (by testing whether the memory is damaged ).

Then the self-check will hand over the control to the BIOS. The self-check will load the BIOS to the end of the memory (may be 0xfffff0) and put a jump command in the first byte of the memory.

The instruction pointer (Cs: IP) of the processor is set to 0, and the processor obtains control.

What does this mean? The processor starts to execute commands with the address 0 × 0. Here, it is the jump command put by the self-check. This jump command will jump to 0xfffff0 (or another BIOS is loaded), and then the processor starts to execute the BIOS.

BiOS control...

Bios

The Basic Input/Output System (BiOS) does this. It creates an interrupt vector table (IVT) and provides some basic interrupt services. Then the BIOS will perform some tests to ensure there is no hardware problem. BiOS also provides a setup tool.

Then the BIOS needs to find an operating system. Based on the boot sequence you set in the bios, the BIOS will execute an interrupt (INT) 0 × 19 to try to find a bootable device.

If no boot device is found (INT 0 × 19 is returned), the BIOS then tries the next device listed in the boot sequence. If there is no device, it will print an error like "no operating system found" and then stop the system.

Interrupt and interrupt vector table (IVT)

An interrupt is a subroutine that can be run through many different programs. These interrupts are stored in a table starting with 0 × 0 that becomes the interrupt vector table. For example, a common interrupt is that int 0 × 21 is used in DOS.

Note: DOS is unavailable.! Only available interruptions are caused by BIOSProvided, but nothing else! Using other interruptions will cause the system to execute a non-existent routine and cause your program to crash!

Note: If you change the processor mode, IVTWill no longer be valid. This means that there is absolutely no "Interruption"-neither software interruption nor hardware interruption available, or even no BIOSInterrupted.We have to do this for a 32-bit operating system. Not yet!

Bios Interrupt 0 × 19

Int 0 × 19-system: bootstrap loader

Restart the system through hot boot without clearing the memory and restoring the interrupt vector table

This interruption is executed by the BIOS. It reads the first sector (1 sector, 0 sector, 0 track) of the first hard disk ).

Slice

A slice only represents a group of 512 bytes. Therefore, Sector 1 represents the first 512 bytes of a disk.

Fan Surface

A "fan" (or a fan) represents one side of the disk. Fan 0 indicates the front side and FAN 1 indicates the back side. Most disks have only one side, so there is only one fan ("fan 0 ").

Track

To understand the track, let's look at the following figure:

In this figure, the disk can represent a hard disk or a floppy disk. Here we can see the fan surface 1 (front side), and the slice represents 512 bytes. A track is a set of sectors.

Note: Remember that one slice is 512Bytes. Each magnetic track on a floppy disk has 18Slice. This is very important when we load files.

If the disk is bootable,The boot sector will be loaded0x7c00And int 0 × 19 will jump to it, so that the bootloader has control.

Note: Remember bootloaderLoaded to 0x7c00This is very important!

Note: On some systems, you can also go to the address 0 × 0040: 0072Storage 0 × 1234Value, and then jump to 0 xFFFF: 0To perform a hot start. Store 0x0 for Cold Restart.

Now, our 1337 bootloader is under control.

Bootloader Theory

We have already talked about bootloader many times. Let's concentrate the important parts!

So far, bootloader...

  • ... Stored together with the Master Boot Record (MBR)
  • ... In the first sector of the Disk
  • ... Its size is the number of bytes per sector (512)
  • ... It is loaded to address 0x7c00 by BIOS int 0 × 19

As you can imagine, we can't do much in 512 bytes. What should we do?

In assembly language, we can easily cross the location of 512 bytes. Therefore, the Code may look good, but onlyPartIt will appear in the memory. For example, consider this situation:

1 mov ax, 4ch
2 inc bx              ; 512 byte
3 mov     [var], bx   ; 514 byte

In assembly language, the program runs down from the top of the file. However, remember, when loading a file into the memory, we load the slice. Each slice is 512 bytes, so it only copies the 512 bytes of the file to the memory. If the code above is executed, and only the first sector is loaded into the memory, it will only be copied to the location of 512 bytes (INC BXCommand ). Therefore, the final mov command is still on the disk,It is not in memory!

InINC BXWhat will the processor do after instruction? It will continue to be executed to the location of 514 bytes. Because it is no longer in memory,It will execute more than the end of the file!What does the end mean? Crash!

However, it is also possible to load the second sector (or more) to a given address and execute it. In this way, the remaining part of the file will be in the memory, and everything will work normally.

This method can work, but it is difficult to implement. The most common method is to keep the size of the bootloader within 512 bytes, search, load and execute a second-level bootloader. We will look at this method in detail later.

Hardware exception

Hardware exceptions are similar to software exceptions, but the processor executes them instead of software exceptions.

Sometimes we need to stop all exceptions to prevent them from occurring. For example, when switching the computer mode, the entire interrupt vector table is no longer valid. Therefore,Any hardware or software interruption will cause your system to crash.It will be detailed later.

CLI And STI Command

You can use the STI and CLI commands to enable and disable all interrupts. Most systems prohibit the use of these commands in applications because it may cause major problems (although the system can simulate them ).

1 cli     ; clear interrupts
2  
3 do something...
4  
5 sti     ; enable interrupts--we're in the clear!
Double fault hardware exception)

If the processor finds a problem during execution (such as an invalid command divided by 0), it will execute a second-level fault exception handling program (dual fault ), that is, the interrupt is 0 × 8.

We will soon see a dual fault. If the processor cannot continue after a dual fault, it will executeTriplicate fault.

Triple fault)

We have seen this term before, haven't we? The "triplicate fault" of a CPU only means that the system is hard restarted.

At the beginning, such as bootloaderNo matter where your code has bugs, The system will cause a triple fault. This indicates that there is a problem in your code.

Develop a simple bootloader

The waiting time has finally arrived! :)

Let's look at our list again:

  • Stored together with the Master Boot Record
  • In the first sector of the Disk
  • Its size is the number of bytes per sector (512)
  • It is loaded to address 0x7c00 by BIOS int 0 × 19

Open any common text editor (Visual Studio 2005 I use), and notepad is enough.

The following is bootloader (boot1.asm )...

01 ;*********************************************
02 ;   Boot1.asm
03 ;       - A Simple Bootloader
04 ;
05 ;   Operating Systems Development Tutorial
06 ;*********************************************
07  
08 org     0x7c00              ; We are loaded by BIOS at 0x7C00
09  
10 bits    16                  ; We are still in 16 bit Real Mode
11  
12 Start:
13  
14 cli                         ; Clear all Interrupts
15 hlt                         ; halt the system
16  
17 times 510 - ($-$$) db 0     ; We have to be 512 bytes. Clear the rest of the bytes with 0
18  
19 dw 0xAA55                   ; Boot Signiture

These will not bring us too many surprises. Let's perform a row-by-row analysis:

1 org     0x7c00              ; We are loaded by BIOS at 0x7C00

Remember:BiosLoad us to 0x7c00.The above code tells NASM to ensure that all addresses are relative to 0x7c00. This means that the first command will be at 0x7c00.

1 bits    16                  ; We are still in 16 bit Real Mode

Do you still remember the content in Chapter 2? In that chapter, I explained how the x86 family is backward compatible with those old dos systems. Because the old dos systems are all 16-bit,Therefore, allX86Compatible computers enter 16Bit mode.This means:

  • We are limited to 1 MB of memory.
  • We are limited to use only 16-bit registers.

We need to switch the computer to the 32-Bit mode. We will do this later.

1 times 510 - ($-$$) db 0             ; We have to be 512 bytes. Clear the rest of the bytes with 0

I hope to have more documents about this. In NASM, the dollar sign ($) represents the address of the current row, and $ represents the address of the First Command (it should be 0x7c00 ). Therefore,$-$The number of bytes from the current row to the beginning (in this example, the size of the program) is returned ).

1 dw 0xAA55                   ; Boot Signiture

This requires some explanation.

Remember, BIOS int 0 × 19 searches for bootable disks. How does it know that the disk is bootable? The answer is the boot tag. If 511 bytes are 0xaa and 512 bytes are 0 × 55, int 0 × 19 will load and execute bootloader.

Because the boot tag must be in the last two bytes of the bootloader, we useTimesKeyword to calculate the variable size that can be filled to 510th bytes, rather than 512nd bytes.

Use NASM Assembly

NASM is a command line assembler. Therefore, it must be executed through the command line or batch processing script. To compile boot1.asm, run the following command:

1 nasm -f bin Boot1.asm -o Boot1.bin

-FSpecifies the type of the output file generated by NASM. In this example, it is a binary program.

-OSpecifies the file name of a generated file. In this exampleBoot1.bin.

After compilation, you will get a precise 512-byte file named "boot1.bin.

Note: For some reason, WindowsThe size displayed by the resource manager is limited to 1 kb.. View the properties of the file. It will notify 512Bytes.

How to Use VFD (Virtual Floppy Drive)

We will use VFD to create a virtual floppy disk image for copying our operating system. Now explain how to use it.

  1. Open vfdwin.exe
  2. Click the start button under the driver tab to open the drive.
  3. Click the driver0 or driver1 tab.
  4. Click to open

You will see the following interface:

Make sure that the media type is a standard 3.5 inch MB Floppy disk and the disk type is Ram. At the same time, ensure that write protection is disabled. Click "CREATE.

Open my computer (on your computer) and you will see a new Floppy Drive.

Right-click the drive and select Properties to format the disk. The VFD tab has a formatting option.

Partcopy-copy to Boot Sector

Good... Now our bootloader is ready. How can we copy it to a disk? You may know that Windows does not allow us to copy it directly to the first sector of the disk. Therefore, we need to use a command to implement it.

In chapter 1, we have read the following command:Debug. If you have decided to use this command, you can skipPartcopy.

Partcopy is a command line program. It is used as follows:

1 partcopy file first_byte last_byte drive

Partcopy is not limited to copying files. It can copy a specified number of bytes to or from the slice. Using its format (shown above) is a safe method.

Because you have already simulated a floppy disk drive, you can reference it with a letter name (like :).

The following command can copy our Bootloader:

1 partcopy Boot1.bin 0 200 -f0

F0 indicates that the disk is 0. You can change between F0 and F1 Based on the drive where your floppy disk is located. Boot1.bin is the file to be copied. It copies the first byte (0 × 0) of the file to the last byte (0 × 200, that is, decimal 512 ). Note that partcopy only receives the hexadecimal number.

Warning remember that using this program may cause permanent damage to the disk. The command line above applies only to floppy disks and does not try to use it on hard disks.

Bochs: Test bootloader

Bochs is a 32-bit PC simulator. We will use bochs for debugging and testing.

Bochs uses a configuration file to describe the simulated hardware. For example, the following configuration file is used:

01 # ROM and VGA BIOS images ---------------------------------------------
02  
03 romimage:    file=BIOS-bochs-latest, address=0xf0000
04 vgaromimage: VGABIOS-lgpl-latest
05  
06 # boot from floppy using our disk image -------------------------------
07  
08 floppya: 1_44=a:, status=inserted  # Boot from drive A
09  
10 # logging and reporting -----------------------------------------------
11  
12 log:         OSDev.log# All errors and info logs will output to OSDev.log
13 error:       action=report
14 info:        action=report

The configuration file uses the # number to indicate comments. It will try to start from any floppy disk image on disk A (for example, the one we created with VFD. Rom bios and vga bios images come from bochs, so you don't need to worry about it.

Locate BIOS Rom

Many lines in the configuration file are very simple, but there is a line we need to look at here:

1 romimage:    file=BIOS-bochs-latest, address=0xf0000

This line tells bochs where the BIOS is stored in the memory (Virtual RAM. Do you still remember that the BIOS size may be different? Do you still remember that the BIOS must end at the end of the first MB (0 xfffff) in the memory?

Therefore, you need to change this line to relocate the BIOS. You can achieve it by obtaining the size of the BIOS image (in your bochs directory, it should be namedBIOS-bochs-Latest). Obtains the number of bytes.

Then, the size (in bytes) of the 0 xfffff-bochs file is simply subtracted ). This is the new BIOS address, and then update this on that line.AddressYou can move the BIOS to its new address.

You can use or do not need to do this step. If you get an error about the BIOS must end with 0xfffff in the bochs test, you need to complete this step before it will work.

How to Use bochs :
  1. Execute bochs.exe
  2. Select option 2 (read Option List); Press ENTER
  3. Enter the configuration file name (the one we created above); Press ENTER
  4. You will return to the main menu. Select Option 5: Start simulation, and then press ENTER
A new window will open, and you will see the following:

If bochs Exit or restart

... So you have just experienced a triplle fault and are back to the Code to try and find out where the problem is. If you need any help, contact me.

If the window appears, but there is nothing

Congratulations! That's ours.CLIAndHltThe command has paused the system, so we know that our bootloader has been executed.

Creation process-Summary

Compare what we have done with the creation process we have seen in the previous chapter. After you get used to it, you will feel very simple.

From now on, I will not describe the detailed steps in the creation process.

Not complete to be continued!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.