目錄
- 實驗背景
- 1. 描述符表
- 2. 特權級
- 2. 中斷程序
- 3. 系統呼叫使用
- 4. 系統呼叫程序
- 實驗目的
- 實驗內容
- 實驗報告
- 實驗結果
- 參考資料
實驗背景
1. 描述符表
作業系統加載程式 setup.s 讀取系統引數至 0x90000 處覆寫 bootsect.s 程式, 然后將 system 模塊下移動到 0x00000 處,.同時,加載中斷描述符表暫存器 idtr 和全域描述符表暫存器 gdtr,設定CPU的控制暫存器 CR0/程式狀態字 PSW,從而進入32位保護模式,跳轉到 head.s 開頭執行,
為了能讓 head.s 在32位保護模式下運行,程式臨時設定中斷描述符表 idt 和全域描述符表 gdt,并在 gdt 中設定當前內核代碼段的描述符和資料段的描述符,

資料段描述符和代碼段描述符存放在gdt 表內,暫存器 gdtr 由基地址和段限長組成,處理器通過暫存器 gdtr 定位 gdt 表,

段選擇符由描述符索引、表指示器 TI 和請求者特權級欄位組成,描述符索參考于選擇指定描述符表中
8192
(
2
1
3
)
8192(2^13)
8192(213) 個描述符的一個,表指示器 TI 值為
0
0
0 表示指定 gdt 表,值為
1
1
1 表示指定 idt 表,而請求者特權級用于保護機制,

2. 特權級

處理器的段保護機制可以識別4個特權級 R0~R3,數值越大特權越小,環中心為核心態,最外層為用戶態,處理器利用特權級防止運行在較低特權級的程式或人物訪問具有較高特權級的一個段,
為了在各個代碼段和資料段之間進行特權級檢測處理,處理器可以識別以下三種型別的特權級:
- 當前特權級
CPL(Current Privilege Level):CPL存放在CS和SS段暫存器的位0和位1,代表正在執行的程式或任務的特權級, - 描述符特權級
DPL(Descriptor Privilege Level):當程式訪問資料時,DPL存放在資料段的DPL欄位,代表訪問當前資料段所需要的特權級, - 請求特權級別
RPL(Request Privilge Level):RPL通過段選擇符的第0和第1位表現出來的,RPL相當于附加的一個權限控制,防止低特權級程式出現高特權級代碼,從而能夠越權訪問資料段,但只有當RPL>DPL的時候,才起到實際的限制作用,

2. 中斷程序
中斷來源包括外部硬體和內部軟體兩部分,系統呼叫需要使用 int 0x80 軟體中斷指令修改 CPL 值,實作處理器內核態和用戶態的切換,
中斷描述符表 idt 可以駐留在記憶體的任何地方,處理器使用啟動時設定的 idtr 暫存器定位 idt 表的位置,idtr 暫存器包含 idt 表32位的基地址和16位的長度值,

idt 表可存放中斷門、陷阱門和任務門三種型別的門描述符,中斷門含有一個長指標(段選擇符和偏移值),處理器使用該長指標把程式執行權轉移到代碼段的中斷處理程序中,


3. 系統呼叫使用

庫函式 printf() 對應的指令本質實際上是將一些資料 write()到顯存的某些位置,而且輸出到螢屏是IO操作,所以需要使用中斷指令進入內核執行系統呼叫例程,
下面給出庫函式API和C代碼中嵌入匯編代碼兩種方式使用同一個系統呼叫 write():
#include <fcntl.h> /* open() */
#include <unistd.h> /* write() */
#include <string.h> /* strlen() */
int main()
{
int fd = open("write.txt", O_RDWR|O_CREAT);
char *buf = "hello,world!\n";
int count = strlen(buf);
write( fd, buf, count);
close( fd );
return 0;
}
編譯執行,成功生成檔案并寫入字串:

下面使用C代碼內嵌匯編的方法自制系統呼叫 my_write():
查詢當前LINUX作業系統的系統呼叫表(System Call Table),可知 write 系統呼叫號為 1,而LINUX0.11的 write 系統呼叫號為4,

