跳到主要內容

6.828 Lab1 part 1

MIT的6.828課程是關於作業系統實作的有趣課程,我報名參加了相關的讀書會,並開始研讀課程內容,這篇文章主要紀錄Lab1的部份練習(以下描述問題時,我會用比較精簡的方式敘述,想知道完整說明的朋友請直接參考課程嘍~):

Ex1:練習x86 assembly。
Ans:由於該課程使用gas與gcc,所以我簡單練習一下AT&T的語法。

  1. .global mmax
  2. mmax:
  3.         pushl   %ebp
  4.         movl    %esp, %ebp
  5.         movl    8(%ebp), %eax
  6.         cmpl    12(%ebp), %eax
  7.         jle     .L2
  8.         movl    8(%ebp), %eax
  9.         jmp     .L3
  10. .L2:
  11.         movl    12(%ebp), %eax
  12. .L3:
  13.         popl    %ebp
  14.         ret

inline assembly的版本(由於在C function中嵌入asm,所以省卻prologue & epilogue):

  1. #include <stdio.h>
  2. static int mmax(int a, int b)
  3. {
  4.         asm volatile (
  5.         "movl   %0, %%eax \n"
  6.         "cmpl   %1, %%eax \n"
  7.         "jle    .L2 \n"
  8.         "movl   %0, %%eax \n"
  9.         "jmp    .L3 \n"
  10. ".L2: \n"
  11.         "movl   %1, %%eax \n"
  12. ".L3: \n"
  13.         ::"q"(a), "q"(b));
  14. }
  15. int main(void)
  16. {
  17.         printf("max = %d\n", mmax(-10, -2));
  18. }

Ex2:使用gdb觀察QEMU的BIOS在開機流程作了哪些事情。
Ans:BIOS基本上將PC的重要硬體週邊初始化並檢測是否有嚴重異常,若無,則讀進first bootable device的bootloader至physical address 0x7c00。課程中的boot device為IDE disk,所以會將sector 0讀進0x7c00,並將控制權移交給bootloader。

Ex3:研讀bootloader的行為。
Ans:主要有兩個檔案:boot/boot.S以及boot/main.c。在課程網站中所提供的文件其實說明的非常深入淺出,連我這個硬體白痴都讀的懂,極力推荐大家參考~


首先,從boot/Makefrag可以知道,bootloader的entry point設在start,並且從0x7c00處開始執行:

  1. $(OBJDIR)/boot/boot: $(BOOT_OBJS)
  2.     @echo + ld boot/boot
  3.     $(V)$(LD) $(LDFLAGS) -N -e start -Ttext 0x7C00 -o $@.out $^
  4.     $(V)$(OBJDUMP) -S $@.out >$@.asm
  5.     $(V)$(OBJCOPY) -S -O binary -j .text $@.out $@
  6.     $(V)perl boot/sign.pl $(OBJDIR)/boot/boot
所以bootloader的第1行指令要從boot.S的start label開始看起:

  1. #include <inc/mmu.h>
  2. # Start the CPU: switch to 32-bit protected mode, jump into C.
  3. # The BIOS loads this code from the first sector of the hard disk into
  4. # memory at physical address 0x7c00 and starts executing in real mode
  5. # with %cs=0 %ip=7c00.
  6. .set PROT_MODE_CSEG, 0x8         # kernel code segment selector
  7. .set PROT_MODE_DSEG, 0x10        # kernel data segment selector
  8. .set CR0_PE_ON,      0x1         # protected mode enable flag
  9. .globl start
  10. start:
  11.   .code16                     # Assemble for 16-bit mode
  12.   cli                         # Disable interrupts
  13.   cld                         # String operations increment
  14.   # Set up the important data segment registers (DS, ES, SS).
  15.   xorw    %ax,%ax             # Segment number zero
  16.   movw    %ax,%ds             # -> Data Segment
  17.   movw    %ax,%es             # -> Extra Segment
  18.   movw    %ax,%ss             # -> Stack Segment
BIOS移交控制權給loader時,環境為real mode,並且除了CS=0以外,不保證其他segment register的初始值,所以一開始需先將其他的segment registers都先設為0。這樣logical address才不會與loader image中的引用不符(link address設在0x7c00)。

