strace使用詳解(轉)

strace使用詳解(轉)
(一) strace 命令
  
  用途:打印 STREAMS 跟蹤消息。
  語法:strace [ mid sid level ] ...
  描述:沒有參數的 strace 命令將所有的驅動程序和模塊中的所有 STREAMS 事件跟蹤消息寫到它的標準輸出中。 這些消息是從 STREAMS 日誌驅動程序中獲取的。如果提供參數,它們必須是在三元組中。每個三元組表明跟蹤消息要從給定的模塊或驅動程序、子標識(通常表明次要設備)以及優先級別等於或小於給定級別的模塊或驅動程序中接收。all 標記可由任何成員使用,以表明對該屬性沒有限制。
  參數:mid---指定 STREAMS 模塊的標識號 sid---指定子標識號 level----指定跟蹤優先級別
  輸出格式:每個跟蹤消息輸出的格式是:
   跟蹤序列號
   消息時間(格式爲 hh:mm:ss)
   系統啓動後,以機器滴答信號表示消息的時間
   跟蹤優先級別
   有以下值之一:
  E
   消息也在錯誤日誌中
  F
   表示一個致命錯誤
  N
   郵件已發送給系統管理員
   源的模塊標識號
   源的子標識號
   跟蹤消息的格式化文本
  在多處理器系統上, 由兩部分組成:消息所有者發送處的處理器號碼,格式化文本本身。
  一旦啓動,strace 命令將繼續執行,直到用戶終止該命令。
  
  注:由於性能的考慮,所以一次只允許一個 strace 命令來打開 STREAMS 日誌驅動程序。
  日誌驅動程序有一個三元組的列表(該列表在命令調用中指定),並且程序會根據該列表比較每個潛在的跟蹤消息,以決定是否要格式化和發送這個信息到 strace 進程中。因此,長的三元組列表會對 STREAMS 的總體性能的影響更大。 運行 strace 命令對於某些模塊和驅動程序(生成要發送給 strace 進程的跟蹤消息的模塊和驅動程序)的定時的影響最大。 如果跟蹤消息生成過快,以至 strace 進程無法處理,那麼就會丟失一些消息。 最後的情況可以通過檢查跟蹤消息輸出上的序列號來確定。
  
  示例
  要輸出模塊標識爲 41 的模塊或驅動程序中的所有跟蹤消息,請輸入:
  
  strace 41 all all
  要輸出模塊標識爲 41,子標識爲 0、1 或 2 的模塊或驅動程序中的跟蹤消息:
  
  strace 41 0 1 41 1 1 41 2 0
   子標識爲 0 和 1 的模塊或驅動程序中的消息必須具有小於或等於 1 的跟蹤級別。子標識爲 2 的模塊或驅動程序中的消息必須具有跟蹤級別 0。
  
  strace: option requires an argument -- e
  usage: strace [-dffhiqrtttTvVxx] [-a column] [-e expr] ... [-o file]
   [-p pid] ... [-s strsize] [-u username] [-E var=val] ...
   [command [arg ...]]
   or: strace -c [-e expr] ... [-O overhead] [-S sortby] [-E var=val] ...
   [command [arg ...]]
  -c -- count time, calls, and errors for each syscall and report summary
  -f -- follow forks, -ff -- with output into separate files
  -F -- attempt to follow vforks, -h -- print help message
  -i -- print instruction pointer at time of syscall
  -q -- suppress messages about attaching, detaching, etc.
  -r -- print relative timestamp, -t -- absolute timestamp, -tt -- with usecs
  -T -- print time spent in each syscall, -V -- print version
  -v -- verbose mode: print unabbreviated argv, stat, termio[s], etc. args
  -x -- print non-ascii strings in hex, -xx -- print all strings in hex
  -a column -- alignment COLUMN for printing syscall results (default 40)
  -e expr -- a qualifying expression: option=[!]all or option=[!]val1[,val2]...
   options: trace, abbrev, verbose, raw, signal, read, or write
  -o file -- send trace output to FILE instead of stderr
  -O overhead -- set overhead for tracing syscalls to OVERHEAD usecs
  -p pid -- trace process with process id PID, may be repeated
  -s strsize -- limit length of print strings to STRSIZE chars (default 32)
  -S sortby -- sort syscall counts by: time, calls, name, nothing (default time)
  -u username -- run command as username handling setuid and/or setgid
  -E var=val -- put var=val in the environment for command
  -E var -- remove var from the environment for command
  
  
  strace - 跟蹤系統調用和信號
  
  usage: strace [-dffhiqrtttTvVxx] [-a column] [-e expr] [-o file]
  [-p pid] [-s strsize] [-u username] [command [arg]]
  strace -c [-e expr] [-O overhead] [-S sortby] [command [arg]]
  
  -a column
   指定顯示返回值的列位置,默認是40(從0開始計數),就是說"="出現在40列的位
   置。
  
  -c 產生類似下面的統計信息
  
   strace -c -p 14653 (Ctrl-C)
   % time seconds usecs/call calls errors syscall
   ------ ----------- ----------- --------- --------- ----------------
   53.99 0.012987 3247 4 2 wait4
   42.16 0.010140 2028 5 read
   1.78 0.000429 61 7 write
   0.76 0.000184 10 18 ioctl
   0.50 0.000121 2 52 rt_sigprocmask
   0.48 0.000115 58 2 fork
   0.18 0.000043 2 18 rt_sigaction
   0.06 0.000014 14 1 1 stat
   0.03 0.000008 4 2 sigreturn
   0.02 0.000006 2 3 time
   0.02 0.000006 3 2 1 setpgid
   ------ ----------- ----------- --------- --------- ----------------
   100.00 0.024053 114 4 total
  
   -d 輸出一些strace自身的調試信息到標準輸出
  
   strace -c -p 14653 -d (Ctrl-C)
   [wait(0x137f) = 14653]
   pid 14653 stopped, [SIGSTOP]
   [wait(0x57f) = 14653]
   pid 14653 stopped, [SIGTRAP]
   cleanup: looking at pid 14653
   % time seconds usecs/call calls errors syscall
   ------ ----------- ----------- --------- --------- ----------------
   ------ ----------- ----------- --------- --------- ----------------
   100.00 0.000000 0 total
  
   -e expr
   A qualifying expression which modifies which events to trace or how to trace
   them. The format of the expression is:
  
   [qualifier=][!]value1[,value2]...
  
   這裏qualifier可以是trace、abbrev、verbose、raw、signal、read或者write。
   value是qualifier相關的符號或數值。缺省qualifier是trace。!表示取反。
   -eopen等價於-e trace=open,表示只跟蹤open系統調用。-etrace=!open意思是
   跟蹤除open系統調用之外的其他所有系統調用。此外value還可以取值all和none。
  
   某些shell用!表示重複歷史指令,此時可能需要引號、轉義符號(/)的幫助。
  
   -e trace=set
   只跟蹤指定的系統調用列表。決定跟蹤哪些系統調用時,-c選項很有用。
   trace=open,close,read,write意即只跟蹤這四種系統調用,缺省是trace=all
  
   -e trace=file
   跟蹤以指定文件名做參數的所有系統調用。
  
   -e trace=process
   Trace all system calls which involve process management. This is
   useful for watching the fork, wait, and exec steps of a process.
  
   -e trace=network
   跟蹤所有和網絡相關的系統調用
  
   -e trace=signal
   Trace all signal related system calls.
  
   -e trace=ipc
   Trace all IPC related system calls.
  
   -e abbrev=set
   Abbreviate the output from printing each member of large structures.
   缺省是abbrev=all,-v選項等價於abbrev=none
  
   -e verbose=set
   Dereference structures for the specified set of system calls.
   The default is verbose=all.
  
   -e raw=set
   Print raw, undecoded arguments for the specifed set of system calls.
   This option has the effect of causing all arguments to be printed in
   hexadecimal. This is mostly useful if you don"t trust the decoding or
   you need to know the actual numeric value of an argument.
  
   -e signal=set
   只跟蹤指定的信號列表,缺省是signal=all。signal=!SIGIO (or signal=!io)
   導致 SIGIO 信號不被跟蹤
  
   -e read=set
   Perform a full hexadecimal and ASCII dump of all the data read from
   file descriptors listed in the specified set. For example, to see all
   input activity on file descriptors 3 and 5 use -e read=3,5. Note that
   this is independent from the normal tracing of the read(2) system call
   which is controlled by the option -e trace=read.
  
   -e write=set
   Perform a full hexadecimal and ASCII dump of all the data written to
   file descriptors listed in the specified set. For example, to see all
   output activity on file descriptors 3 and 5 use -e write=3,5. Note
   that this is independent from the normal tracing of the write(2)
   system call which is controlled by the option -e trace=write.
  
   -f
   follow forks,跟隨子進程?
  
   Trace child processes as they are created by currently traced
   processes as a result of the fork(2) system call. The new process
   is attached to as soon as its pid is known (through the return value
   of fork(2) in the parent process). This means that such children may
   run uncontrolled for a while (especially in the case of a vfork(2)),
   until the parent is scheduled again to complete its (v)fork(2)
   call. If the parent process decides to wait(2) for a child that is
   currently being traced, it is suspended until an appropriate child
   process either terminates or incurs a signal that would cause it to
   terminate (as determined from the child"s current signal disposition).
  
   意思應該是說跟蹤某個進程時,如果發生fork()調用,則選擇跟蹤子進程
   可以參考gdb的set follow-fork-mode設置
  
   -F
   attempt to follow vforks
   (On SunOS 4.x, this is accomplished with some dynamic linking trickery.
   On Linux, it requires some kernel functionality not yet in the
   standard kernel.) Otherwise, vforks will not be followed even if -f
   has been given.
  
   類似-f選項
  
   -ff
   如果-o file選項有效指定,則跟蹤過程中新產生的其他相關進程的信息分別寫
   入file.pid,這裏pid是各個進程號。
  
   -h
   顯示幫助信息
  
   -i
   顯示發生系統調用時的IP寄存器值
   strace -p 14653 -i
  
   -o filename
   指定保存strace輸出信息的文件,默認使用標準錯誤輸出stderr
  
   Use filename.pid if -ff is used. If the argument begins with `|" or
   with `!" then the rest of the argument is treated as a command and all
   output is piped to it. This is convenient for piping the debugging
   output to a program without affecting the redirections of executed
   programs.
  
   -O overhead
   Set the overhead for tracing system calls to overhead microseconds.
   This is useful for overriding the default heuristic for guessing how
   much time is spent in mere measuring when timing system calls using
   the -c option. The acuracy of the heuristic can be gauged by timing
   a given program run without tracing (using time(1)) and comparing
   the accumulated system call time to the total produced using -c.
  
   好象是用於確定哪些系統調用耗時多
  
   -p pid
  
   指定待跟蹤的進程號,可以用Ctrl-C終止這種跟蹤而被跟蹤進程繼續運行。可以
   指定多達32個-p參數同時進行跟蹤。
  
   比如 strace -ff -o output -p 14653 -p 14117
  
   -q
   Suppress messages about attaching, detaching etc. This happens
   automatically when output is redirected to a file and the command is
   run directly instead of attaching.
  
   -r
   Print a relative timestamp upon entry to each system call. This
   records the time difference between the beginning of successive
   system calls.
  
   strace -p 14653 -i -r
  
   -s strsize
   指定字符串最大顯示長度,默認32。但文件名總是顯示完整。
   -S sortby
   Sort the output of the histogram printed by the -c option by the
   specified critereon. Legal values are time, calls, name, and nothing
   (default time).
  
   -t
   與-r選項類似,只不過-r採用相對時間戳,-t採用絕對時間戳(當前時鐘)
  
   -tt
   與-t類似,絕對時間戳中包含微秒
  
   -ttt
   If given thrice, the time printed will include the microseconds and
   the leading portion will be printed as the number of seconds since
   the epoch.
  
   -T
   這個選項顯示單個系統調用耗時
  
   -u username
   用指定用戶的UID、GID以及輔助組身份運行待跟蹤程序
  
   -v
   冗餘顯示模式
   Print unabbreviated versions of environment, stat, termios, etc. calls.
   These structures are very common in calls and so the default behavior
   displays a reasonable subset of structure members. Use this option to
   get all of the gory details.
  
   -V
   顯示strace版本信息
  
   -x 以16進制字符串格式顯示非ascii碼,比如"/x08",默認採用8進制,比如"/10"
  
   -xx 以16進制字符串格式顯示所有字節

===============================================

(二)應用
strace 命令是一種強大的工具,它能夠顯示所有由用戶空間程序發出的系統調用。
  strace 顯示這些調用的參數並返回符號形式的值。strace 從內核接收信息,而且不需要以任何特殊的方式來構建內核。
  下面記錄幾個常用 option .
  1 -f -F選項告訴strace同時跟蹤fork和vfork出來的進程
  2 -o xxx.txt 輸出到某個文件。
  3 -e execve 只記錄 execve 這類系統調用
  -------------------------------------------------------------------------------------------------------------------------
  進程無法啓動,軟件運行速度突然變慢,程序的"SegmentFault"等等都是讓每個Unix系統用戶頭痛的問題,
  本文通過三個實際案例演示如何使用truss、strace和ltrace這三個常用的調試工具來快速診斷軟件的"疑難雜症"。
  
  
  truss和strace用來跟蹤一個進程的系統調用或信號產生的情況,而 ltrace用來跟蹤進程調用庫函數的情況。truss是早期爲System V R4開發的調試程序,包括Aix、FreeBSD在內的大部分Unix系統都自帶了這個工具;
  而strace最初是爲SunOS系統編寫的,ltrace最早出現在GNU/DebianLinux中。
  這兩個工具現在也已被移植到了大部分Unix系統中,大多數Linux發行版都自帶了strace和ltrace,而FreeBSD也可通過Ports安裝它們。
  
  你不僅可以從命令行調試一個新開始的程序,也可以把truss、strace或ltrace綁定到一個已有的PID上來調試一個正在運行的程序。三個調試工具的基本使用方法大體相同,下面僅介紹三者共有,而且是最常用的三個命令行參數:
  
  -f :除了跟蹤當前進程外,還跟蹤其子進程。
  -o file :將輸出信息寫到文件file中,而不是顯示到標準錯誤輸出(stderr)。
  -p pid :綁定到一個由pid對應的正在運行的進程。此參數常用來調試後臺進程。
  
   使用上述三個參數基本上就可以完成大多數調試任務了,下面舉幾個命令行例子:
  truss -o ls.truss ls -al: 跟蹤ls -al的運行,將輸出信息寫到文件/tmp/ls.truss中。
  strace -f -o vim.strace vim: 跟蹤vim及其子進程的運行,將輸出信息寫到文件vim.strace。
  ltrace -p 234: 跟蹤一個pid爲234的已經在運行的進程。
  
   三個調試工具的輸出結果格式也很相似,以strace爲例:
  
  brk(0) = 0x8062aa8
  brk(0x8063000) = 0x8063000
  mmap2(NULL, 4096, PROT_READ, MAP_PRIVATE, 3, 0x92f) = 0x40016000
  
  每一行都是一條系統調用,等號左邊是系統調用的函數名及其參數,右邊是該調用的返回值。 truss、strace和ltrace的工作原理大同小異,都是使用ptrace系統調用跟蹤調試運行中的進程,詳細原理不在本文討論範圍內,有興趣可以參考它們的源代碼。
  舉兩個實例演示如何利用這三個調試工具診斷軟件的"疑難雜症":
  
  案例一:運行clint出現Segment Fault錯誤
  
  操作系統:FreeBSD-5.2.1-release
  clint是一個C++靜態源代碼分析工具,通過Ports安裝好之後,運行:
  
  # clint foo.cpp
  Segmentation fault (core dumped)
   在Unix系統中遇見"Segmentation Fault"就像在MS Windows中彈出"非法操作"對話框一樣令人討厭。OK,我們用truss給clint"把把脈":
  
  # truss -f -o clint.truss clint
  Segmentation fault (core dumped)
  # tail clint.truss
   739: read(0x6,0x806f000,0x1000) = 4096 (0x1000)
   739: fstat(6,0xbfbfe4d0) = 0 (0x0)
   739: fcntl(0x6,0x3,0x0) = 4 (0x4)
   739: fcntl(0x6,0x4,0x0) = 0 (0x0)
   739: close(6) = 0 (0x0)
   739: stat("/root/.clint/plugins",0xbfbfe680) ERR#2 'No such file or directory'
  SIGNAL 11
  SIGNAL 11
  Process stopped because of: 16
  process exit, rval = 139
  我們用truss跟蹤clint的系統調用執行情況,並把結果輸出到文件clint.truss,然後用tail查看最後幾行。
  注意看clint執行的最後一條系統調用(倒數第五行):stat("/root/.clint/plugins",0xbfbfe680) ERR#2 'No such file or directory',問題就出在這裏:clint找不到目錄"/root/.clint/plugins",從而引發了段錯誤。怎樣解決?很簡單: mkdir -p /root/.clint/plugins,不過這次運行clint還是會"Segmentation Fault"9。繼續用truss跟蹤,發現clint還需要這個目錄"/root/.clint/plugins/python",建好這個目錄後 clint終於能夠正常運行了。
  
  案例二:vim啓動速度明顯變慢
  
  操作系統:FreeBSD-5.2.1-release
  vim版本爲6.2.154,從命令行運行vim後,要等待近半分鐘才能進入編輯界面,而且沒有任何錯誤輸出。仔細檢查了.vimrc和所有的vim腳本都沒有錯誤配置,在網上也找不到類似問題的解決辦法,難不成要hacking source code?沒有必要,用truss就能找到問題所在:
  
  # truss -f -D -o vim.truss vim
  
  這裏-D參數的作用是:在每行輸出前加上相對時間戳,即每執行一條系統調用所耗費的時間。我們只要關注哪些系統調用耗費的時間比較長就可以了,用less仔細查看輸出文件vim.truss,很快就找到了疑點:
  
  735: 0.000021511 socket(0x2,0x1,0x0) = 4 (0x4)
  735: 0.000014248 setsockopt(0x4,0x6,0x1,0xbfbfe3c8,0x4) = 0 (0x0)
  735: 0.000013688 setsockopt(0x4,0xffff,0x8,0xbfbfe2ec,0x4) = 0 (0x0)
  735: 0.000203657 connect(0x4,{ AF_INET 10.57.18.27:6000 },16) ERR#61 'Connection refused'
  735: 0.000017042 close(4) = 0 (0x0)
  735: 1.009366553 nanosleep(0xbfbfe468,0xbfbfe460) = 0 (0x0)
  735: 0.000019556 socket(0x2,0x1,0x0) = 4 (0x4)
  735: 0.000013409 setsockopt(0x4,0x6,0x1,0xbfbfe3c8,0x4) = 0 (0x0)
  735: 0.000013130 setsockopt(0x4,0xffff,0x8,0xbfbfe2ec,0x4) = 0 (0x0)
  735: 0.000272102 connect(0x4,{ AF_INET 10.57.18.27:6000 },16) ERR#61 'Connection refused'
  735: 0.000015924 close(4) = 0 (0x0)
  735: 1.009338338 nanosleep(0xbfbfe468,0xbfbfe460) = 0 (0x0)
  
  vim試圖連接10.57.18.27這臺主機的6000端口(第四行的connect()),連接失敗後,睡眠一秒鐘繼續重試(第6行的 nanosleep())。以上片斷循環出現了十幾次,每次都要耗費一秒多鐘的時間,這就是vim明顯變慢的原因。可是,你肯定會納悶:"vim怎麼會無緣無故連接其它計算機的6000端口呢?"。問得好,那麼請你回想一下6000是什麼服務的端口?沒錯,就是X Server。看來vim是要把輸出定向到一個遠程X Server,那麼Shell中肯定定義了DISPLAY變量,查看.cshrc,果然有這麼一行:setenv DISPLAY ${REMOTEHOST}:0,把它註釋掉,再重新登錄,問題就解決了。
  
  
  案例三:用調試工具掌握軟件的工作原理
  
  操作系統:Red Hat Linux 9.0
  用調試工具實時跟蹤軟件的運行情況不僅是診斷軟件"疑難雜症"的有效的手段,也可幫助我們理清軟件的"脈絡",即快速掌握軟件的運行流程和工作原理,不失爲一種學習源代碼的輔助方法。下面這個案例展現瞭如何使用strace通過跟蹤別的軟件來"觸發靈感",從而解決軟件開發中的難題的。
  大家都知道,在進程內打開一個文件,都有唯一一個文件描述符(fd:file descriptor)與這個文件對應。而本人在開發一個軟件過程中遇到這樣一個問題:
  已知一個fd,如何獲取這個fd所對應文件的完整路徑?不管是Linux、FreeBSD或是其它Unix系統都沒有提供這樣的API,怎麼辦呢?我們換個角度思考:Unix下有沒有什麼軟件可以獲取進程打開了哪些文件?如果你經驗足夠豐富,很容易想到lsof,使用它既可以知道進程打開了哪些文件,也可以瞭解一個文件被哪個進程打開。好,我們用一個小程序來試驗一下lsof,看它是如何獲取進程打開了哪些文件。lsof: 顯示進程打開的文件。
  
  /* testlsof.c */
  #include #include #include #include #include
  int main(void)
  {
   open("/tmp/foo", O_CREAT|O_RDONLY); /* 打開文件/tmp/foo */
   sleep(1200); /* 睡眠1200秒,以便進行後續操作 */
   return 0;
  }
  
  將testlsof放入後臺運行,其pid爲3125。命令lsof -p 3125查看進程3125打開了哪些文件,我們用strace跟蹤lsof的運行,輸出結果保存在lsof.strace中:
  
  # gcc testlsof.c -o testlsof
  # ./testlsof &
  [1] 3125
  # strace -o lsof.strace lsof -p 3125
  
  我們以"/tmp/foo"爲關鍵字搜索輸出文件lsof.strace,結果只有一條:
  
  
  # grep '/tmp/foo' lsof.strace
  readlink("/proc/3125/fd/3", "/tmp/foo", 4096) = 8
  
  原來lsof巧妙的利用了/proc/nnnn/fd/目錄(nnnn爲pid):Linux內核會爲每一個進程在/proc/建立一個以其pid爲名的目錄用來保存進程的相關信息,而其子目錄fd保存的是該進程打開的所有文件的fd。目標離我們很近了。好,我們到/proc/3125/fd/看個究竟:
  
  # cd /proc/3125/fd/
  # ls -l
  total 0
  lrwx------ 1 root root 64 Nov 5 09:50 0 -> /dev/pts/0
  lrwx------ 1 root root 64 Nov 5 09:50 1 -> /dev/pts/0
  lrwx------ 1 root root 64 Nov 5 09:50 2 -> /dev/pts/0
  lr-x------ 1 root root 64 Nov 5 09:50 3 -> /tmp/foo
  # readlink /proc/3125/fd/3
  /tmp/foo
  
  答案已經很明顯了:/proc/nnnn/fd/目錄下的每一個fd文件都是符號鏈接,而此鏈接就指向被該進程打開的一個文件。我們只要用readlink()系統調用就可以獲取某個fd對應的文件了,代碼如下:
  
  
  #include #include #include #include #include #include
  int get_pathname_from_fd(int fd, char pathname[], int n)
  {
   char buf[1024];
   pid_t pid;
   bzero(buf, 1024);
   pid = getpid();
   snprintf(buf, 1024, "/proc/%i/fd/%i", pid, fd);
   return readlink(buf, pathname, n);
  }
  int main(void)
  {
   int fd;
   char pathname[4096];
   bzero(pathname, 4096);
   fd = open("/tmp/foo", O_CREAT|O_RDONLY);
   get_pathname_from_fd(fd, pathname, 4096);
   printf("fd=%d; pathname=%sn", fd, pathname);
   return 0;
  }
  
  出於安全方面的考慮,在FreeBSD 5 之後系統默認已經不再自動裝載proc文件系統,因此,要想使用truss或strace跟蹤程序,你必須手工裝載proc文件系統:mount -t procfs proc /proc;或者在/etc/fstab中加上一行:
  
  proc /proc procfs rw 0 0

(一)轉自:
http://www.tianyablog.com/blogger/post_show.asp?blogid=289546&postid=5311333
(二)轉自:http://www.tianyablog.com/blogger/post_show.asp?blogid=289546&postid=5311234
發佈了31 篇原創文章 · 獲贊 5 · 訪問量 23萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章