內嵌匯編的語法如下:
_asm_ _volatile_ (
匯編陳述句模版;
輸出部分;
輸入部分;
破壞描述部分;
);
匯編語言部分將 write 系統呼叫號保存至 rax,使用 syscall 而非 int $0x80 觸發系統呼叫,輸入部分從記憶體 m 獲取檔案描述符 fd,字串指標 buf 和字串長度 count,輸出部分回傳錯誤資訊 res,
int my_write(int fd, const void *buf, int count)
{
int res = 0;
asm("movl $1, %%rax\n\t" /* 系統呼叫號sys_write(1) */
"syscall\n\t" /* 觸發系統呼叫 */
:"=a"(res) /* 輸出部分:變數res */
:"m"(fd), "m"(buf), "m"(count) /* 輸入部分:檔案描述符fd, 字串指標buf,字串長度count */
);
return res;
}
C代碼中嵌入匯編代碼方式使用系統呼叫 my_write():
#include <fcntl.h> /* open() */
#include <unistd.h> /* write() close() */
#include <string.h> /* strlen() */
int my_write(int fd, const void *buf, int count)
{
int res = 0;
asm("movl $1, %%rax\n\t" /* 系統呼叫號sys_write(1) */
"syscall\n\t" /* 觸發系統呼叫 */
:"=a"(res) /* 輸出部分:變數res */
:"m"(fd), "m"(buf), "m"(count) /* 輸入部分:檔案描述符fd, 字串指標buf,字串長度count */
);
return res;
}
int main()
{
int fd = open("write.txt", O_RDWR|O_CREAT);
char *buf = "hello,world!\n";
int count = strlen(buf);
my_write( fd, buf, count);
close( fd );
return 0;
}
再次編譯執行,成功生成檔案并寫入字串:

4. 系統呼叫程序
LINUX將匯編代碼層層封裝,程式之間互相呼叫,方便代碼的重用