接著,由於歷史因素,需要將A20打開才能順利使用1MB以上的physical address。

  1.   # Enable A20:
  2.   #   For backwards compatibility with the earliest PCs, physical
  3.   #   address line 20 is tied low, so that addresses higher than
  4.   #   1MB wrap around to zero by default.  This code undoes this.
  5. seta20.1:
  6.   inb     $0x64,%al               # Wait for not busy
  7.   testb   $0x2,%al
  8.   jnz     seta20.1
  9.   movb    $0xd1,%al               # 0xd1 -> port 0x64
  10.   outb    %al,$0x64
  11. seta20.2:
  12.   inb     $0x64,%al               # Wait for not busy
  13.   testb   $0x2,%al
  14.   jnz     seta20.2
  15.   movb    $0xdf,%al               # 0xdf -> port 0x60
  16.   outb    %al,$0x60
接著,切換到protected mode。

  1.   # Switch from real to protected mode, using a bootstrap GDT
  2.   # and segment translation that makes virtual addresses
  3.   # identical to their physical addresses, so that the
  4.   # effective memory map does not change during the switch.
  5.   lgdt    gdtdesc
  6.   movl    %cr0, %eax
  7.   orl     $CR0_PE_ON, %eax
  8.   movl    %eax, %cr0
  9.   # Jump to next instruction, but in 32-bit code segment.
  10.   # Switches processor into 32-bit mode.
  11.   ljmp    $PROT_MODE_CSEG, $protcseg

從gdtdesc可以看到,loader所設定的protected mode非常單純,僅先引入32 bit addressing的能力:

  1. # Bootstrap GDT
  2. .p2align 2                                # force 4 byte alignment
  3. gdt:
  4.   SEG_NULL              # null seg
  5.   SEG(STA_X|STA_R, 0x0, 0xffffffff) # code seg
  6.   SEG(STA_W, 0x0, 0xffffffff)           # data seg
  7. gdtdesc:
  8.   .word   0x17                            # sizeof(gdt) - 1
  9.   .long   gdt                             # address gdt
我們可以看到,作者只設定了兩個gdt descriptors,一個作為code segment descriptor,另一個作為data segment descriptor。並且將base都設成0,limit都設成4G。於是,loader從ljmp $PROT_MODE_CEG, $protcseg後,就擁有了32 bit address的能力,並且logical address直接對應physical address。

  1.   .code32                     # Assemble for 32-bit mode
  2. protcseg:
  3.   # Set up the protected-mode data segment registers
  4.   movw    $PROT_MODE_DSEG, %ax    # Our data segment selector
  5.   movw    %ax, %ds                # -> DS: Data Segment
  6.   movw    %ax, %es                # -> ES: Extra Segment
  7.   movw    %ax, %fs                # -> FS
  8.   movw    %ax, %gs                # -> GS
  9.   movw    %ax, %ss                # -> SS: Stack Segment
  10.   # Set up the stack pointer and call into C.
  11.   movl    $start, %esp
  12.   call bootmain
由於進到protected mode後,addressing的方式需使用新方式,所以第一件事就是將gdt中的data segment指定給ds, es, fs, gs, ss,由此可知,gdt中的data segment其實是多個同屬性的segments的集合。接著將start(也就是0x7c00)放進esp以完成stack的初始設定,然後跳進bootmain()這個C function,在閱讀bootmain()之前,我們可以歸納出來,目前的memory使用狀況大致如下:
OK,接著的bootmain()相對單純,基本上就是先讀取sector 1之後一個page,然後依據ELF header將kernel image的每個segment(ELF中的segment往往是多個sections的組合,想知道細節的話可以參考"程式設計師的自我修養")分別載入到指定的load address(program header中的LMA欄位,也就是下列程式的ph->p_pa):

  1. void
  2. bootmain(void)
  3. {
  4.     struct Proghdr *ph, *eph;
  5.     // read 1st page off disk
  6.     readseg((uint32_t) ELFHDR, SECTSIZE*8, 0);
  7.     // is this a valid ELF?
  8.     if (ELFHDR->e_magic != ELF_MAGIC)
  9.         goto bad;
  10.     // load each program segment (ignores ph flags)
  11.     ph = (struct Proghdr *) ((uint8_t *) ELFHDR + ELFHDR->e_phoff);
  12.     eph = ph + ELFHDR->e_phnum;
  13.     for (; ph < eph; ph++)
  14.         // p_pa is the load address of this segment (as well
  15.         // as the physical address)
  16.         readseg(ph->p_pa, ph->p_memsz, ph->p_offset);
  17.     // call the entry point from the ELF header
  18.     // note: does not return!
  19.     ((void (*)(void)) (ELFHDR->e_entry))();
  20. bad:
  21.     outw(0x8A00, 0x8A00);
  22.     outw(0x8A00, 0x8E00);
  23.     while (1)
  24.         /* do nothing */;
  25. }
然後loader就功成身退啦~接著就將控制權交由kernel嘍~

留言

