1# Copyright (C) 2013 Google Inc. All rights reserved.
2#
3# Redistribution and use in source and binary forms, with or without
4# modification, are permitted provided that the following conditions are
5# met:
6#
7#     * Redistributions of source code must retain the above copyright
8# notice, this list of conditions and the following disclaimer.
9#     * Redistributions in binary form must reproduce the above
10# copyright notice, this list of conditions and the following disclaimer
11# in the documentation and/or other materials provided with the
12# distribution.
13#     * Neither the name of Google Inc. nor the names of its
14# contributors may be used to endorse or promote products derived from
15# this software without specific prior written permission.
16#
17# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
29import cgi
30import logging
31
32from webkitpy.common.webkit_finder import WebKitFinder
33from webkitpy.layout_tests.breakpad.dump_reader import DumpReader
34
35
36_log = logging.getLogger(__name__)
37
38
39class DumpReaderMultipart(DumpReader):
40    """Base class for Linux and Android breakpad dump reader."""
41
42    def __init__(self, host, build_dir):
43        super(DumpReaderMultipart, self).__init__(host, build_dir)
44        self._webkit_finder = WebKitFinder(host.filesystem)
45        self._breakpad_tools_available = None
46
47    def check_is_functional(self):
48        return self._check_breakpad_tools_available()
49
50    def _get_pid_from_dump(self, dump_file):
51        dump = self._read_dump(dump_file)
52        if not dump:
53            return None
54        if 'pid' in dump:
55            return dump['pid'][0]
56        return None
57
58    def _get_stack_from_dump(self, dump_file):
59        dump = self._read_dump(dump_file)
60        if not dump:
61            return None
62        if not 'upload_file_minidump' in dump:
63            return None
64
65        self._generate_breakpad_symbols_if_necessary()
66        f, temp_name = self._host.filesystem.open_binary_tempfile('dmp')
67        f.write("\r\n".join(dump['upload_file_minidump']))
68        f.close()
69
70        cmd = [self._path_to_minidump_stackwalk(), temp_name, self._symbols_dir()]
71        try:
72            stack = self._host.executive.run_command(cmd, return_stderr=False)
73        except:
74            _log.warning('Failed to execute "%s"' % ' '.join(cmd))
75            stack = None
76        finally:
77            self._host.filesystem.remove(temp_name)
78        return stack
79
80    def _read_dump(self, dump_file):
81        with self._host.filesystem.open_binary_file_for_reading(dump_file) as f:
82            boundary = f.readline().strip()[2:]
83            f.seek(0)
84            data = cgi.parse_multipart(f, {'boundary': boundary})
85            return data
86        return None
87
88    def _check_breakpad_tools_available(self):
89        if self._breakpad_tools_available != None:
90            return self._breakpad_tools_available
91
92        REQUIRED_BREAKPAD_TOOLS = [
93            'dump_syms',
94            'minidump_stackwalk',
95        ]
96        result = True
97        for binary in REQUIRED_BREAKPAD_TOOLS:
98            full_path = self._host.filesystem.join(self._build_dir, binary)
99            if not self._host.filesystem.exists(full_path):
100                result = False
101                _log.error('Unable to find %s' % binary)
102                _log.error('    at %s' % full_path)
103
104        if not result:
105            _log.error("    Could not find breakpad tools, unexpected crashes won't be symbolized")
106            _log.error('    Did you build the target blink_tests?')
107            _log.error('')
108
109        self._breakpad_tools_available = result
110        return self._breakpad_tools_available
111
112    def _path_to_minidump_stackwalk(self):
113        return self._host.filesystem.join(self._build_dir, "minidump_stackwalk")
114
115    def _path_to_generate_breakpad_symbols(self):
116        return self._webkit_finder.path_from_chromium_base("components", "breakpad", "tools", "generate_breakpad_symbols.py")
117
118    def _symbols_dir(self):
119        return self._host.filesystem.join(self._build_dir, 'content_shell.syms')
120
121    def _generate_breakpad_symbols_if_necessary(self):
122        if self._host.filesystem.exists(self._symbols_dir()):
123            needs_update = False
124            symbols_mtime = self._host.filesystem.mtime(self._symbols_dir())
125            for binary in self._binaries_to_symbolize():
126                full_path = self._host.filesystem.join(self._build_dir, binary)
127                if self._host.filesystem.mtime(full_path) >= symbols_mtime:
128                    needs_update = True
129            if not needs_update:
130                return
131
132        _log.debug("Regenerating breakpad symbols")
133        self._host.filesystem.rmtree(self._symbols_dir())
134
135        for binary in self._binaries_to_symbolize():
136            full_path = self._host.filesystem.join(self._build_dir, binary)
137            cmd = [
138                self._path_to_generate_breakpad_symbols(),
139                '--binary=%s' % full_path,
140                '--symbols-dir=%s' % self._symbols_dir(),
141                '--build-dir=%s' % self._build_dir,
142            ]
143            try:
144                self._host.executive.run_command(cmd)
145            except:
146                _log.error('Failed to execute "%s"' % ' '.join(cmd))
147
148    def _binaries_to_symbolize(self):
149        """This routine must be implemented by subclasses.
150
151        Returns an array of binaries that need to be symbolized."""
152        raise NotImplementedError()
153
154
155class DumpReaderLinux(DumpReaderMultipart):
156    """Linux breakpad dump reader."""
157
158    def _binaries_to_symbolize(self):
159        return ['content_shell', 'libTestNetscapePlugIn.so', 'libffmpegsumo.so', 'libosmesa.so']
160
161    def _file_extension(self):
162        return 'dmp'
163
164
165class DumpReaderAndroid(DumpReaderMultipart):
166    """Android breakpad dump reader."""
167
168    def _binaries_to_symbolize(self):
169        return ['lib/libcontent_shell_content_view.so']
170
171    def _file_extension(self):
172        return 'dmp'
173