1.什么是tombstone

当一个动态库(native 程序)开始执行时,系统会注册一些连接到 debuggerd 的 signal handlers,当系统 crash 的时候,会保存一个 tombstone 文件到/data/tombstones目录下(Logcat中也会有相应的信息),文件的确就像墓碑一样记录了死亡了的进程的基本信息(例如进程的进程号,线程号),死亡的地址(在哪个地址上发生了 Crash),死亡时的现场是什么样的(记录了一系列的堆栈调用信息)等等。

2.tombstone文件长什么样

一个tombstone文件大概包含以下信息

  1. --------- beginning of crash
  2. F/libc ( ): invalid address or address of corrupt block 0xb82f54a0 passed to dlfree
  3. I/libc ( ): debuggerd_signal_handler called: signal=, fn=0xb6fbdaa1
  4. F/libc ( ): Fatal signal (SIGSEGV), code , fault addr 0xdeadbaad in tid (mediaserver)
  5. I/libc ( ): exit from debuggerd_signal_handler
  6. W/NativeCrashListener( ): Couldn't find ProcessRecord for pid 244
  7. I/DEBUG ( ): *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
  8. E/DEBUG ( ): AM write failure ( / Broken pipe)
  9. I/DEBUG ( ): Build fingerprint: XXXXXXXXX
  10. I/DEBUG ( ): Revision: ''
  11. I/DEBUG ( ): ABI: 'arm'
  12. I/DEBUG ( ): pid: , tid: , name: mediaserver >>> /system/bin/mediaserver <<<
  13. I/DEBUG ( ): signal (SIGSEGV), code (SEGV_MAPERR), fault addr 0xdeadbaad
  14. I/art ( ): now dumpable=
  15. I/DEBUG ( ): Abort message: 'invalid address or address of corrupt block 0xb82f54a0 passed to dlfree'
  16. I/DEBUG ( ): r0 r1 b6f20dec r2 deadbaad r3
  17. I/DEBUG ( ): r4 b82f54a0 r5 b6f220f8 r6 r7
  18. I/DEBUG ( ): r8 ffffffff r9 b82f5460 sl fp
  19. I/DEBUG ( ): ip sp beb2c020 lr b6ef1fa7 pc b6ef1fa8 cpsr 600e0030
  20. I/DEBUG ( ): d0 d1 6f2073736572646c
  21. I/DEBUG ( ): d2 707572726f632066 d3 206b636f6c622072
  22. I/DEBUG ( ): d4 d5
  23. I/DEBUG ( ): d6 d7 3ecccccd42424242
  24. I/DEBUG ( ): d8 d9
  25. I/DEBUG ( ): d10 d11
  26. I/DEBUG ( ): d12 d13
  27. I/DEBUG ( ): d14 d15
  28. I/DEBUG ( ): d16 d17 3ff0000000000000
  29. I/DEBUG ( ): d18 7e37e43c8800759c d19 bfd5f3f082400000
  30. I/DEBUG ( ): d20 3e66376972bea4d0 d21 bf66b12699b6468f
  31. I/DEBUG ( ): d22 3fc54aa75950670f d23 bfd73498f0a5ef3a
  32. I/DEBUG ( ): d24 3fe0000000000000 d25 bfaaf3ec933c988f
  33. I/DEBUG ( ): d26 d27
  34. I/DEBUG ( ): d28 4002e6931e14bde7 d29 3faaf3ec9198f99c
  35. I/DEBUG ( ): d30 3ff0000000000000 d31 3fd29572efd86cee
  36. I/DEBUG ( ): scr
  37. I/DEBUG ( ):
  38. I/DEBUG ( ): backtrace:
  39. I/DEBUG ( ): # pc 00028fa8 /system/lib/libc.so (dlfree+)
  40. I/DEBUG ( ): # pc 0000f2cb /system/lib/libc.so (free+)
  41. I/DEBUG ( ): # pc 0000a1cb /system/lib/libstagefright_foundation.so (_ZN7android7ABufferD2Ev+)
  42. I/DEBUG ( ): # pc 0000a211 /system/lib/libstagefright_foundation.so (_ZN7android7ABufferD0Ev+)
  43. I/DEBUG ( ): # pc 0000d68d /system/lib/libutils.so (_ZNK7android7RefBase9decStrongEPKv+)
  44. I/DEBUG ( ): # pc 0005adfd /system/lib/libstagefright.so (_ZN7android2spINS_13GraphicBufferEED2Ev+)
  45. I/DEBUG ( ): # pc 0007cd0f /system/lib/libstagefright.so (_ZN7android14MPEG4Extractor10parseChunkEPxi+)
  46. I/DEBUG ( ): # pc 0007d43d /system/lib/libstagefright.so (_ZN7android14MPEG4Extractor10parseChunkEPxi+)
  47. I/DEBUG ( ): # pc 0007e873 /system/lib/libstagefright.so (_ZN7android14MPEG4Extractor12readMetaDataEv+)
  48. I/DEBUG ( ): # pc 0007eaa1 /system/lib/libstagefright.so (_ZN7android14MPEG4Extractor11countTracksEv+)
  49. I/DEBUG ( ): # pc 000acf9d /system/lib/libstagefright.so (_ZN7android13ExtendedUtils29MediaExtractor_CreateIfNeededENS_2spINS_14MediaExtractorEEERKNS1_INS_10DataSourceEEEPKc+)
  50. I/DEBUG ( ): # pc 0008e3f5 /system/lib/libstagefright.so (_ZN7android14MediaExtractor6CreateERKNS_2spINS_10DataSourceEEEPKc+)
  51. I/DEBUG ( ): # pc 0006ace9 /system/lib/libstagefright.so (_ZN7android13AwesomePlayer15setDataSource_lERKNS_2spINS_10DataSourceEEE+)
  52. I/DEBUG ( ): # pc 0006c0dd /system/lib/libstagefright.so (_ZN7android13AwesomePlayer13setDataSourceEixx+)
  53. I/DEBUG ( ): # pc 0003d647 /system/lib/libmediaplayerservice.so (_ZN7android18MediaPlayerService6Client13setDataSourceEixx+)
  54. I/DEBUG ( ): # pc 0005ea03 /system/lib/libmedia.so (_ZN7android13BnMediaPlayer10onTransactEjRKNS_6ParcelEPS1_j+)
  55. I/DEBUG ( ): # pc 00017fad /system/lib/libbinder.so (_ZN7android7BBinder8transactEjRKNS_6ParcelEPS1_j+)
  56. I/DEBUG ( ): # pc 0001cfdb /system/lib/libbinder.so (_ZN7android14IPCThreadState14executeCommandEi+)
  57. I/DEBUG ( ): # pc 0001d12f /system/lib/libbinder.so (_ZN7android14IPCThreadState20getAndExecuteCommandEv+)
  58. I/DEBUG ( ): # pc 0001d171 /system/lib/libbinder.so (_ZN7android14IPCThreadState14joinThreadPoolEb+)
  59. I/DEBUG ( ): # pc /system/bin/mediaserver
  60. I/DEBUG ( ): # pc 0000f411 /system/lib/libc.so (__libc_init+)
  61. I/DEBUG ( ): # pc /system/bin/mediaserver
  62. I/DEBUG ( ):
  63. I/DEBUG ( ): stack:
  64. I/DEBUG ( ): beb2bfe0
  65. I/DEBUG ( ): beb2bfe4 29ec038f
  66. I/DEBUG ( ): beb2bfe8 0009eb34
  67. I/DEBUG ( ): beb2bfec b82f54a0 [heap]
  68. I/DEBUG ( ): beb2bff0 b6f220f8
  69. I/DEBUG ( ): beb2bff4
  70. I/DEBUG ( ): beb2bff8
  71. I/DEBUG ( ): beb2bffc b6edb3d1 /system/lib/libc.so (__libc_fatal_no_abort+)
  72. I/DEBUG ( ): beb2c000 b6f12f97 /system/lib/libc.so
  73. I/DEBUG ( ): beb2c004 beb2c014 [stack]
  74. I/DEBUG ( ): beb2c008 b6f167be /system/lib/libc.so
  75. I/DEBUG ( ): beb2c00c b6ef1fa7 /system/lib/libc.so (dlfree+)
  76. I/DEBUG ( ): beb2c010 b6f12f97 /system/lib/libc.so
  77. I/DEBUG ( ): beb2c014 b82f54a0 [heap]
  78. I/DEBUG ( ): beb2c018 b6f167be /system/lib/libc.so
  79. I/DEBUG ( ): beb2c01c b82f54b0 [heap]
  80. I/DEBUG ( ): # beb2c020 b82f5460 [heap]
  81. ......

