1. 程式人生 > >systemtap如何寫C函數 捎帶著看看ret kprobe怎麽用

systemtap如何寫C函數 捎帶著看看ret kprobe怎麽用

tasks blank valid clas ktr pri may sin hat

systemstap中自定義函數

Embedded C can be the body of a script function. Instead enclosing the function body statements in { and
}, use %{ and %}. Any enclosed C code is literally transcribed into the kernel module: it is up to you to make
it safe and correct. In order to take parameters and return a value, macros STAP_ARG_*

and STAP_RETVALUE
are made available. The familiar data-gathering functions pid(), execname(), and their neighbours are all
embedded C functions. Figure 10 contains another example.


Since systemtap cannot examine the C code to infer these types, an optional annotation syntax is available
to assist the type inference process. Simply suffix parameter names and/or the function name with :string


or :long to designate the string or numeric type. In addition, the script may include a %{ %} block at the
outermost level of the script, in order to transcribe declarative code like #include <linux/foo.h>. These
enable the embedded C functions to refer to general kernel types.
There are a number of safety-related constraints that should be observed by developers of embedded C code.
1. Do not dereference pointers that are not known or testable valid.
2. Do not call any kernel routine that may cause a sleep or fault.
3. Consider possible undesirable recursion, where your embedded C function calls a routine that may be
the subject of a probe. If that probe handler calls your embedded C function, you may suffer infinite
regress. Similar problems may arise with respect to non-reentrant locks.
4. If locking of a data structure is necessary, use a trylock type call to attempt to take the lock. If that
fails, give up, do not block.

下面是tutorial中發出來的一個例子:

# cat embedded-C.stp
%{
#include <linux/sched.h>
#include <linux/list.h>
%}
function task_execname_by_pid:string (pid:long) %{
struct task_struct *p;
struct list_head *_p, *_n;
list_for_each_safe(_p, _n, &current->tasks) {
p = list_entry(_p, struct task_struct, tasks);
if (p->pid == (int)STAP_ARG_pid)
snprintf(STAP_RETVALUE, MAXSTRINGLEN, "%s", p->comm);
}
%}
probe begin;
{
printf("%s(%d)\n", task_execname_by_pid(target()), target())
exit()
}

https://sourceware.org/systemtap/tutorial.pdf

使用最新的systemtap去使用print_backtrace呀,並且最後一定要make install

---恢復內容開始---

systemtap  寫C函數的一個原理是system的翻譯器不翻譯這段代碼,直接把代碼給了C編譯器

systemtap如何寫C函數 捎帶著看看ret kprobe怎麽用