启动扇区代码分析 FreeBSD 5.2.1 boot0( 二 )



下面,我们对FreeBSD启动扇区代码boot0.s进行逐步分析 。boot0.s代码如下:

#
# Copyright (c) 1998 Robert NordIEr
# All rights reserved.
#
# Redistribution and use in source and binary forms are freely
# permitted provided that the above copyright notice and this
# paragraph and the following disclaimer are duplicated in all
# such forms.
#
# This software is provided "AS IS" and without any express or
# implied warranties, including, without limitation, the implied
# warranties of merchantability and fitness for a particular
# purpose.
#
以上的Coyright就不用翻译了 。

# $FreeBSD: src/sys/boot/i386/boot0/boot0.s,v 1.27 2003/11/20 20:28:18 jhb Exp $
以上供版本管理软件使用


# A 512-byte boot manager.

.set NHRDRV,0x475 # Number of hard drives
.set ORIGIN,0x600 # Execution address
.set FAKE,0x800 # Partition entry
.set LOAD,0x7c00 # Load address

.set PRT_OFF,0x1be # Partition table

.set TBL0SZ,0x3 # Table 0 size
.set TBL1SZ,0xb # Table 1 size

.set MAGIC,0xaa55 # Magic: bootable
.set B0MAGIC,0xbb66 # Identification

.set KEY_ENTER,0x1c # Enter key scan code
.set KEY_F1,0x3b # F1 key scan code
.set KEY_1,0x02 # #1 key scan code
#
# Addresses in the sector of embedded data values.
# Accessed with negative offsets from the end of the relocated sector (雙).
#
.set _NXTDRV,-0x48 # Next drive
.set _OPT,-0x47 # Default option
.set _SETDRV,-0x46 # Drive to force
.set _FLAGS,-0x45 # Flags
.set _TICKS,-0x44 # Timeout ticks
.set _FAKE,0x0 # Fake partition entry
.set _MNUOPT,0xc # Menu options


以上是定义相关的参数值,例如“.set NHRDRV,0x475”类似于C语言中的“#define NHRDRV 0x475”

.globl start # Entry point
.code16 # This runs in real mode

#
# Initialise segments and registers to known values.
# segments start at 0.
# The stack is immediately below the address we were loaded to.
#
start:
cld # String ops inc
xorw %ax,%ax # Zero
movw %ax,%es # Address
movw %ax,%ds # data
movw %ax,%ss # Set up
movw $LOAD,%sp # stack


以上代码:
1)首先使用“cld”指令清除方向标志,使得以下的进行“rep”操作时SI和DI的值递增 。
2)使ax清零,并使除代码段cs外的另外两个数据段寄存器es、ds和堆栈段ss清零 。当然,此时cs
由于reset或初始上电已经为零了 。
3)BIOS已经把引导扇区的512字节的内容读入到了0:0x7c00处,movw $LOAD,%sp 使得堆栈指针指向扇区
代码(或曰本段代码 0:0x7c00)的顶部 。虽然堆栈向下生长可能会影响代码的内容,但下面我
们马上就把位于0:7c00处代码移到其他地方去执行 。


#
# Copy this code to the address it was linked for
#
movw %sp,%si # Source
movw $start,%di # Destination
movw $0x100,%cx # Word count
rep # Relocate
movsw # code

把位于0:7c00处的代码搬移到0:0x600处 。注意,此时由于代码连接的重定向,$start=0x600 。

#
# Set address for variable space beyond code, and clear it.
# Notice that this is also used to point to the values embedded in the block,
# by using negative offsets.
movw %di,%bp # Address variables
movb $0x8,%cl # Words to clear
rep # Zero
stosw # them

通过以上一段代码的执行,本代码已被搬移到0:0x600处,此时si=di=0x600 0x100,以上代码
把di的值保存到bp,bp此时指向本程序搬移后的未用的空间的首部,且把此bp所指的16字节空间
清零 。以上过程如下图所示:

┏>0:0x600 ┏━━━━━┓
┃ ┃ ┃
┃ ┃ 搬 ┃
┃ ┃ 移 ┃
┃ ┃ 之 ┃
┃ ┃ 后 ┃
┃ ┃ 的 ┃
┃ ┃ 代 ┃
┃ ┃ 码 ┃
┃ ┃ ┃
┃ 0:0x7ff ┣━━━━━┫
┃ ┃ 0 ┃

推荐阅读