我们发现,在起点与终点之间,还有几个中转站。最近的一站叫作MBR。BIOS,带你到MBR后,说:“对不起,只能送你到这里了。”
那其它几个中转站是什么呢?我们知道,在x86上,保护模式有两种,32位页式寻址的保护模式和32位段式寻址的保护模式。显然,32位页式寻址的保护模式要求系统中已经构造好页表。从16位实地址模式直接到32位页式寻址的保护模式是很有难度的,因为你要在16位实地址模式下构造页表。所以不妨三级跳,先从16位实地址模式跳到32位段式寻址的保护模式,再从32位段式寻址的保护模式跳到32位页式寻址的保护模式。
我们需要这样一个程序,负责从16位实地址模式跳到32位段式寻址的保护模式,然后设置eip,启动内核。这个程序的确存在,就是arch/i386/boot/setup.S。最后汇编成setup程序。
事实上,平时所见的压缩内核映象bzImage,其实由三部分组成。这可以从arch/i386/boot/tools/build.c中看出来。build.c是用户态工具build的源代码,后者用来把bootsect(MBR),setup(辅助程序)和vmlinux.bin(压缩过的内核)拼接成bzImage。
/*
* linux/tools/build.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*/
/*
* This file builds a disk-image from three different files:
*
* - bootsect: exactly 512 bytes of 8086 machine code, loads the rest
* - setup: 8086 machine code, sets up system parm
* - system: 80386 code for actual system
*
* It does some checking that all files are of the correct type, and
* just writes the result to stdout, removing headers and padding to
* the right amount. It also writes some system data to stderr.
*/
/*
* Changes by tytso to allow root device specification
* High loaded stuff by Hans Lermen & Werner Almesberger, Feb. 1996
* Cross compiling fixes by Gertjan van Wingerde, July 1996
*/
#include <stdio.h> /* fprintf */
#include <string.h>
#include <stdlib.h> /* contains exit */
#include <sys/types.h> /* unistd.h needs this */
#include <sys/stat.h>
#include <sys/sysmacros.h>
#include <unistd.h> /* contains read/write */
#include <fcntl.h>
#include <linux/a.out.h>
#include <errno.h>
#define MINIX_HEADER 32
#define N_MAGIC_OFFSET 1024
#ifndef __BFD__
static int GCC_HEADER = sizeof(struct exec);
#endif
#ifdef __BIG_KERNEL__
#define SYS_SIZE 0xffff
#else
#define SYS_SIZE DEF_SYSSIZE
#endif
#define DEFAULT_MAJOR_ROOT 0
#define DEFAULT_MINOR_ROOT 0
/* max nr of sectors of setup: don't change unless you also change
* bootsect etc */
#define SETUP_SECTS 4
#define STRINGIFY(x) #x
typedef union {
int i;
long l;
short s[2];
char b[4];
} conv;
long intel_long(long l)
{
conv t;
t.b[0] = l & 0xff; l >>= 8;
t.b[1] = l & 0xff; l >>= 8;
t.b[2] = l & 0xff; l >>= 8;
t.b[3] = l & 0xff; l >>= 8;
return t.l;
}
int intel_int(int i)
{
conv t;
t.b[0] = i & 0xff; i >>= 8;
t.b[1] = i & 0xff; i >>= 8;
t.b[2] = i & 0xff; i >>= 8;
t.b[3] = i & 0xff; i >>= 8;
return t.i;
}
short intel_short(short l)
{
conv t;
t.b[0] = l & 0xff; l >>= 8;
t.b[1] = l & 0xff; l >>= 8;
return t.s[0];
}
void die(const char * str)
{
fprintf(stderr,"%s\n",str);
exit(1);
}
void usage(void)
{
die("Usage: build bootsect setup system [rootdev] [> image]");
}
int main(int argc, char ** argv)
{
int i,c,id,sz,tmp_int;
unsigned long sys_size, tmp_long;
char buf[1024];
#ifndef __BFD__
struct exec *ex = (struct exec *)buf;
#endif
char major_root, minor_root;
struct stat sb;
unsigned char setup_sectors;
if ((argc < 4) || (argc > 5))
usage();
if (argc > 4) {
if (!strcmp(argv[4], "CURRENT")) {
if (stat("/", &sb)) {
perror("/");
die("Couldn't stat /");
}
major_root = major(sb.st_dev);
minor_root = minor(sb.st_dev);
} else if (strcmp(argv[4], "FLOPPY")) {
if (stat(argv[4], &sb)) {
perror(argv[4]);
die("Couldn't stat root device.");
}
major_root = major(sb.st_rdev);
minor_root = minor(sb.st_rdev);
} else {
major_root = 0;
minor_root = 0;
}
} else {
major_root = DEFAULT_MAJOR_ROOT;
minor_root = DEFAULT_MINOR_ROOT;
}
fprintf(stderr, "Root device is (%d, %d)\n", major_root, minor_root);
for (i=0;i<sizeof buf; i++) buf[i]=0;
if ((id=open(argv[1],O_RDONLY,0))<0)
die("Unable to open 'boot'");
if (read(id,buf,MINIX_HEADER) != MINIX_HEADER)
die("Unable to read header of 'boot'");
if (((long *) buf)[0]!=intel_long(0x04100301))
die("Non-Minix header of 'boot'");
if (((long *) buf)[1]!=intel_long(MINIX_HEADER))
die("Non-Minix header of 'boot'");
if (((long *) buf)[3] != 0)
die("Illegal data segment in 'boot'");
if (((long *) buf)[4] != 0)
die("Illegal bss in 'boot'");
if (((long *) buf)[5] != 0)
die("Non-Minix header of 'boot'");
if (((long *) buf)[7] != 0)
die("Illegal symbol table in 'boot'");
i=read(id,buf,sizeof buf);
fprintf(stderr,"Boot sector %d bytes.\n",i);
if (i != 512)
die("Boot block must be exactly 512 bytes");
if ((*(unsigned short *)(buf+510)) != (unsigned short)intel_short(0xAA55))
die("Boot block hasn't got boot flag (0xAA55)");
buf[508] = (char) minor_root;
buf[509] = (char) major_root;
i=write(1,buf,512);
if (i!=512)
die("Write call failed");
close (id);
if ((id=open(argv[2],O_RDONLY,0))<0)
die("Unable to open 'setup'");
if (read(id,buf,MINIX_HEADER) != MINIX_HEADER)
die("Unable to read header of 'setup'");
if (((long *) buf)[0]!=intel_long(0x04100301))
die("Non-Minix header of 'setup'");
if (((long *) buf)[1]!=intel_long(MINIX_HEADER))
die("Non-Minix header of 'setup'");
if (((long *) buf)[3] != 0)
die("Illegal data segment in 'setup'");
if (((long *) buf)[4] != 0)
die("Illegal bss in 'setup'");
if (((long *) buf)[5] != 0)
die("Non-Minix header of 'setup'");
if (((long *) buf)[7] != 0)
die("Illegal symbol table in 'setup'");
for (i=0 ; (c=read(id,buf,sizeof buf))>0 ; i+=c )
#ifdef __BIG_KERNEL__
{
if (!i) {
/* Working with memcpy because of alignment constraints
on Sparc - Gertjan */
memcpy(&tmp_long, &buf[2], sizeof(long));
if (tmp_long != intel_long(0x53726448) )
die("Wrong magic in loader header of 'setup'");
memcpy(&tmp_int, &buf[6], sizeof(int));
if (tmp_int < intel_int(0x200))
die("Wrong version of loader header of 'setup'");
buf[0x11] = 1; /* LOADED_HIGH */
tmp_long = intel_long(0x100000);
memcpy(&buf[0x14], &tmp_long, sizeof(long)); /* code32_start */
}
#endif
if (write(1,buf,c)!=c)
die("Write call failed");
#ifdef __BIG_KERNEL__
}
#endif
if (c != 0)
die("read-error on 'setup'");
close (id);
setup_sectors = (unsigned char)((i + 511) / 512);
/* for compatibility with LILO */
if (setup_sectors < SETUP_SECTS)
setup_sectors = SETUP_SECTS;
fprintf(stderr,"Setup is %d bytes.\n",i);
for (c=0 ; c<sizeof(buf) ; c++)
buf[c] = '\0';
while (i < setup_sectors * 512) {
c = setup_sectors * 512 - i;
if (c > sizeof(buf))
c = sizeof(buf);
if (write(1,buf,c) != c)
die("Write call failed");
i += c;
}
if ((id=open(argv[3],O_RDONLY,0))<0)
die("Unable to open 'system'");
#ifndef __BFD__
if (read(id,buf,GCC_HEADER) != GCC_HEADER)
die("Unable to read header of 'system'");
if (N_MAGIC(*ex) == ZMAGIC) {
GCC_HEADER = N_MAGIC_OFFSET;
lseek(id, GCC_HEADER, SEEK_SET);
} else if (N_MAGIC(*ex) != QMAGIC)
die("Non-GCC header of 'system'");
fprintf(stderr,"System is %d kB (%d kB code, %d kB data and %d kB bss)\n",
(ex->a_text+ex->a_data+ex->a_bss)/1024,
ex->a_text /1024,
ex->a_data /1024,
ex->a_bss /1024);
sz = N_SYMOFF(*ex) - GCC_HEADER + 4;
#else
if (fstat (id, &sb)) {
perror ("fstat");
die ("Unable to stat 'system'");
}
sz = sb.st_size;
fprintf (stderr, "System is %d kB\n", sz/1024);
#endif
sys_size = (sz + 15) / 16;
if (sys_size > SYS_SIZE)
die("System is too big");
while (sz > 0) {
int l, n;
l = sz;
if (l > sizeof(buf))
l = sizeof(buf);
if ((n=read(id, buf, l)) != l) {
if (n == -1)
perror(argv[1]);
else
fprintf(stderr, "Unexpected EOF\n");
die("Can't read 'system'");
}
if (write(1, buf, l) != l)
die("Write failed");
sz -= l;
}
close(id);
if (lseek(1, 497, 0) == 497) {
if (write(1, &setup_sectors, 1) != 1)
die("Write of setup sectors failed");
}
if (lseek(1,500,0) == 500) {
buf[0] = (sys_size & 0xff);
buf[1] = ((sys_size >> 8) & 0xff);
if (write(1, buf, 2) != 2)
die("Write failed");
}
return(0);
}
setup有了,它可以启动内核,然而新的问题来了。谁来启动setup呢?第一个想到的是MBR。可惜,MBR只有512个字节,而且有64个字节来存放主分区表。这样看来,MBR的功能就很有限了。所以,最好在setup和MBR之间再架一座桥梁。引导程序,对,用它来引导setup再合适不过了。现有的引导程序如grub,lilo不仅功能强大,而且还提供了人机交互的功能。再合适不过了。
所以,我们理清了大概思路,查阅相关资料可知:
1.CPU加电,从0xffff0处,执行BIOS(可以理解为“硬件”引导BIOS)
2.BIOS执行扫描检测设备的操作,然后将MBR读到物理地址为0x7c00处。然后从MBR头部开始执行(可以理解为BIOS引导MBR)
3.MBR上的代码跳转到引导程序,开始执行引导程序的代码,例如grub(引以理解为BIOS引导boot loader)。
4.引导程序把内核映象(包括bootsect,setup,vmlinux)读到内存中,其中setup位于0x90200处,如果是zImage,则vmlinux.bin位于0x10000(64K)处。如果是bzImage,则vmlinux.bin位于0x100000(1M)处。然后执行setup(可以理解为boot loader引导setup)
5.setup负责引导linux内核vmlinux.bin
现在,让我们看看setup做了些什么。首先,运行一下file setup
它报告说这是一个MS DOS的可执行程序。看来,file也有不正常工作的时候。不过有一点是肯定的。setup不是普通的elf可执行程序。事实上,gcc可以编译出各种格式的程序,具体可以运行objdump -i,查看ld(gcc的链接器)支持的输出格式。其中有一个是binary格式。
从start开始,setup做了很多操作,例如,如果是zImage,则把它从0x10000拷贝到0x1000,调用bios功能,查询硬件信息,然后放在内存中供将来的内核使用,然后建立临时的idt和gdt,负责把16位实地址模式转化为32位段式寻址的保护模式。
前面这些我们不关心。我们关心的是后者:
832 movw $1, %ax # protected mode (PE) bit
833 lmsw %ax # This is it!
正是以下指令开启了保护模式的大门。最后,再临门一脚对bzImage来说:
jmpi 0x100000,__BOOT_CS对zImage来说:
jmpi 0x1000,__BOOT_CS
就大功告成了。
不过,且慢,由于当时CS寄存器还没有设置为__BOOT_CS,所以,尽管在保护模式下,也仍然不能用通常的方式访问大于1M的内存。
不过,x86处理器提供了特殊的手段来访问大于1M的内存,那就是在指令前加前缀0x66。由于跳转地址与内核大小相关(zImage和bzImage不一样)所以用一个小技巧,即把该指令当作数据处理。在计算机看来,指令和数据是没什么区别的,只要ip寄存器指向内存中某地址,计算机就把地址中的数据当作指令来看待。
854 .byte 0x66, 0xea # prefix + jmpiopcode
855 code32: .long 0x1000 # will be set to 0x100000
856 # for big kernels
857 .word __BOOT_CS
我不仅发出感慨:看setup.S的代码真是一种痛苦的体验,并且有以下感悟:1.为什么不用C写呢?
原因很简单,因为setup要尽量短小精悍,由于种种原因,它的大小不能超过63.5K.启动时内存分配如下:
0x00000~0x00400BIOS中断向量表0x00400~0x010000x01000~0x10000
0x10000~0x8f000用来存放zImage所以最多508K
0x8f000~0x90000引导程序的命令行参数以及bios查询的信息0x90000~0x90200MBR0x90200~0xA0000setup
0xA0000~0x100000映射到BIOS和外设硬件等
0x100000~存放bzImage(如果大于508K)
2.如何引用变量?
在setup.S中,定义了不少全局变量。在编译生成setup文件时,链接参数LDFLAGS_setup := -Ttext 0x0 -s --oformat binary -e begtext
意为text段的地址为0,输出格式为binary(而不是默认的elf32-i386),入口地址begtext。
由于基本上处于16位实模式下,所以只要设置好CS等段寄存器就可以正确地寻址了。
现在我们跳到vmlinux.bin的开头(位于0x1000或者0x100000),也就是startup_32(),执行相应代码。
3.helloworld,vmlinux,arch/i386/boot/compressed/vmlinux,setup,bootsect的区别与联系。
这几个可执行文件都是由gcc编译生成。只是格式不一样。
其中,helloworld,vmlinux,arch/i386/boot/compressed/vmlinux都是elf32_i386格式的可执行文件。setup,bootsect是binary格式的可执行文件,它们的区别在于
1).helloworld是普通的elf32_i386可执行文件。它的入口是_start。运行在用户态空间。变量的地址都是32位页式寻址的保护模式的地址,在用户态空间。由shell负责装载。2).vmlinux是未压缩的内核,它的入口是startup_32(0x100000,线性地址),运行在内核态空间,变量的地址是32位页式寻址的保护模式的地址,在内核态空间。由内核自解压后启动运行。
3).arch/i386/boot/compressed/vmlinux是压缩后的内核,它的入口地址是
startup_32(0x100000,线性地址).运行在32位段式寻址的保护模式下,变量的地址是32位段式寻址的保护模式的地址。由setup启动运行。
4).setup是装载内核的binary格式的辅助程序。它的入口地址是:begtext(偏移地址为0。运行时需要把cs段寄存器设置为0x9020)。运行在16位实地址模式下。变量的地址等于相对于代码段起始地址的偏移地址。由boot loader启动运行。
5).bootsect是MBR上的引导程序,也为binary格式。它的入口地址是_start(),由于装载到0x7c00处,运行时需要把cs段寄存器设置为0x7c0。运行在16位实地址模式下。变量地址等于相对于代码段起始地址的偏移地址。由BIOS启动运行。
问题出现了。startup_32有两个,分别在这两个文件中:arch/i386/boot/compressed/head.Sarch/i386/kernel/head.S
那究竟执行的是哪一个呢?难道编译时不会报错么?