최상단

컨텐츠

[Linux] strace - 시스템 콜과 시그널을 추적하자~

글 정보

Category
컴퓨터 이야기
2007. 6. 6. 04:58

본문


본 페이지는  리눅스 명령어 strace에 대한 페이지 입니다.

http://www.die.net/doc/linux/man/man1/strace.1.html 페이지를 참조하여 제작되었으며, 처음으로 해보는 번역이라 제가 봐도 참..이해가 안되는군요;;;

이 페이지는 이러한 명령어도 있다는 소개정도로만 해두고 자세한 내용은 원문을 참조하시는게 좋으실 듯 합니다^-^;;

 현재 DESCRIPTION 이하 부분은 번역되지 않았으며, 차후 필요성이 느껴지면 나머지도 번역하도록 하겠습니다^^;;


NAME 

strace - 시스템 콜과 시그널을 추적

SYNOPSIS 

strace [ -dffhiqrtttTvxx ] [ -acolumn ] [ -eexpr ] ... [ -ofile ] [ -ppid ] ... [ -sstrsize ] [ -uusername ] [ -Evar=val ] ... [ -Evar ] ... [ command [ arg ... ] ]

strace -c [ -eexpr ] ... [ -Ooverhead ] [ -Ssortby ] [ command [ arg ... ] ]

DESCRIPTION 

  strace의 가장 간단한 경우는 프로그램이 종료될 때까지 특정 명령어를 실행시키는 것이다. strace는 프로세스에 의해 호출되어지는 시스템콜과 프로세스가 받는 시그널을 가로채 기록한다. 각 시스템콜의 이름, 인자, 반환값들은 표준에러출력(stderr)으로 출력되거나 -o 옵션에 의해 명시된 파일로 출력된다.

  strace는  유용한 진단툴, 교육용툴, 디버깅 툴이다. 시스템 관리자, 진단자(diagnosticians), 트러블슈터들이 프로그램을 소스없이 추적하여 문제점을 찾을 수 있게 해준다. 추적하기 위해 재컴파일 될 필요가 없기 때문에 프로그램 소스가 필요치 않는 프로그램의 문제를 해결하기 위한 매우 중요한 부분들을 찾을수 있게 해준다.

   학생, 해커와 궁금증이 많은 사람들은 일반적인 프로그램을 추적함으로써 시스템콜과 시스템에 대하여 배울 수 있다. 그리고 프로그래머는 시스템 콜과 시그널들은 사용자/커널 인터페이스에서 발행하는 이벤트이기 때문에, 이 경계에 대한 면밀한 조사는 버그를 격리하고, 코드 안정성, 레이스컨디션(race conditions)을 찾아내기를 시도하기에 매우 유용하다는 것을 알 수 있을 것이다.


각 라인은 시스템콜 이름과 그 뒤에 인자, 그리고 반환값으로 이루어진다.

  예제 : 'cat /dev/null'의 strace 결과이다.

open("/dev/null", O_RDONLY) = 3

에러들(일반적으로 -1의 반환값을 가진다)은 errno 심볼을 가지고 에러문자열을 덧붙인다.

open("/foo/bar", O_RDONLY) = -1 ENOENT (No such file or directory)

시그널들은 시그널 심볼과 시그널 문자열로 출력된다. 다음은 'sleep 666' 명령어의 stracing과 interrupting에서 발취하였다.

sigsuspend([] <unfinished ...>
--- SIGINT (Interrupt) ---
+++ killed by SIGINT +++

인자들은 심볼릭한 형태로 출력된다. 이 예제는 '>>xyzzy' (출력 리디렉션(output redirection) 쉘 명령의 실행이다.

open("xyzzy", O_WRONLY|O_APPEND|O_CREAT, 0666) = 3

여기 open은 3개의 인자를 가지고 있며, 플래그 인자는 3개의 bitwire-OR 형태로 나누어져 표현되며 mode 값은 전통적인 방식처럼 8진수로 쓰여져 있다. 전통적이거나(traditional) Native한 사용법은 ANSI나 POSIX의 다르지만, 문자 형태를 더 선호한다. 어떤 경우에는 strace는 소스보다 더 읽기 쉬운 출력을 제공하기도 한다.

구조체 포인터는 디레퍼런스(포인터가 가리키는 번지에 수납된 데이터에 접근하기) 되어지며 맴버들은 자세하게 표현된다. 모든 경우 인자들은 최대한 가능한 C 같은 형식으로 표현된다. 예를 들어, 'ls -l /dev/null/' 명령어에서 가장 중요한 부분은 아래와 같다.

lstat("/dev/null", {st_mode=S_IFCHR|0666, st_rdev=makedev(1, 3), ...}) = 0

어떻게 'struct stat'의 인자가 디레퍼런스 되고 어떻게 각 맴버들이 심볼릭하게 표현되는지 나타낸다. 개별적으로, st_mode 멤버가 어떻게 숫자와 심볼릭한 bitwise-OR로 표현되는지 볼 수 있다. 또한 이 예제는 첫번째 인자인 lstat는 시스템콜의 입력이고 두번째 인자는 출력임을 나타낸다. 출력 인자는 시스템콜이 실패하여도 수정되지 않기 때문에, 인자는 항상 디레퍼런스 되지 않는다. 예를 들어 'ls -l'는 존재하지 않는 파일에 대하여 다음과 같은 결과를 생성한다.

lstat("/foo/bar", 0xb004) = -1 ENOENT (No such file or directory)

이 경우 현관불은 켜져있지만 집에는 아무도 없다.(???? 원문.In this case the porch light is on but nobody is home.)

캐릭터 포인터는 디레퍼런스 되고 C 문자열 형식으로 출력된다. 문자열에서 출력되지 않는 문자는 일반적인 C escape codes로 표현된다. 문자열의 strsize(기본값 32)갯수까지만 출력된다. 더 긴 문자열은 "로 닫아지고 생략되어진다. 'ls -l'에서 getpwuid 라이브러리 루틴으로 패스워드 파일을 읽는 부분이다.

read(3, "root::0:0:System Administrator:/"..., 1024) = 422

While structures are annotated using curly braces, simple pointers and arrays are printed using square brackets with commas separating elements. Here is an example from the command ``id'' on a system with supplementary group ids:

구조체가 {}(curly braces)로 사용하여 주석이 달리는 반면, 간단한 포인터와 배열은 [](square brackets)와 ,(콤마)를 사용하여 출력된다. 아래에 추가의 그룹 id들을 가지는 시스템에서 'id' 명령어를 나타낸다.

getgroups(32, [100, 0]) = 2

반면, 비트셋(bit-sets)들은 []로 표현되나 set elements는 스페이스에 의해서만 구분되어진다. 아래는 쉘에서 외부 명령어를 실행하기 위해 준비하는 부분이다.

sigprocmask(SIG_BLOCK, [CHLD TTOU], []) = 0

Here the second argument is a bit-set of two signals, SIGCHLD and SIGTTOU. In some cases the bit-set is so full that printing out the unset elements is more valuable. In that case, the bit-set is prefixed by a tilde like this:

두번째 인자는 두 시그널(SIGCHLD와 SIGTTOU)의 비트셋이다. 어떤 경우에 비트셋은 설정되지 않은 요소들이 더 중요할 경우 ~를 접두사를 가지고 출력된다.

sigprocmask(SIG_UNBLOCK, ~[], NULL) = 0

여기서 두번째 인자는 모든 시그널이 설정되어 있는 것을 나타낸다.


OPTIONS

-c
Count time, calls, and errors for each system call and report a summary on program exit. On Linux, this attempts to show system time (CPU time spent running in the kernel) independent of wall clock time. If -c is used with -f or -F (below), only aggregate totals for all traced processes are kept.
-d
Show some debugging output of strace itself on the standard error.
-f
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).
-ff
If the -o filename option is in effect, each processes trace is written to filename.pid where pid is the numeric process id of each process. This is incompatible with -c, since no per-process counts are kept.
-F
Attempt to follow vforks. (On SunOS 4.x, this is accomplished with some dynamic linking trickery.) Otherwise, vforks will not be followed even if -f has been given.
-h
Print the help summary.
-i
Print the instruction pointer at the time of the system call.
-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.
-t
Prefix each line of the trace with the time of day.
-tt
If given twice, the time printed will include the microseconds.
-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
Show the time spent in system calls. This records the time difference between the beginning and the end of each system call.
-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
Print the version number of strace.
-x
Print all non-ASCII strings in hexadecimal string format.
-xx
Print all strings in hexadecimal string format.
-a column
Align return values in a specific column (default column 40).
-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]...
where qualifier is one of trace, abbrev, verbose, raw, signal, read, or write and value is a qualifier-dependent symbol or number. The default qualifier is trace. Using an exclamation mark negates the set of values. For example, -eopen means literally -e trace=open which in turn means trace only the open system call. By contrast, -etrace=!open means to trace every system call except open. In addition, the special values all and none have the obvious meanings.
Note that some shells use the exclamation point for history expansion even inside quoted arguments. If so, you must escape the exclamation point with a backslash.
-e trace=set
Trace only the specified set of system calls. The -c option is useful for determining which system calls might be useful to trace. For example, trace=open,close,read,write means to only trace those four system calls. Be careful when making inferences about the user/kernel boundary if only a subset of system calls are being monitored. The default is trace=all.
-e trace=file
Trace all system calls which take a file name as an argument. You can think of this as an abbreviation for -e trace=open,stat,chmod,unlink,... which is useful to seeing what files the process is referencing. Furthermore, using the abbreviation will ensure that you don't accidentally forget to include a call like lstat in the list. Betchya woulda forgot that one.
-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
Trace all the network related system calls.
-e trace=signal
Trace all signal related system calls.
-e trace=ipc
Trace all IPC related system calls.
-e trace=desc
Trace all file descriptor related system calls.
-e abbrev=set
Abbreviate the output from printing each member of large structures. The default is abbrev=all. The -v option has the effect of 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 specified 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
Trace only the specified subset of signals. The default is signal=all. For example, signal=!SIGIO (or signal=!io) causes SIGIO signals not to be traced.
-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.
-o filename
Write the trace output to the file filename rather than to 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 accuracy 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
Attach to the process with the process ID pid and begin tracing. The trace may be terminated at any time by a keyboard interrupt signal (CTRL-C). strace will respond by detaching itself from the traced process(es) leaving it (them) to continue running. Multiple -p options can be used to attach to up to 32 processes in addition to command (which is optional if at least one -p option is given).
-s strsize
Specify the maximum string size to print (the default is 32). Note that filenames are not considered strings and are always printed in full.
-S sortby
Sort the output of the histogram printed by the -c option by the specified criterion. Legal values are time, calls, name, and nothing (default time).
-u username
Run command with the user ID, group ID, and supplementary groups of username. This option is only useful when running as root and enables the correct execution of setuid and/or setgid binaries. Unless this option is used setuid and setgid programs are executed without effective privileges.
-E var=val
Run command with var=val in its list of environment variables.
-E var
Remove var from the inherited list of environment variables before passing it on to the command.

SETUID INSTALLATION

If strace is installed setuid to root then the invoking user will be able to attach to and trace processes owned by any user. In addition setuid and setgid programs will be executed and traced with the correct effective privileges. Since only users trusted with full root privileges should be allowed to do these things, it only makes sense to install strace as setuid to root when the users who can execute it are restricted to those users who have this trust. For example, it makes sense to install a special version of strace with mode `rwsr-xr--', user root and group trace, where members of the trace group are trusted users. If you do use this feature, please remember to install a non-setuid version of strace for ordinary lusers to use.

SEE ALSO

ltrace(1), time(1), ptrace(2), proc(5)

NOTES

It is a pity that so much tracing clutter is produced by systems employing shared libraries.

It is instructive to think about system call inputs and outputs as data-flow across the user/kernel boundary. Because user-space and kernel-space are separate and address-protected, it is sometimes possible to make deductive inferences about process behavior using inputs and outputs as propositions.

In some cases, a system call will differ from the documented behavior or have a different name. For example, on System V-derived systems the true time(2) system call does not take an argument and the stat function is called xstat and takes an extra leading argument. These discrepancies are normal but idiosyncratic characteristics of the system call interface and are accounted for by C library wrapper functions.

On some platforms a process that has a system call trace applied to it with the -p option will receive a SIGSTOP. This signal may interrupt a system call that is not restartable. This may have an unpredictable effect on the process if the process takes no action to restart the system call.

BUGS

Programs that use the setuid bit do not have effective user ID privileges while being traced.

A traced process ignores SIGSTOP except on SVR4 platforms.

A traced process which tries to block SIGTRAP will be sent a SIGSTOP in an attempt to force continuation of tracing.

A traced process runs slowly.

Traced processes which are descended from command may be left running after an interrupt signal (CTRL-C).

On Linux, exciting as it would be, tracing the init process is forbidden.

The -i option is weakly supported.

HISTORY

strace The original strace was written by Paul Kranenburg for SunOS and was inspired by its trace utility. The SunOS version of strace was ported to Linux and enhanced by Branko Lankester, who also wrote the Linux kernel support. Even though Paul released strace 2.5 in 1992, Branko's work was based on Paul's strace 1.5 release from 1991. In 1993, Rick Sladkey merged strace 2.5 for SunOS and the second release of strace for Linux, added many of the features of truss(1) from SVR4, and produced an strace that worked on both platforms. In 1994 Rick ported strace to SVR4 and Solaris and wrote the automatic configuration support. In 1995 he ported strace to Irix and tired of writing about himself in the third person.

PROBLEMS

Problems with strace should be reported via the Debian Bug Tracking System, or to the strace mailing list at <strace-devel@lists.sourceforge.net>.

REFERENCED BY

dstat(1), htop(1), xxd(1)

이 글은 스프링노트에서 작성되었습니다.

트랙백과 댓글 여닫기

TOP