Home > 工具介绍, 调优 > systemtap如何跟踪libc.so

systemtap如何跟踪libc.so

原创文章,转载请注明: 转载自Erlang非业余研究

本文链接地址: systemtap如何跟踪libc.so

下午和周忱同学折腾复杂程序的内存泄漏问题,用了valgrind, gogle perftools等工具都不大好用,很容易把应用程序搞死,于是打算用systemtap来在libc.so层面了解内存的使用情况。主要思路就是看malloc/realloc和free的调用次数的平衡。

首先准备下环境,系统是标准的RHEL 5u4:

$ uname -r
2.6.18-164.el5

$ stap -V
SystemTap translator/driver (version 1.3/0.137 non-git sources)
Copyright (C) 2005-2010 Red Hat, Inc. and others
This is free software; see the source for copying conditions.
enabled features: LIBRPM LIBSQLITE3 NSS BOOST_SHARED_PTR TR1_UNORDERED_MAP
$stap -L  'kernel.function("printk")'
kernel.function("printk@kernel/printk.c:533") $fmt:char const* $args:va_list

$ stap -L  'process("/lib64/libc.so.6").function("malloc")'
Missing separate debuginfos, use: debuginfo-install glibc-2.5-42.x86_64

内核的符号是OK的,glibc没有安装符号。系统提示用 debuginfo-install glibc-2.5-42.x86_64 命令安装符号信息,但是RHEL 5不交钱不能用这个服务的,只能自己下载包安装。

$ wget -c ftp.redhat.com/pub/redhat/linux/enterprise/5Server/en/os/x86_64/Debuginfo/glibc-debuginfo-2.5-42.x86_64.rpm
$ sudo rpm -i  glibc-debuginfo-2.5-42.x86_64.rpm
$ stap -L  'process("/lib64/libc.so.6").function("malloc")'
process("/lib64/libc-2.5.so").function("__libc_malloc@/usr/src/debug/glibc-2.5-20061008T1257/malloc/malloc.c:3560") $bytes:size_t

这次有了glibc的符号了,可以方便的跟踪libc.so中malloc的使用情况。
接着我们来简单的写个c程序调用malloc, 同时写个stap脚本来跟踪malloc的调用堆栈:

$ cat t.c
#include <stdlib.h>

void fun() {
  malloc(1000);
}

int main(int argc, char *argv[]) {
  fun();
  return 0;
}

$cat m.stp
probe process("/lib64/libc.so.6").function("malloc") {
if (target()== pid()) {
print_ubacktrace();
exit();
}
}
probe begin {
println("~");
}

$ gcc  -g t.c

$ stap -L 'process("./a.out").function("*")'
process("/home/chuba/a.out").function("fun@/home/chuba/t.c:3")
process("/home/chuba/a.out").function("main@/home/chuba/t.c:7") $argc:int $argv:char**

现在程序准备好了,那么我们来执行下看内存泄漏在那里:

$sudo stap m.stp -c ./a.out
~
 0x33d5e74b96 : malloc+0x16/0x230 [libc-2.5.so]
 0x4004a6 [a.out+0x4a6/0x1000]

我们看到在a.out的0x4004a6的地方地方调用了malloc, 但是具体在程序里面是哪行呢? 用add2line就很容易找出来:

$ addr2line -e ./a.out 0x4004a6
/home/chuba/t.c:5
$ nl t.c
     1  #include <stdlib.h>

     2  void fun() {
     3    malloc(1000);
     4  }

     5  int main(int argc, char *argv[]) {
     6    fun();
     7    return 0;
     8  }

哈哈,
祝大家玩得开心。

Post Footer automatically generated by wp-posturl plugin for wordpress.

Related posts:

  1. Erlang open_port极度影响性能的因素
  2. Systemtap辅助设置tcp_init_cwnd,免对操作系统打Patch
  3. disktop per设备per应用层面的IO读写统计
  4. gcc mudflap 用来检测内存越界的问题
  5. Linux文件预读分析以及评估对系统的影响
Categories: 工具介绍, 调优 Tags: ,
  1. January 12th, 2012 at 16:49 | #1

    霸爷V5!

    [Reply]

  2. chaoslawful
    January 15th, 2012 at 14:29 | #2

    systemtap 做这个有点儿杀鸡用牛刀吧,用 ltrace -i 就能达到这个效果了

    [Reply]

  1. No trackbacks yet.