--[ 内容
0 - 前言
1 - strace的原理
2 - strace死循环的分析
3 - anti-strace
3.1 方法一
3.2 方法二
3.3 方法三
4 - anti anti-strace
4.1 int3的情况
4.2 kill的情况
5 - 参考
6 - strace.4.5.8.patch
--[ 0 - 前言
前面在介绍Burneye加密文档的时候,碰到了两个问题,一个是GDB中无法配置断点,另一个
问题是strace时死循环。GDB的问题已找到,无法配置断点是GDB的一个Bug,具体的结
论见[1].至于strace的问题,一直没有解决,假如真能写出一个让strace死循环的程式,
也算是一种anti-strace的技术。但是一直没有将死循环的现象用程式重现。
后来经Grip2的指点,发现了问题的原因,经过对内核和strace源代码的研究,写了一个
防止strace死循环的patch,之后更进一步的patch,使得strace更加健壮,能够跟踪anti-
strace程式的系统调用。
在这里感谢Grip2的帮助和测试程式。
本文的环境是Redhat Fedora Core 2, Linux 2.6.5/2.6.8.1,
gcc 3.3.1, strace 4.5.8
--[ 1 - strace的原理
要想了解strace的原理,首先得谈谈ptrace。
ptrace是操作系统为了调试为用户程式提供的系统接口。先来看看ptrace的用法:[2]
long ptrace(enum __ptrace_request request, pid_t pid, void *addr, void
*data)
strace需要使用的__ptrace_request主要有以下几个:
被调试的进程)
PTRACE_TRACEME 自己主动提供被跟踪的请求,当被跟踪的进程收到信号时,会先被
父进程截获.同样,execve时也是如此.
监控进程strace)
PTRACE_GETREGS 获得被跟踪进程的寄存器状况,周详的结构请参见asm/user.h的
user_regs_struct
PTRACE_PEEKDATA 获得系统堆栈中的参数
PTRACE_SYSCALL 这是最重要的,每次本跟踪的进程在系统调用时,ptrace会返回
两次,一次是系统调用之前,会调用PTRACE_PEEKDATA获得参数
值,另一次是系统调用之后,会调用PTRACE_GETREGS获得返回值
ENTRY(system_call)
...
# system call tracing in operation
testb $(_TIF_SYSCALL_TRACE|_TIF_SYSCALL_AUDIT),TI_flags(%ebp)
jnz syscall_trace_entry
...
syscall_trace_entry:
movl $-ENOSYS,EAX(%esp)
movl %esp, %eax
xorl %edx,%edx
call do_syscall_trace do_sigaction()
2298 if (signal_pending(current)) {
2299 /*
2300 * If there might be a fatal signal pending on multiple
2301 * threads, make sure we take it before changing the action.
2302 */
2303 spin_unlock_irq(¤t->sighand->siglock);
2304 return -ERESTARTNOINTR;
2305 }
也就是说当程式执行sys_signal时,假如有信号还未处理,就直接返回-ERESTARTNOINTR
接下来当系统调用返回时,会依次调用
resume_userspace->work_pending->work_notify_sig->do_notify_resume->do_sign
al
590 no_signal:
591 /* Did we come from a system call? */
592 if (regs->orig_eax >= 0) {
593 /* Restart the system call - no handlers present */
594 if (regs->eax == -ERESTARTNOHAND ||
595 regs->eax == -ERESTARTSYS ||
596 regs->eax == -ERESTARTNOINTR) {
597 regs->eax = regs->orig_eax;
598 regs->eip -= 2;
599 }
600 if (regs->eax == -ERESTART_RESTARTBLOCK){
601 regs->eax = __NR_restart_syscall;
602 regs->eip -= 2;
603 }
604 }
605 return 0;
606 }
此时, regs->eip -= 2;正好代表int $0x80 (0xcd 0x80)两个字节,可见,内核重启
系统调用。
那么,究竟什么时候signal_pending(current)为真呢?经过GDB调试,发现strace在处理
sys_signal系统调用时,syscall.c:trace_syscall会调用signal的sys_signal函数
sys_res = (*sysent[tcp->scno].sys_func)(tcp)
signal.c::sys_signal()
...
#ifndef USE_PROCFS
if (tcp->u_arg[0] == SIGTRAP) {
tcp->flags |= TCB_SIGTRAPPED;
kill(tcp->pid, SIGSTOP);
}
#endif /* !USE_PROCFS */
死循环的问题就在这个kill(tcp->pid, SIGSTOP)上,当程式被处于跟踪的时刻,向已
停止的进程发送SIGSTOP本来是没有必要的,不知道strace的作者为什么还要单独来上这
么一句?Linux 2.4和2.6内核又出现了差异,在2.6内核的do_sigaction判断了是否有信
号pending,而2.4却没有,因此在2.4的机器上,运行strace不会出现死循环的情况,在
2.6上,我们只须将改行注释掉即可。
我们能够认为这是strace和2.6内核不兼容的一个Bug!
注意:假如您在程式里用的是C库的signal,实际上使用的是sys_rt_sigaction而不是
sys_signal,而strace在处理sys_rt_sigaction时,并没有kill(tcp->pid, SIGSTOP);
也许strace的作者认为用C写的程式不会用到sys_signal?
接下来让我们试一试新的strace来跟踪burneye加密的程式
#./strace /tmp/ls.new (ls.new是burneye加密的程式)
execve("/tmp/ls.new", ["/tmp/ls.new"], [/* 20 vars */]) = 0
signal(SIGTRAP, 0x5371991) = 0 (SIG_DFL)
--- SIGSEGV (Segmentation fault) @ 0 (0) ---
+++ killed by SIGSEGV ++
OK,不死循环了,但是我们现在还无法继续跟踪,因为burneye加密的时候使用了某些anti-
strace的技术。
--[ 3 - anti-strace的原理
了解了strace的工作原理,就能够有针对的使用anti-strace的技术
--[ 3.1 方法一
利用上边介绍的strace和2.6内核的不兼容,造成死循环.对上边打过patch的strace不适用
测试程式(Grip2提供)
#include
#include
#include
#include
#include
#include
#include
void sig_handler(int sig)
{
printf("signal trap\n");
return;
}
static inline int my_signal(int num, void *func)
{
int ret;
__asm__ __volatile__ ( "int $0x80"
:"=a"(ret)
:"0" (48), "b" ((long)num),
"c" ((int)func));
return ret;
}
int main(int argc, char *argv[])
{
my_signal(SIGTRAP, sig_handler);
return 0;
}
注意一定不能使用C库的signal,原因在前边已提过
--[ 3.2 方法二
自己发送int3
这种方法是Silvio Cesare在[3]中介绍的方法,由程式自己执行int3,这样会产生一个
陷阱,内核会向程式发送一个SIGTRAP信号,由于程式被跟踪,因此信号由strace截获,
根据strace的源代码,if (ptrace(PTRACE_SYSCALL, pid, (char *) 1, 0)
#include
#include
#include
#include
#include
#include
static int not_trace
void sig_handler(int sig)
{
not_trace++;
return;
}
int main(int argc, char *argv[])
{
signal(SIGTRAP, sig_handler);
__asm__ __volatile__ ( "int3" );
if(!not_trace){
printf("TRACING...\n");
exit(-1);
}
return 0;
}
--[ 3.3 方法三
程式使用kill向自己发送SIGTRAP,跟方法二类似,这里就不赘述了
kill(getpid(), SIGTRAP);
--[ 4 - anti anti-strace
现在我们来进一步完善strace,让他也能对付方法二和方法三,其实问题的关键就是看
strace在ptrace退出之后,下次使用ptrace能不能将SIGTRAP信号返回给被跟踪程式。
根据ptrace的手册页对PTRACE_CONT和PTRACE_SYSCALL的描述
PTRACE_CONT ... If data is non-zero and not SIGSTOP, it is interpreted as a
signal to be delivered to the child ...
PTRACE_SYSCALL ... Restarts the stopped child as for PTRACE_CONT
看来我们只须在下一次调用ptrace时指定返回的信号是SIGTRAP即可,但是不能胡乱发送,
只有在发现int3和kill(pid, SIGTRAP)的情况下才适用。
--[ 4.1 int3的情况
首先,我们需要判断int3的情况,因此,需要在strace.c::trace()最后添加以下几行
tracing:
if(ptrace(PTRACE_GETREGS, pid, NULL, (int)®s) scno != __NR_sigreturn && tcp->scno != __NR_rt_sigreturn)
--[ 4.2 kill的情况
kill情况比较简单,只须在sys_kill调用的第二次ptrace返回时,将返回值设定为SIGTRAP
if(tcp->scno == __NR_kill){
if(!(tcp->flags & TCB_INSYSCALL)){
tprintf("\n!! Self SIGTRAP !!\n");
if(ptrace(PTRACE_SYSCALL,
pid,
(char *)1,
SIGTRAP)
附录:
strace使用及举例
(一) strace 命令
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