它包含了发生问题的进程ID信息

  1. I/DEBUG ( ): pid: , tid: , name: mediaserver >>> /system/bin/mediaserver <<<

当 tid == pid 时,问题发生在父进程,反之问题发生在子进程,从上面的日志信息可以看出发生问题的进程是mediaserver的子进程。

Terminated signal 和 fault address 信息

  1. F/libc ( ): Fatal signal (SIGSEGV), code , fault addr 0xdeadbaad in tid (mediaserver)

这里的信息说明出现进程 Crash 的原因是因为程序产生了段错误的信号,访问了非法的内存空间,而访问的非法地址是 0xdeadbaad。

信号机制是 Linux 进程间通信的一种重要方式,Linux 信号一方面用于正常的进程间通信和同步,如任务控制(SIGINT, SIGTSTP,SIGKILL, SIGCONT,……);另一方面,它还负责监控系统异常及中断。 当应用程序运行异常时, Linux 内核将产生错误信号并通知当前进程。 当前进程在接收到该错误信号后,可以有三种不同的处理方式。

(1)忽略该信号。

(2)捕捉该信号并执行对应的信号处理函数(signal handler)。

(3)执行该信号的缺省操作(如 SIGSEGV, 其缺省操作是终止进程)。

当 Linux 应用程序在执行时发生严重错误,一般会导致程序 crash。其中,Linux 专门提供了一类 crash 信号,在程序接收到此类信号时,缺省操作是将 crash 的现场信息记录到 core 文件,然后终止进程。