這個網誌中的熱門文章

誰在呼叫我?不同的backtrace實作說明好文章

今天下班前一個同事問到:如何在Linux kernel的function中主動印出backtrace以方便除錯? 寫過kernel module的人都知道,基本上就是用dump_stack()之類的function就可以作到了。但是dump_stack()的功能是如何作到的呢?概念上其實並不難,慣用手法就是先觀察stack在function call時的變化(一般OS或計組教科書都有很好的說明,如果不想翻書,可以參考 這篇 ),然後將對應的return address一層一層找出來後,再將對應的function名稱印出即可(透過執行檔中的section去讀取函式名稱即可,所以要將KALLSYM選項打開)。在userspace的實作可參考Jserv介紹過的 whocallme 或對岸好手實作過的 backtrace() ,都是針對x86架構的很好說明文章。 不過從前面兩篇文章可以知道,只要知道編譯器的calling convention,就可以實作出backtrace,所以是否GCC有提供現成的機制呢?Yes, that is what __builtin_return_address() for!! 可以參考這篇 文章 。該篇文章還提到了其他可以拿來實作功能更齊全的backtrace的 程式庫 ,在了解了運作原理後,用那些東西還蠻方便的。 OK,那Linux kernel是怎麼做的呢?就是用頭兩篇文章的方式啦~ 每個不同的CPU架構各自手工實作一份dump_stack()。 為啥不用GCC的機制?畢竟...嗯,我猜想,除了backtrace以外,開發者還會想看其他register的值,還有一些有的沒的,所以光是GCC提供的介面是很難印出全部所要的資訊,與其用半套GCC的機制,不如全都自己來~ arm的實作 大致上長這樣,可以看到基本上就只是透過迭代fp, lr, pc來完成: 352 void unwind_backtrace (struct pt_regs * regs , struct task_struct *tsk) 353 { 354 struct stackframe frame ; 355 register unsigned long current_sp asm ( "...

淺讀Linux root file system初始化流程

在Unix的世界中,file system佔據一個極重要的抽象化地位。其中,/ 所代表的rootfs更是所有後續新增file system所必須依賴前提條件。以Linux為例,黑客 Jserv 就曾經詳細說明過 initramfs的背後設計考量 。本篇文章不再重複背景知識,主要將追蹤rootfs初始化的流程作點整理,免得自己日後忘記。 :-) file system與特定CPU架構無關,所以我觀察的起點從init/main.c的start_kernel()開始,這是Linux作完基本CPU初始化後首先跳進的C function(我閱讀的版本為 3.12 )。跟root file system有關的流程羅列如下: start_kernel()         -> vfs_caches_init_early()         -> vfs_caches_init()                 -> mnt_init()                         -> init_rootfs()                         -> init_mount_tree()         -> rest_init()                 -> kernel_thread(kernel_init,...) 其中比較重要的是mnt_int()中的init_rootfs()與init_mout_tree()。init_rootfs()實作如下: int __init init_root...

中文試譯:Load-time relocation of shared libraries

作者: eliben 原文連結: http://eli.thegreenplace.net/2011/08/25/load-time-relocation-of-shared-libraries/ 共享庫的載入時重定位 這篇文章的目的在解釋現代作業系統如何讓共享庫在載入時的連結動作發生。我們聚焦在32位元的x86 Linux上頭,但相同的原則在其他的作業系統與CPUs上一樣適用。 要注意的是,共享庫有許多不同的名字 - 共享庫(shared libraries),共享物件( shared objects),動態共享物件( dynamic shared objects (DSOs)),動態連結庫( dynamically linked libraries(如果你習慣的是Windows的環境,就知道這是所謂的DLL))。為了一致性,我在整篇文章中會使用"共享庫"這個字眼。 載入可執行檔 如同其他支援虛擬記憶體的作業系統,Linux將可執行檔載入到一個固定的記憶體位址。如果我們檢視任意一個可執行檔的ELF header,我們將可發現一個Entry point的位址: $ readelf -h /usr/bin/uptime ELF Header: Magic: 7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00 Class: ELF32 [...] some header fields Entry point address: 0x8048470 [...] some header fields 這是由linker所放置的,可告訴作業系統要從何處開始執行此執行檔[1]。如果我們用GDB載入程式並觀察0x8048470的位址,我們將可看到.text segment的第一個被執行的指令。 這代表的是,當linker連結可執行檔時,會把全部的內部符號引用的位址都確定下來(function以及data),確定它們的固定的、最終的位址。Linker本身會對自己進行一些relocation[2],但最終的結果不會有任何的relocation。 講啥啊?注意,我在上段文中特別強...