- 源程式
lib/write.c:展開宏定義_syscall3,作用相當于write(int fd, const void *buf, int count):
// lib/write.c
#include <unistd.h>
_syscall3(int,write,int,fd,const char *,buf,off_t,count)
- 頭檔案
include/unistd.h:系統呼叫宏定義_syscall3包含3個引數,C宏定義使用中斷指令int $0x80觸發系統呼叫write,系統呼叫號__NR_write為4,其余內容與內嵌匯編代碼基本一一對應,中斷指令int $0x80觸發系統呼叫中斷,從而進入匯編程式system_call.s
#define __NR_write 4
#define _syscall3(type,name,atype,a,btype,b,ctype,c) \
type name(atype a,btype b,ctype c) \
{ \
long __res; \
__asm__ volatile ("int $0x80" \
: "=a" (__res) \
: "0" (__NR_##name),"b" ((long)(a)),"c" ((long)(b)),"d" ((long)(c))); \
if (__res>=0) \
return (type) __res; \
errno=-__res; \
return -1; \
}
- 匯編程式
kernel/system_call.s:nr_system_calls代表系統呼叫號的總數,push %ebx, %ecx, %edx代表系統呼叫宏定義的引數個數,call sys_call_table + 4 * %eax進入sys.h查詢系統呼叫表,其中eax中放的是系統呼叫號__NR_write,

- 頭檔案
include/linux/sys.h:系統呼叫表sys_call_table[]包含系統所需的所有系統呼叫指標,每個陣列元素對應一個extern int函式參考,根據__NR_write查找系統呼叫表的sys_write,跳轉到源程式read_write.c使用函式sys_write()
fn_ptr sys_call_table[] = { sys_setup, sys_exit, sys_fork, sys_read, sys_write, ...
實驗目的
建立對系統呼叫介面的深入認識
掌握系統呼叫的基本程序
能完成系統呼叫的全面控制
為后續實驗做準備
實驗內容
此次實驗的基本內容是:在Linux 0.11上添加兩個系統呼叫,并撰寫兩個簡單的應用程式測驗它們,

實驗報告
系統呼叫程序是從上至下的,所以添加系統呼叫應該從下至上進行,同時因為實驗一作業系統啟動的修改,Bochs已經無法正常啟動,所以需要重新下載 oslab 檔案進行修改,
1.添加 kernel/who.c 系統呼叫 sys_iam() 和 sys_whoami():
#define __LIBRARY__
#include <unistd.h>
#include <errno.h> /* 要求設定錯誤為EINVAL */
#include <asm/segment.h> /* 使用put_fs_byte和get_fs_byte */
char temp[64]={0}; /* 存盤sys_iam獲取的字串 */
int sys_iam(const char* name)
{
int i=0; /* 用戶空間資料name長度 */
while(get_fs_byte(name+i)!='\0') i++;
if(i>23) return -EINVAL;
printk("%d\n",i);
i=0; /* 獲取name至temp */
while((temp[i]=get_fs_byte(name+i))!='\0'){
i++;
}
return i;
}
int sys_whoami(char* name,unsigned int size)
{
int i=0; /* 內核空間資料temp長度 */
while (temp[i]!='\0') i++;
if (size<i) return -1;
i=0; /* 獲取temp至name */
while(temp[i]!='\0'){
put_fs_byte(temp[i],(name+i));
i++;
}
return i;
}
2.修改 include/linux/sys.h:系統呼叫表 sys_call_table[] 內添加系統呼叫函式指標及函式參考

3.修改 kernel/system_call.s 系統呼叫總數:
nr_system_calls = 74
4.include/unistd.h 添加系統呼叫號:
#define __NR_whoami 72
#define __NR_iam 73
5.修改 kernel/Makefile 鏈接 who.c 與其他LINUX代碼:
OBJS = sched.o system_call.o traps.o asm.o fork.o \
panic.o printk.o vsprintf.o sys.o exit.o \
signal.o mktime.o who.o
...
### Dependencies:
who.s who.o: who.c ../include/linux/kernel.h ../include/unistd.h
exit.s exit.o: exit.c ../include/errno.h ../include/signal.h \
../include/sys/types.h ../include/sys/wait.h ../include/linux/sched.h \
../include/linux/head.h ../include/linux/fs.h ../include/linux/mm.h \
../include/linux/kernel.h ../include/linux/tty.h ../include/termios.h \
../include/asm/segment.h
至此,添加系統呼叫的作業已經基本完成,
實驗結果
下面需要通過 iam.c 和 whoami.c 程式測驗系統呼叫,
/* iam.c */
#define __LIBRARY__
#include "unistd.h"
_syscall1(int, iam, const char*, name);
int main(int argc, char** argv){
int wlen = 0;
if(argc < 1){
printf("not enougth argument\n");
return -2;
}
wlen = iam(argv[1]);
return wlen;
}
/* whoami.c */
#define __LIBRARY__
#include "unistd.h"
_syscall2(int, whoami,char*,name,unsigned int,size);
int main(int argc, char** argv){
char buf[30];
int rlen;
rlen = whoami(buf, 30);
printf("%s\n", buf);
return rlen;
}
腳本測驗檔案 testlab2.c 和 testlab.sh 評分,為了避免尋找及下載的麻煩,下面直接給出代碼:
/* testlab2.c */
/*
* Compile: "gcc testlab2.c"
* Run: "./a.out"
*/
#include <string.h>
#include <assert.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#define __LIBRARY__
#include <unistd.h>
_syscall2(int, whoami,char*,name,unsigned int,size);
_syscall1(int, iam, const char*, name);
#define MAX_NAME_LEN 23
#define NAMEBUF_SIZE (MAX_NAME_LEN + 1)
/* truncate a long name to SHORT_NAME_LEN for display */
#define SHORT_NAME_LEN (MAX_NAME_LEN + 2)
/* name score */
#define TEST_CASE { \
{"x", 10, 1, NAMEBUF_SIZE, 1},\
{"sunner", 10, 6, NAMEBUF_SIZE, 6},\
{"Twenty-three characters", 5, 23, NAMEBUF_SIZE, 23},\
{"123456789009876543211234", 5, -1, 0, -1},\
{"abcdefghijklmnopqrstuvwxyz", 5, -1, 0, -1},\
{"Linus Torvalds", 5, 14, NAMEBUF_SIZE, 14},\
{"", 5, 0, NAMEBUF_SIZE, 0},\
{"whoami(0xbalabala, 10)", 5, 22, 10, -1},\
{NULL, 0, 0, 0, 0} /* End of cases */ \
}
/*改動一:增加size,和rval2*/
int test(const char* name, int max_score, int expected_rval1, int size, int expected_rval2);
void print_message(const char* msgfmt, const char* name);
struct test_case
{
char *name;
int score;
int rval1; /* return value of iam() */
/*改動2:增加size,和rval2定義*/
int size; /*Patch for whoami,2009.11.2*/
int rval2; /* return value of whoami() */
};
int main(void)
{
struct test_case cases[] = TEST_CASE;
int total_score=0, i=0;
while (cases[i].score != 0)
{
int score;
printf("Test case %d:", i+1);
/*改動3:增加size,和rval2的引數阿*/
score = test( cases[i].name,
cases[i].score,
cases[i].rval1,
cases[i].size,
cases[i].rval2 );
total_score += score;
i++;
}
printf("Final result: %d%%\n", total_score);
return 0;
}
/*改動4:增加size,和rval2的宣告*/
int test(const char* name, int max_score, int expected_rval1, int size, int expected_rval2)
{
int rval;
int len;
char * gotname;
int score=-1;
assert(name != NULL);
print_message("name = \"%s\", length = %d...", name);
/*Test iam()*/
len = strlen(name);
rval = iam(name);
/* printf("Return value = %d\n", rval);*/
/*改動5:增加的expected_rval1*/
if (rval == expected_rval1)
{
if (rval == -1 && errno == EINVAL) /*The system call can detect bad name*/
{
/* print_message("Long name, %s(%d), detected.\n", name);*/
printf("PASS\n");
score = max_score;
}
else if (rval == -1 && errno != EINVAL)
{
printf("\nERROR iam(): Bad errno %d. It should be %d(EINVAL).\n", errno, EINVAL);
score = 0;
}
/* iam() is good. Test whoami() next. */
}
else
{
printf("\nERROR iam(): Return value is %d. It should be %d.\n", rval, expected_rval1);
score = 0;
}
if (score != -1)
return score;
/*Test whoami()*/
gotname = (char*)malloc(len+1);
if (gotname == NULL)
exit(-1);
memset(gotname, 0, len+1);
/* printf("Get: buffer length = %d.\n", len+1); */
rval = whoami(gotname, size);
/* printf("Return value = %d\n", rval); */
/*改動6:增加的expected_rval2*/
/*改動++:比較多 ,但還是順序的改改*/
if(rval == expected_rval2)
{
if(rval == -1)
{
printf("PASS\n");
score = max_score;
}
else
{
if (strcmp(gotname, name) == 0)
{
/* print_message("Great! We got %s(%d) finally!\n", gotname); */
printf("PASS\n");
score = max_score;
}
else
{
print_message("\nERROR whoami(): we got %s(%d). ", gotname);
print_message("It should be %s(%d).\n", name);
score = 0;
}
}
}
else if (rval == -1)
{
printf("\nERROR whoami(): Return value is -1 and errno is %d. Why?\n", errno);
score = 0;
}
else
{
printf("\nERROR whoami(): Return value should be %d, not %d.\n", expected_rval2, rval);
score = 0;
}
free(gotname);
assert(score != -1);
return score;
}
void print_message(const char* msgfmt, const char* name)
{
char short_name[SHORT_NAME_LEN + 4] = {0};
int len;
len = strlen(name);
if (len == 0)
{
strcpy(short_name, "NULL");
}
else if (len <= SHORT_NAME_LEN)
{
strcpy(short_name, name);
}
else
{
memset(short_name, '.', SHORT_NAME_LEN+3);
memcpy(short_name, name, SHORT_NAME_LEN);
}
printf(msgfmt, short_name, len);
}
/* testlab2.sh */
#/bin/sh
string1="Sunner"
string2="Richard Stallman"
string3="This is a very very long string!"
score1=10
score2=10
score3=10
expected1="Sunner"
expected2="Richard Stallman"
expected3="Richard Stallman"
echo Testing string:$string1
./iam "$string1"
result=`./whoami`
if [ "$result" = "$expected1" ]; then
echo PASS.
else
score1=0
echo FAILED.
fi
score=$score1
echo Testing string:$string2
./iam "$string2"
result=`./whoami`
if [ "$result" = "$expected2" ]; then
echo PASS.
else
score2=0
echo FAILED.
fi
score=$score+$score2
echo Testing string:$string3
./iam "$string3"
result=`./whoami`
if [ "$result" = "$expected3" ]; then
echo PASS.
else
score3=0
echo FAILED.
fi
score=$score+$score3
let "totalscore=$score"
echo Score: $score = $totalscore%
因為添加的系統呼叫只能在虛擬機中起作用,所以我們需要掛載虛擬硬碟
cd ~/oslab
sudo ./mount-hdc
然后將測驗檔案 iam.c 和 whoami.c,評分檔案 testlab2.c 和 testlab2.sh 復制到虛擬機 hdc/usr/root 目錄下,并使用下列替換虛擬機內的部分頭檔案:
sudo cp ~/oslab/linux-0.11/include/linux/sys.h ~/oslab/hdc/usr/include/linux/sys.h
sudo cp ~/oslab/linux-0.11/include/unistd.h ~/oslab/hdc/usr/include/unistd.h
卸載虛擬機器:
cd ~/oslab
sudo umount hdc
編譯檔案并運行 Bochs 模擬器:
cd linux-0.11
make all
../run
Bochs 執行編譯虛擬機內檔案,測驗字串 Sean's system call 并使用 testlab2 評分:
gcc -o iam iam.c
gcc -o whoami whoami.c
gcc -o testlab2 testlab2.c
sync
./iam "Sean's system call"
./whoami
./testlab2
結果顯示獲得該部分分數:

再使用 testlab2.sh 評分,結果顯示獲得該部分分數,剩余 20% 分數為實驗報告,
chmod +x testlab2.sh
./testlab2.sh

參考資料
《Linux內核完全注釋》
哈工大作業系統試驗2 系統呼叫
哈工大作業系統實驗課——系統呼叫(lab3)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/148573.html
標籤:java