crash 信号列表:

Signal Description
SIGSEGV Invalid memory reference.
SIGBUS Access to an undefined portion of a memory object.
SIGFPE Arithmetic operation error, like divide by zero.
SIGILL Illegal instruction, like execute garbage or a privileged instruction
SIGSYS Bad system call.
SIGXCPU CPU time limit exceeded.
SIGXFSZ File size limit exceeded.

定义在prebuilts/gcc/linux-x86/host/x86_64-linux-glibc2.11-4.8/sysroot/usr/include/bits/signum.h

  1. /* Signals. */
  2. #define SIGHUP 1 /* Hangup (POSIX). */
  3. #define SIGINT 2 /* Interrupt (ANSI). */
  4. #define SIGQUIT 3 /* Quit (POSIX). */
  5. #define SIGILL 4 /* Illegal instruction (ANSI). */
  6. #define SIGTRAP 5 /* Trace trap (POSIX). */
  7. #define SIGABRT 6 /* Abort (ANSI). */
  8. #define SIGIOT 6 /* IOT trap (4.2 BSD). */
  9. #define SIGBUS 7 /* BUS error (4.2 BSD). */
  10. #define SIGFPE 8 /* Floating-point exception (ANSI). */
  11. #define SIGKILL 9 /* Kill, unblockable (POSIX). */
  12. #define SIGUSR1 10 /* User-defined signal 1 (POSIX). */
  13. #define SIGSEGV 11 /* Segmentation violation (ANSI). */
  14. #define SIGUSR2 12 /* User-defined signal 2 (POSIX). */
  15. #define SIGPIPE 13 /* Broken pipe (POSIX). */
  16. #define SIGALRM 14 /* Alarm clock (POSIX). */
  17. #define SIGTERM 15 /* Termination (ANSI). */
  18. #define SIGSTKFLT 16 /* Stack fault. */
  19. #define SIGCLD SIGCHLD /* Same as SIGCHLD (System V). */
  20. #define SIGCHLD 17 /* Child status has changed (POSIX). */
  21. #define SIGCONT 18 /* Continue (POSIX). */
  22. #define SIGSTOP 19 /* Stop, unblockable (POSIX). */
  23. #define SIGTSTP 20 /* Keyboard stop (POSIX). */
  24. #define SIGTTIN 21 /* Background read from tty (POSIX). */
  25. #define SIGTTOU 22 /* Background write to tty (POSIX). */
  26. #define SIGURG 23 /* Urgent condition on socket (4.2 BSD). */
  27. #define SIGXCPU 24 /* CPU limit exceeded (4.2 BSD). */
  28. #define SIGXFSZ 25 /* File size limit exceeded (4.2 BSD). */
  29. #define SIGVTALRM 26 /* Virtual alarm clock (4.2 BSD). */
  30. #define SIGPROF 27 /* Profiling alarm clock (4.2 BSD). */
  31. #define SIGWINCH 28 /* Window size change (4.3 BSD, Sun). */
  32. #define SIGPOLL SIGIO /* Pollable event occurred (System V). */
  33. #define SIGIO 29 /* I/O now possible (4.2 BSD). */
  34. #define SIGPWR 30 /* Power failure restart (System V). */
  35. #define SIGSYS 31 /* Bad system call. */
  36. #define SIGUNUSED 31
  37.  
  38. #define _NSIG 65 /* Biggest signal number + 1
  39. (including real-time signals). */

3.怎么分析tombstone文件

