linux2022
3
ptrace 系統呼叫允許一個追蹤者 (tracer) 行程得以觀察或控制另外一個受追蹤者 (tracee) 行程的內容(如記憶體或暫存器)或執行流程。這主要用來實作除錯器 (debugger) 與系統呼叫的追蹤。使用這個系統呼叫之後,被追蹤者必須依附 (attach) 於追蹤者行程。該 attach 行為是以執行緒為單位,也就是說,在一個具備多個執行緒的行程中,其中每個執行緒都可個別 attach 在不同的追蹤者行程,或在其他執行緒被追蹤時,維持原本的執行流程。
延伸閱讀:
dont_trace
這個 Linux 核心模組利用 task_struct
內部成員 ptrace 來偵測給定的行程是否被除錯器或其他使用 ptrace 系統呼叫的程式所 attach,一旦偵測到其他行程嘗試追蹤該行程,dont_trace
就會主動 kill
追蹤者行程。流程:
task_struct
, which is simply a linked list that contains all the tracees that the process is "ptracing".SIGKILL
signal to each of them including the tracer. This results in killing both the tracer and its tracees.JIFFIES_DELAY
, which is set to 1. That is, the module will run every one jiffy. This can be changed through modifying the macro JIFFIES_DELAY
defined in the module.執行以下命令可得知目前 Linux 核心的 HZ
設定:
例如輸出 100
就表示 100 HZ,亦即週期為 秒。
GDB 使用示範:
預期可見類似以下輸出:
可在 GDB 執行以下命令,要求 yes
命令不再執行: ((gdb)
開頭表示 GDB 命令提示字元,不用輸入 (gdb)
字樣,只要輸入 signal
開始的 GDB 命令)
預期可見以下輸出:
一旦 dont_trace
掛載到 Linux 核心,重複上述操作時,會遇到截然不同的狀況:
也就是 GDB 無法去追蹤給定的 yes
行程,除非執行 sudo rmmod dont_trace
命令,GDB 一類使用 ptrace 系統呼叫的程式才可正確運作。
以下是 dont_trace.c
程式碼列表: (遮蔽部分程式碼)
對應的 Makefile
:
請研讀《The Linux Kernel Module Programming Guide》和《Demystifying the Linux CPU Scheduler》以理解相關背景知識,並補完程式碼,使得執行符合預期。作答規範:
periodic_routine
函式程式碼延伸問題: