是否可以将内置命令跟踪到Bash?


13

受题为:内置命令何时加载到内存的启发,在尝试回答此问题时,我尝试了以下命令,但由于无法运行而感到有些惊讶:

$ strace cd $HOME

有什么我可以利用的方法来为sash的内置命令运行strace吗?


1
您为什么认为strace不运行程序不会导致跟踪令人惊讶?
Bananguin

Answers:


15

如果您考虑如何strace工作,那么完全可以理解,Bash的所有内建函数都是不可追溯的。strace只能跟踪实际的可执行文件,而内置文件则不能。

例如,我的cd命令:

$ type cd
cd is a function
cd () 
{ 
    builtin cd "$@";
    local result=$?;
    __rvm_project_rvmrc;
    __rvm_after_cd;
    return $result
}

欺骗光盘的技巧?

我遇到过这种技术,您可以strace在实际bash过程中调用该方法,并以此cd方式间接进行跟踪。

$ stty -echo
$ cat | strace bash > /dev/null

这使我能够bash跟踪该过程,如下所示:

....
getegid()                               = 501
getuid()                                = 500
getgid()                                = 501
access("/bin/bash", X_OK)               = 0
stat("/bin/bash", {st_mode=S_IFREG|0755, st_size=940312, ...}) = 0
geteuid()                               = 500
getegid()                               = 501
getuid()                                = 500
getgid()                                = 501
access("/bin/bash", R_OK)               = 0
getpgrp()                               = 32438
rt_sigaction(SIGCHLD, {0x43e360, [], SA_RESTORER, 0x34e7233140}, {SIG_DFL, [], SA_RESTORER, 0x34e7233140}, 8) = 0
getrlimit(RLIMIT_NPROC, {rlim_cur=1024, rlim_max=62265}) = 0
rt_sigprocmask(SIG_BLOCK, NULL, [], 8)  = 0
fcntl(0, F_GETFL)                       = 0 (flags O_RDONLY)
fstat(0, {st_mode=S_IFIFO|0600, st_size=0, ...}) = 0
lseek(0, 0, SEEK_CUR)                   = -1 ESPIPE (Illegal seek)
rt_sigprocmask(SIG_BLOCK, NULL, [], 8)  = 0
read(0, 

这是Bash提示符,它坐在那里,等待一些输入。所以我们给它命令cd ..

read(0, "c", 1)                         = 1
read(0, "d", 1)                         = 1
read(0, " ", 1)                         = 1
read(0, ".", 1)                         = 1
read(0, ".", 1)                         = 1
read(0, "\n", 1)                        = 1
stat("/home", {st_mode=S_IFDIR|0755, st_size=4096, ...}) = 0
stat("/home/saml", {st_mode=S_IFDIR|0700, st_size=32768, ...}) = 0
stat("/home/saml/tst", {st_mode=S_IFDIR|0775, st_size=4096, ...}) = 0
stat("/home/saml/tst/90609", {st_mode=S_IFDIR|0775, st_size=4096, ...}) = 0
stat("/home/saml/tst/90609", {st_mode=S_IFDIR|0775, st_size=4096, ...}) = 0
chdir("/home/saml/tst")                 = 0
rt_sigprocmask(SIG_BLOCK, NULL, [], 8)  = 0
read(0, 

从上面的输出中,您可以看到我在哪里键入命令,cd ..然后按Enter键(\n)。从那里可以看到该stat()函数已被调用,然后Bash坐在另一个read(0..提示符下,等待另一个命令。


7

straceshell做cd /some/dir

{ strace -p "$$" & sleep 1; cd /some/dir; kill "$!"; }

为什么$1在这里,对bash,如果不是这种%%1
Graeme 2014年

1

您可以尝试以下方法:

strace bash -c <command/builtin>

例如:

strace bash -c 'cd /path/to/destination/'
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.