我们主要关注 backtrace 下面的内容,它保存了发生 crash 时候的函数调用关系,但是需要注意的是它的调用顺序是从下向上执行的(#XX pc -->#00 pc),通过这些函数调用关系,我们就可以大概定位出问题发生的地方,在本次 tombstone 日志中,我们通过

  1. I/DEBUG ( ): # pc 00028fa8 /system/lib/libc.so (dlfree+)
  2. I/DEBUG ( ): # pc 0000f2cb /system/lib/libc.so (free+)
  3. I/DEBUG ( ): # pc 0000a1cb /system/lib/libstagefright_foundation.so (_ZN7android7ABufferD2Ev+)
  4. I/DEBUG ( ): # pc 0000a211 /system/lib/libstagefright_foundation.so (_ZN7android7ABufferD0Ev+)
  5. I/DEBUG ( ): # pc 0000d68d /system/lib/libutils.so (_ZNK7android7RefBase9decStrongEPKv+)

可以分析出问题是在调用free函数时发生了指针错误,还可以看出问题发生的原因是libstagefright_foundation.so中释放了两次ABuffer引用,接着就去分析是谁谁释放的AUbffer强指针。

  1. I/DEBUG ( ): # pc 0005adfd /system/lib/libstagefright.so (_ZN7android2spINS_13GraphicBufferEED2Ev+)
  2. I/DEBUG ( ): # pc 0007cd0f /system/lib/libstagefright.so (_ZN7android14MPEG4Extractor10parseChunkEPxi+)
  3. I/DEBUG ( ): # pc 0007d43d /system/lib/libstagefright.so (_ZN7android14MPEG4Extractor10parseChunkEPxi+)
  4. I/DEBUG ( ): # pc 0007e873 /system/lib/libstagefright.so (_ZN7android14MPEG4Extractor12readMetaDataEv+)

可以看出来在 libstagefright 动态库中的MPEG4Extractor.cpp 的 parseChunk函数出现的错误。

4.一些分析工具

虽然通过 tombstone 的日志文件我们就可以大致定位出引发 crash 的代码的位置,但是通过借助一些分析工具,可以大大的提高工作效率和准确性,下面就来介绍以下这些工具。

(1)addr2line

addr2line 是 用来获得指定动态链接库文件或者可执行文件中指定地址对应的源代码信息的工具

它的各种参数如下所示(这个是google aosp android M 中带的):

  1. ~/source/google_android/prebuilts/gcc/linux-x86/x86/x86_64-linux-android-4.9/bin$ ./x86_64-linux-android-addr2line -h
  2. Usage: ./x86_64-linux-android-addr2line [option(s)] [addr(s)]
  3. Convert addresses into line number/file name pairs.
  4. If no addresses are specified on the command line, they will be read from stdin
  5. The options are:
  6. @<file> Read options from <file>
  7. -a --addresses Show addresses
  8. -b --target=<bfdname> Set the binary file format
  9. -e --exe=<executable> Set the input file name (default is a.out)
  10. -i --inlines Unwind inlined functions
  11. -j --section=<name> Read section-relative offsets instead of addresses
  12. -p --pretty-print Make the output easier to read for humans
  13. -s --basenames Strip directory names
  14. -f --functions Show function names
  15. -C --demangle[=style] Demangle function names
  16. -h --help Display this information
  17. -v --version Display the program's version
  18. ./x86_64-linux-android-addr2line: supported targets: elf64-x86- elf32-i386 elf32-x86- a.out-i386-linux pei-i386 pei-x86- elf64-l1om elf64-k1om elf64-little elf64-big elf32-little elf32-big plugin srec symbolsrec verilog tekhex binary ihex
  19. Report bugs to <http://source.android.com/source/report-bugs.html>

addr2line 的基本用法如下所示:

  1. ./prebuilts/gcc/linux-x86/arm/arm-linux-androideabi-4.8/bin/arm-linux-androideabi-addr2line -f -e out/debug/target/product/XXXX/symbols/system/lib/libstagefright.so 0007cd0f
  2. _ZN7android14MPEG4Extractor10parseChunkEPxi
  3. /home/XXX/source/XXX/LINUX/android/frameworks/av/media/libstagefright/MPEG4Extractor.cpp: (discriminator )

这里需要注意的是不能直接使用out/debug/target/product/XXX/system/lib/libstagefright.so,会出现运行上面命令之后显示

  1. ??
  2. ??:

因为这个动态库是最后要打包到最后生成的system.ing中的,所以它不包含调试符号信息。

(2)ndk-stack

Android NDK 自从版本 r6开始, 提供了一个工具 ndk-stack。这个工具能自动分析 tombstone 文件, 能将崩溃时的调用内存地址和 c++ 代码一行一行对应起来.

它的使用方法为

  1. ./ndk-stack
  2. Usage:
  3. ndk-stack -sym <path> [-dump <path>]
  4. -sym Contains full path to the root directory for symbols.
  5. -dump Contains full path to the file containing the crash dump.
  6. This is an optional parameter. If ommited, ndk-stack will
  7. read input data from stdin
  8. See docs/NDK-STACK.html in your NDK installation tree for more details.

①dump 参数很容易理解, 即 dump 下来的 log 文本文件. ndk-stack会分析此文件。

②sym 参数就是你android项目下,编译成功之后,obj目录下的文件(android系统源码o 中带有符号信息的文件)。

我们可以使用它来分析我们的log文件

  1. ndk-stack -sym xxx.so -dump logfile

所以我们在调试android系统源码的时候也可以直接分析log中的crash信息。

  1. adb shell logcat | ndk-stack -sym out/debug/target/product/XXXX/symbols/system/lib/xxx.so

(3)stack.py

stack.py工具就是要把backtrace通过addr2line工具一次性把addr对应到代码

  1. #!/usr/bin/python2.4 -E
  2. import getopt
  3. import os
  4. import re
  5. import string
  6. import sys
  7. import getpass
  8. import urllib
  9. import subprocess
  10. def PrintUsage():
  11. print
  12. print " usage: " + sys.argv[0] + " [options] [FILE]"
  13. print
  14. print " --symbols-dir=path"
  15. print " the path to a symbols dir, such as =/tmp/out/target/product/dream/symbols"
  16. print
  17. print " --symbols-zip=path"
  18. print " the path to a symbols zip file, such as =dream-symbols-12345.zip"
  19. print
  20. print " --auto"
  21. print " attempt to:"
  22. print " 1) automatically find the build number in the crash"
  23. print " 2) if it's an official build, download the symbols "
  24. print " from the build server, and use them"
  25. print
  26. print " FILE should contain a stack trace in it somewhere"
  27. print " the tool will find that and re-print it with"
  28. print " source files and line numbers. If you don't"
  29. print " pass FILE, or if file is -, it reads from"
  30. print " stdin."
  31. print
  32. sys.exit(1)
  33. def FindSymbolsDir():
  34. cmd = "CALLED_FROM_SETUP=true make -f build/core/envsetup.mk " \
  35. + "dumpvar-abs-TARGET_OUT_UNSTRIPPED"
  36. stream = os.popen(cmd)
  37. str = stream.read()
  38. stream.close()
  39. return str.strip()
  40. # returns a list containing the function name and the file/lineno
  41. def CallAddr2Line(lib, addr):
  42. uname = os.uname()[0]
  43. if uname == "Darwin":
  44. proc = os.uname()[-1]
  45. if proc == "i386":
  46. uname = "darwin-x86"
  47. else:
  48. uname = "darwin-ppc"
  49. if lib != "":
  50. #cmd = "./prebuilt/" + uname + "/toolchain-eabi-4.2.1/bin/arm-eabi-addr2line" \
  51. #cmd = "./prebuilts/gcc/linux-x86/arm/arm-linux-androideabi-4.7/bin/arm-linux-androideabi-addr2line" \
  52. cmd = " arm-eabi-addr2line" \
  53. + " -f -e " + SYMBOLS_DIR + lib \
  54. + " 0x" + addr
  55. stream = os.popen(cmd)
  56. lines = stream.readlines()
  57. list = map(string.strip, lines)
  58. else:
  59. list = []
  60. if list != []:
  61. # Name like "move_forward_type<JavaVMOption>" causes troubles
  62. mangled_name = re.sub('<', '\<', list[0]);
  63. mangled_name = re.sub('>', '\>', mangled_name);
  64. #cmd = "./prebuilt/" + uname + "/toolchain-eabi-4.2.1/bin/arm-eabi-c++filt "\
  65. cmd = "./prebuilts/gcc/linux-x86/arm/arm-linux-androideabi-4.7/bin/arm-linux-androideabi-c++filt "\
  66. + mangled_name
  67. stream = os.popen(cmd)
  68. list[0] = stream.readline()
  69. stream.close()
  70. list = map(string.strip, list)
  71. else:
  72. list = [ "(unknown)", "(unknown)" ]
  73. return list
  74. class SSOCookie(object):
  75. """
  76. creates a cookie file so we can download files from the build server
  77. """
  78. def __init__(self, cookiename=".sso.cookie", keep=False):
  79. self.sso_server = "login.corp.google.com"
  80. self.name = cookiename
  81. self.keeper = keep
  82. self.tmp_opts = ".curl.options"
  83. if not os.path.exists(self.name):
  84. user = os.environ['USER']
  85. print "\n%s, to access the symbols, please enter your LDAP " % user,
  86. password = getpass.getpass()
  87. params = urllib.urlencode({"u": user, "pw": password})
  88. fd = os.open(self.tmp_opts, os.O_RDWR | os.O_CREAT, 0600)
  89. os.write(fd, '-b "%s"\n' % self.name)
  90. os.write(fd, '-c "%s"\n' % self.name)
  91. os.write(fd, '-s"\n-L\n-d "%s"\n' % params)
  92. os.write(fd, 'url = "https://%s/login?ssoformat=CORP_SSO"\n' %
  93. self.sso_server)
  94. # login to SSO
  95. response = os.popen("/usr/bin/curl -K %s" % self.tmp_opts)
  96. response.close()
  97. if os.path.exists(self.tmp_opts):
  98. os.remove(self.tmp_opts)
  99. if os.path.exists(self.name):
  100. os.chmod(self.name, 0600)
  101. else:
  102. print "Could not log in to SSO"
  103. sys.exit(1)
  104. def __del__(self):
  105. """clean up"""
  106. if not self.keeper:
  107. os.remove(self.name)
  108. class NoBuildIDException(Exception):
  109. pass
  110. def FindBuildFingerprint(lines):
  111. """
  112. Searches the given file (array of lines) for the build fingerprint information
  113. """
  114. fingerprint_regex = re.compile("^.*Build fingerprint:\s'(?P<fingerprint>.*)'")
  115. for line in lines:
  116. fingerprint_search = fingerprint_regex.match(line.strip())
  117. if fingerprint_search:
  118. return fingerprint_search.group('fingerprint')
  119.  
  120. return None # didn't find the fingerprint string, so return none
  121.  
  122. class SymbolDownloadException(Exception):
  123. pass
  124. DEFAULT_SYMROOT = "/tmp/symbols"
  125. def DownloadSymbols(fingerprint, cookie):
  126. """
  127. Attempts to download the symbols from the build server, extracts them,
  128. and returns the path. Takes the fingerprint from the pasted stack trace
  129. and the SSOCookie
  130. """
  131. if fingerprint is None:
  132. return (None, None)
  133. symdir = "%s/%s" % (DEFAULT_SYMROOT, hash(fingerprint))
  134. if not os.path.exists(symdir):
  135. os.makedirs(symdir)
  136. # build server figures out the branch based on the CL
  137. params = {
  138. 'op': "GET-SYMBOLS-LINK",
  139. 'fingerprint': fingerprint,
  140. }
  141. url = urllib.urlopen("http://android-build/buildbot-update?",
  142. urllib.urlencode(params)).readlines()[0]
  143. if url == "":
  144. raise SymbolDownloadException, "Build server down? Failed to find syms..."
  145. regex_str = (r'(?P<baseURL>http\:\/\/android-build\/builds\/.*\/[0-9]+' +
  146. r'\/)(?P<img>.*)')
  147. url_regex = re.compile(regex_str)
  148. url_match = url_regex.match(url)
  149. if url_match is None:
  150. raise SymbolDownloadException, "Unexpected results from build server URL..."
  151.  
  152. baseURL = url_match.group('baseURL')
  153. img = url_match.group('img')
  154. symbolfile = img.replace("-img-", "-symbols-")
  155. symurl = baseURL + symbolfile
  156. localsyms = symdir + symbolfile
  157. if not os.path.exists(localsyms):
  158. print "downloading %s ..." % symurl
  159. curlcmd = ("""/usr/bin/curl -b %s -sL -w %%{http_code} -o %s %s""" %
  160. (cookie.name, localsyms, symurl))
  161. (fi,fo,fe) = os.popen3(curlcmd)
  162. fi.close()
  163. code = fo.read()
  164. err = fe.read()
  165. if err != "":
  166. raise SymbolDownloadException, "stderr from curl download: %s" % err
  167. if code != "":
  168. raise SymbolDownloadException, "Faied to download %s" % symurl
  169. else:
  170. print "using existing cache for symbols"
  171. print "extracting %s..." % symbolfile
  172. saveddir = os.getcwd()
  173. os.chdir(symdir)
  174. unzipcode = subprocess.call(["unzip", "-qq", "-o", localsyms])
  175. if unzipcode > 0:
  176. raise SymbolDownloadException, ("failed to extract symbol files (%s)."
  177. % localsyms)
  178. os.chdir(saveddir)
  179.  
  180. return (symdir, "%s/out/target/product/dream/symbols" % symdir)
  181. def UnzipSymbols(symbolfile):
  182. """Unzips a file to DEFAULT_SYMROOT and returns the unzipped location.
  183. Args:
  184. symbolfile: The .zip file to unzip
  185. Returns:
  186. A tuple containing (the directory into which the zip file was unzipped,
  187. the path to the "symbols" directory in the unzipped file). To clean
  188. up, the caller can delete the first element of the tuple.
  189. Raises:
  190. SymbolDownloadException: When the unzip fails.
  191. """
  192. symdir = "%s/%s" % (DEFAULT_SYMROOT, hash(symbolfile))
  193. if not os.path.exists(symdir):
  194. os.makedirs(symdir)
  195. print "extracting %s..." % symbolfile
  196. saveddir = os.getcwd()
  197. os.chdir(symdir)
  198. unzipcode = subprocess.call(["unzip", "-qq", "-o", symbolfile])
  199. if unzipcode > 0:
  200. raise SymbolDownloadException, ("failed to extract symbol files (%s)."
  201. % symbolfile)
  202. os.chdir(saveddir)
  203.  
  204. return (symdir, "%s/out/target/product/dream/symbols" % symdir)
  205. def PrintTraceLines(traceLines):
  206. maxlen = max(map(lambda tl: len(tl[1]), traceLines))
  207. print
  208. print "Stack Trace:"
  209. print " ADDR " + "FUNCTION".ljust(maxlen) + " FILE:LINE"
  210. for tl in traceLines:
  211. print " " + tl[0] + " " + tl[1].ljust(maxlen) + " " + tl[2]
  212. return
  213. def PrintValueLines(valueLines):
  214. print
  215. print "Stack Data:"
  216. print " ADDR VALUE " + "FILE:LINE/FUNCTION"
  217. for vl in valueLines:
  218. print " " + vl[1] + " " + vl[2] + " " + vl[4]
  219. if vl[4] != "":
  220. print " " + vl[3]
  221. return
  222. def ConvertTrace(lines):
  223. PROCESS_INFO_LINE = re.compile("(pid: [0-9]+, tid: [0-9]+.*)")
  224. SIGNAL_LINE = re.compile("(signal [0-9]+ \(.*\).*)")
  225. REGISTER_LINE = re.compile("(([ ]*[0-9a-z]{2} [0-9a-f]{8}){4})")
  226. TRACE_LINE = re.compile("(.*)\#([0-9]+) (..) ([0-9a-f]{3})([0-9a-f]{5}) ([^\r\n \t]*)")
  227. VALUE_LINE = re.compile("(.*)([0-9a-f]{2})([0-9a-f]{6}) ([0-9a-f]{3})([0-9a-f]{5}) ([^\r\n \t]*)")
  228. THREAD_LINE = re.compile("(.*)(\-\-\- ){15}\-\-\-")
  229. traceLines = []
  230. valueLines = []
  231. for line in lines:
  232. header = PROCESS_INFO_LINE.search(line)
  233. if header:
  234. print header.group(1)
  235. continue
  236. header = SIGNAL_LINE.search(line)
  237. if header:
  238. print header.group(1)
  239. continue
  240. header = REGISTER_LINE.search(line)
  241. if header:
  242. print header.group(1)
  243. continue
  244. if TRACE_LINE.match(line):
  245. match = TRACE_LINE.match(line)
  246. groups = match.groups()
  247. if groups[5] == "<unknown>" or groups[5] == "[heap]" or groups[5] == "[stack]":
  248. traceLines.append((groups[3]+groups[4], groups[5], groups[5]))
  249. else:
  250. info = CallAddr2Line(groups[5], groups[4])
  251. traceLines.append((groups[3]+groups[4], info[0], info[1]))
  252. if VALUE_LINE.match(line):
  253. match = VALUE_LINE.match(line)
  254. groups = match.groups()
  255. if groups[5] == "<unknown>" or groups[5] == "[heap]" or groups[5] == "[stack]" or groups[5] == "":
  256. valueLines.append((groups[0], groups[1]+groups[2], groups[3]+groups[4], groups[5], ""))
  257. else:
  258. info = CallAddr2Line(groups[5], groups[4])
  259. valueLines.append((groups[0], groups[1]+groups[2], groups[3]+groups[4], info[0], info[1]))
  260. header = THREAD_LINE.search(line)
  261. if header:
  262. if len(traceLines) > 0:
  263. PrintTraceLines(traceLines)
  264. if len(valueLines) > 0:
  265. PrintValueLines(valueLines)
  266. traceLines = []
  267. valueLines = []
  268. print
  269. print "-----------------------------------------------------\n"
  270. if len(traceLines) > 0:
  271. PrintTraceLines(traceLines)
  272. if len(valueLines) > 0:
  273. PrintValueLines(valueLines)
  274. SYMBOLS_DIR = FindSymbolsDir()
  275. if __name__ == '__main__':
  276. try:
  277. options, arguments = getopt.getopt(sys.argv[1:], "",
  278. ["auto", "symbols-dir=", "symbols-zip=", "help"])
  279. except getopt.GetoptError, error:
  280. PrintUsage()
  281.  
  282. AUTO = False
  283. zipArg = None
  284. for option, value in options:
  285. if option == "--help":
  286. PrintUsage()
  287. elif option == "--symbols-dir":
  288. SYMBOLS_DIR = value
  289. elif option == "--symbols-zip":
  290. zipArg = value
  291. elif option == "--auto":
  292. AUTO = True
  293.  
  294. if len(arguments) > 1:
  295. PrintUsage()
  296. if AUTO:
  297. cookie = SSOCookie(".symbols.cookie")
  298.  
  299. if len(arguments) == 0 or arguments[0] == "-":
  300. print "Reading native crash info from stdin"
  301. f = sys.stdin
  302. else:
  303. print "Searching for native crashes in %s" % arguments[0]
  304. f = open(arguments[0], "r")
  305. lines = f.readlines()
  306. rootdir = None
  307. if AUTO:
  308. fingerprint = FindBuildFingerprint(lines)
  309. print "fingerprint:", fingerprint
  310. rootdir, SYMBOLS_DIR = DownloadSymbols(fingerprint, cookie)
  311. elif zipArg is not None:
  312. rootdir, SYMBOLS_DIR = UnzipSymbols(zipArg)
  313.  
  314. print "Reading symbols from", SYMBOLS_DIR
  315. lines = ConvertTrace(lines)
  316.  
  317. if rootdir is not None:
  318. # be a good citizen and clean up...os.rmdir and os.removedirs() don't work
  319. cmd = "rm -rf \"%s\"" % rootdir
  320. print "\ncleaning up (%s)" % cmd
  321. os.system(cmd)
  322.  
  323. # vi: ts=2 sw=2

使用方法:

  1. python stack.py --symbols-dir=out/target/profuct/XXX/sysbols/ tombstone-00(tombstone文件)

Android Tombstone 分析的更多相关文章

  1. Android多线程分析之五:使用AsyncTask异步下载图像

    Android多线程分析之五:使用AsyncTask异步下载图像 罗朝辉 (http://www.cnblogs.com/kesalin) CC 许可,转载请注明出处 在本系列文章的第一篇<An ...

  2. Android多线程分析之四:MessageQueue的实现

    Android多线程分析之四:MessageQueue的实现 罗朝辉 (http://www.cnblogs.com/kesalin/) CC 许可,转载请注明出处 在前面两篇文章<Androi ...

  3. Android多线程分析之三:Handler,Looper的实现

    Android多线程分析之三:Handler,Looper的实现 罗朝辉 (http://www.cnblogs.com/kesalin/) CC 许可,转载请注明出处 在前文<Android多 ...

  4. Android多线程分析之二:Thread的实现

    Android多线程分析之二:Thread的实现 罗朝辉 (http://www.cnblogs.com/kesalin/) CC 许可,转载请注明出处   在前文<Android多线程分析之一 ...

  5. Android多线程分析之一:使用Thread异步下载图像

    Android多线程分析之一:使用Thread异步下载图像 罗朝辉 (http://www.cnblogs.com/kesalin) CC 许可,转载请注明出处   打算整理一下对 Android F ...

  6. Android Launcher分析和修改13——实现Launcher编辑模式(1) 壁纸更换

    已经很久没更新Launcher系列文章,今天不分析源码,讲讲如何在Launcher里面添加桌面设置的功能.目前很多第三方Launcher或者定制Rom都有简单易用的桌面设置功能.例如小米MIUI的La ...

  7. Android Launcher分析和修改9——Launcher启动APP流程

    本来想分析AppsCustomizePagedView类,不过今天突然接到一个临时任务.客户反馈说机器界面的图标很难点击启动程序,经常点击了没有反应,Boss说要优先解决这问题.没办法,只能看看是怎么 ...

  8. 正确使用Android性能分析工具——TraceView

    http://blog.jobbole.com/78995/     首页 最新文章 IT 职场 前端 后端 移动端 数据库 运维 其他技术 - 导航条 - 首页 最新文章 IT 职场 前端 - Ja ...

  9. Android架构分析之Android消息处理机制(二)

    作者:刘昊昱 博客:http://blog.csdn.net/liuhaoyutz Android版本号:4.4.2 在上一篇文章中我们看了一个使用Handler处理Message消息的样例,本文我们 ...

随机推荐

  1. (转)OpenStack Kilo 版本中 Neutron 的新变化

    OpenStack Kilo 版本,OpenStack 这个开源项目的第11个版本,已经于2015年4月正式发布了.现在是个合适的时间来看看这个版本中Neutron到底发生了哪些变化了,以及引入了哪些 ...

  2. nova instance启动中的同步与异步

    instance create:nova/api/servers.create -- self.compute_api.create -- self.compute_task_api.build_in ...

  3. 我的博客搬家到https://www.w2le.com/了

    大家以后想看我的博文的请到这里哦,欢迎大家访问https://www.w2le.com/

  4. 在CentOS6.4中安装配置LAMP环境的详细步骤 - Leroy-LIZH

    本文详细介绍了CentOS6.4系统中安装LAMP服务并对其进行配置的过程,即安装Apache+PHP+Mysql,参照了网上大神的设置,其他Linux发行系统可以参考~ 在本文中部分命令操作需要ro ...

  5. mysql数据库优化课程---1、数据库的本质是什么

    mysql数据库优化课程---1.数据库的本质是什么 一.总结 一句话总结: 文件夹-文件:一个数据库其实就是一个的文件夹,数据库里面的表就是文件夹里的一个或者多个文件(根据数据库引擎不同而不同,My ...

  6. java:正则匹配Pattern,Matcher

    一.正则匹配Pattern,Mather String s = "aa424fsfsd92lfjw2755097"; Pattern p = Pattern.compile(&qu ...

  7. .net core web发布到CentOS汇总

    直到今天我的博客终于可以见世人了,中间懒了很长一段时间,什么也没干,也没怎么学习,前段时间也是各种折腾,无心学习.本篇主要汇总下从一开始到现在遇到的问题汇总,作为学习笔记.我的博客就是我的学习笔记,因 ...

  8. shell脚本:利用7z备份git项目

    注:无git的方法参见:tar 或 7z 备份项目 首先利用homebrew安装p7zip $ brew install p7zip 然后利用两个shell脚本: backupProject.sh 会 ...

  9. cmd命令之查看进程到杀掉进程

    1. cmd命令查看当前进程 netstat -ano | findstr “port”

  10. 应该是实例化对象的没有对属性赋值时,自动赋值为null,但不是空指针对象引用

    此时会输出两个null. Users类的实例是myUsers,但是由于javabean的作用范围是page,所以前面页面传送的javabean的设置的属性全部不能接收到.所以对象myUsers属性为自 ...