1. 程式人生 > >2018-2019-1 20189229《Linux內核原理與分析》第六周作業

2018-2019-1 20189229《Linux內核原理與分析》第六周作業

root onf miss copy lin get sys details ror

系統調用的三層機制(下)

本章主要講解在內核態跟蹤調試一個系統調用,進一步分析系統調用的內核處理過程。

給MenuOS增加命令

重現克隆新版本的meun,其中已添加了time/time-asm兩個系統調用函數,time為C語言方式顯示系統時間,time-asm為使用匯編方式顯示系統時間。如圖:
技術分享圖片

使用gdb跟蹤系統調用內核函數sys_time

使用下列命令調試內核
‘cd .. #返回到LinuxKernel目錄下‘
‘qemu -Kernel linux-3.18.6/arch/x86/boot/bzImage -initrd rootfs.img -S -s‘
技術分享圖片

啟動gdb,將linux-3.18.6內核加載進來,連接到target remote 1234端口:
‘file linux-3.18.6/vmlinux‘
‘target remote:1234‘
設置斷點,在sys_call處設置斷點。當系統執行中斷指令:int 0x80時,CPU會自動跳轉到system_call函數。那具體來了解system_call是如何跳轉與執行的呢?一下為system_call函數源碼,下面來分析具體system_call與中斷指令int 0x80的跳轉關系。

ENTRY(system_call)
491 RING0_INT_FRAME         # can‘t unwind into user space anyway
492 ASM_CLAC
493 pushl_cfi %eax          # save orig_eax
494 SAVE_ALL
495 GET_THREAD_INFO(%ebp)
496                 # system call tracing in operation / emulation
497 testl $_TIF_WORK_SYSCALL_ENTRY,TI_flags(%ebp)
498 jnz syscall_trace_entry
499 cmpl $(NR_syscalls), %eax
500 jae syscall_badsys
501syscall_call:
502 call *sys_call_table(,%eax,4)
503syscall_after_call:
504 movl %eax,PT_EAX(%esp)      # store the return value
505syscall_exit:
506 LOCKDEP_SYS_EXIT
507 DISABLE_INTERRUPTS(CLBR_ANY)    # make sure we don‘t miss an interrupt
508                 # setting need_resched or sigpending
509                 # between sampling and the iret
510 TRACE_IRQS_OFF
511 movl TI_flags(%ebp), %ecx
512 testl $_TIF_ALLWORK_MASK, %ecx  # current->work
513 jne syscall_exit_work
514
515restore_all:
516 TRACE_IRQS_IRET
517restore_all_notrace:
518#ifdef CONFIG_X86_ESPFIX32
519 movl PT_EFLAGS(%esp), %eax  # mix EFLAGS, SS and CS
520 # Warning: PT_OLDSS(%esp) contains the wrong/random values if we
521 # are returning to the kernel.
522 # See comments in process.c:copy_thread() for details.
523 movb PT_OLDSS(%esp), %ah
524 movb PT_CS(%esp), %al
525 andl $(X86_EFLAGS_VM | (SEGMENT_TI_MASK << 8) | SEGMENT_RPL_MASK), %eax
526 cmpl $((SEGMENT_LDT << 8) | USER_RPL), %eax
527 CFI_REMEMBER_STATE
528 je ldt_ss           # returning to user-space with LDT SS
529#endif
530restore_nocheck:
531 RESTORE_REGS 4          # skip orig_eax/error_code
532irq_return:
533 INTERRUPT_RETURN

系統調用在內核代碼中的處理過程

本節將仔細分析system_call作為一個中斷服務程序的來龍去脈。
以time為例,在用戶態調用time,通過gdb跟蹤內核裏面的系統調用函數sys_time,觸發一個系統調用到執行這個系統調用的內核處理函數,再到最後系統調用返回到用戶態。如圖所示:
技術分享圖片

中斷向量0x80和system_call中斷服務程序入口的關系

2018-2019-1 20189229《Linux內核原理與分析》第六周作業