aboutsummaryrefslogtreecommitdiffstats
path: root/src/libs/qt-breakpad/qtbreakpadsymbols
blob: 3b7c5af8ffc09e273042d4269150deebc1236997 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
#!/usr/bin/python

import sys
import os
import os.path
import subprocess
import shlex
import shutil
import base64

from poster.encode import multipart_encode
from poster.encode import MultipartParam
from poster.streaminghttp import register_openers
import urllib2

from optparse import OptionParser

register_openers()

breakpadSourceDir = os.environ['BREAKPAD_SOURCE_DIR']
breakpadUploadUrl = os.environ['BREAKPAD_UPLOAD_URL']
breakpadUserName = os.environ['BREAKPAD_USER_NAME']
breakpadUserPassword = os.environ['BREAKPAD_USER_PASSWORD']

if sys.platform == 'win32':
    nullfilename = 'nul:'
else:
    nullfilename = '/dev/null'
nullfile = open(nullfilename, 'r+b')


def stdoutFromProcess(process):
    (stdout, stderr) = process.communicate()
    if stderr:
        print stderr
        raise SystemError()
        sys.exit(1)
    return stdout

def toolPath():
    if sys.platform == 'linux2':
        dumpsymsPath = os.path.join(breakpadSourceDir, 'src/tools/linux/dump_syms/dump_syms')
    elif sys.platform == 'darwin':
        dumpsymsPath = os.path.join(breakpadSourceDir, 'src/tools/mac/dump_syms/build/Release/dump_syms')
    elif sys.platform == 'win32':
        dumpsymsPath = os.path.join(breakpadSourceDir,'src\\tools\\windows\\binaries\\dump_syms.exe')
    else:
        sys.exit(1)
    return dumpsymsPath

gitRootDirectoryCache = {}

def gitRootDirectory(path):
    directory = os.path.dirname(path)
    if directory in gitRootDirectoryCache:
        return gitRootDirectoryCache[directory]
    directoryList = directory.split(os.sep)
    while len(directoryList) > 0:
        gitDirectory = os.sep.join(directoryList + ['.git'])
        if os.path.exists(gitDirectory):
            gitDirectory = os.sep.join(directoryList)
            gitRootDirectoryCache[directory] = gitDirectory
            return gitDirectory
        directoryList.pop()

    return None


gitCommitShaCache = {}


def gitCommitSha(gitRootPath):
    if gitRootPath in gitCommitShaCache:
        return gitCommitShaCache[gitRootPath]
    gitProcess = subprocess.Popen(shlex.split('git rev-parse HEAD'),
                                  stdout=subprocess.PIPE,
                                  stderr=nullfile, cwd=gitRootPath)
    commitSha = stdoutFromProcess(gitProcess).strip('\n')
    gitCommitShaCache[gitRootPath] = commitSha
    return commitSha


gitRemoteRepositoryCache = {}


def gitRemoteRepository(gitRootPath):
    if gitRootPath in gitRemoteRepositoryCache:
        return gitRemoteRepositoryCache[gitRootPath]
    gitProcess = \
        subprocess.Popen(shlex.split('git config remote.origin.url'),
                         stdout=subprocess.PIPE, stderr=nullfile,
                         cwd=gitRootPath)
    repository = stdoutFromProcess(gitProcess).strip('\n')
    gitRemoteRepositoryCache[gitRootPath] = repository
    return repository


gitFilePathCache = {}


def populateFilePathCache(gitRootPath):
    if gitRootPath not in gitFilePathCache:
        gitProcess = \
            subprocess.Popen(shlex.split('git ls-files --full-name'),
                             stdout=subprocess.PIPE, stderr=nullfile,
                             cwd=gitRootPath)
        fileNameList = stdoutFromProcess(gitProcess).split('\n')
        filePathCache = {}
        for fileName in fileNameList:
            baseFileName = os.path.basename(fileName)
            filePathCache[baseFileName] = fileName
        gitFilePathCache[gitRootPath] = filePathCache


def gitFilePath(path, gitRootPath):
    if not gitRootPath:
        return path

    populateFilePathCache(gitRootPath)

    baseFileName = os.path.basename(path)
    filePathCache = gitFilePathCache[gitRootPath]
    if baseFileName in filePathCache:
        return filePathCache[baseFileName]
    else:
        return os.path.relpath(path, gitRootPath)


def isInRepository(path):
    gitRootPath = gitRootDirectory(path)
    if not gitRootPath:
        return False

    populateFilePathCache(gitRootPath)
    baseFileName = os.path.basename(path)
    if baseFileName in gitFilePathCache[gitRootPath]:
        return True
    else:
        return False


def sendSymbolsToServer(
    breakpadUploadUrl,
    symbolText,
    codeFile,
    debugFile,
    debugIdentifier,
    operatingSystem,
    cpu,
    ):
    (data, headers) = multipart_encode({
        'symbol_file': MultipartParam('symbol_file', value=symbolText,
                filename='symbol_file'),
        'code_file': codeFile,
        'debug_file': debugFile,
        'debug_identifier': debugIdentifier,
        'os': operatingSystem,
        'cpu': cpu,
        })
    request = urllib2.Request(breakpadUploadUrl, data, headers)
    auth = base64.encodestring('%s:%s' % (breakpadUserName,
                               breakpadUserPassword))[:-1]  # This is just standard un/pw encoding
    request.add_header('Authorization', 'Basic %s' % auth)  # Add Auth header to request
    result = urllib2.urlopen(request).read()


def generateSymbolFilesAndSend(binaryPath, projectPath):
    dumpsymsPath = toolPath()

    originalBinaryPath = binaryPath

    if sys.platform == 'darwin':
        dsymutilProcess = \
            subprocess.Popen(shlex.split('/usr/bin/dsymutil "'
                             + binaryPath + '"'), stdout=nullfile,
                             stderr=nullfile)
        dsymutilProcess.wait()
        binaryPath += os.path.join('.dSYM/Contents/Resources/DWARF/',
                                   os.path.basename(binaryPath))

    binaryPath = os.path.normpath(binaryPath)

    dumpsymsProcess = subprocess.Popen(shlex.split('"' + dumpsymsPath
            + '" "' + binaryPath + '"'), stdout=subprocess.PIPE,
            stderr=nullfile, cwd=projectPath)
    symbolList = stdoutFromProcess(dumpsymsProcess).split('\n')

    outputTextList = []
    codeFile = os.path.basename(binaryPath)
    debugFile = ''
    debugIdentifier = ''
    operatingSystem = ''
    cpu = ''
    moduleNotParsed = True
    for line in symbolList:
        line = line.strip('\n').strip('\r')
        if line[:4] == 'FILE':
            (marker, idnumber, filepath) = line.split(' ', 2)
            filepath = os.path.normpath(os.path.join(projectPath,
                    filepath))

            if isInRepository(filepath):
                gitRootPath = gitRootDirectory(filepath)
                commitSha = gitCommitSha(gitRootPath)
                repository = \
                    gitRemoteRepository(gitRootPath).replace(':', '/')
                relativeFilePath = gitFilePath(filepath,
                        gitRootPath).replace('\\', '/')
                outputTextList.append('FILE ' + idnumber + ' git:'
                        + repository + ':' + relativeFilePath + ':'
                        + commitSha)
            else:
                outputTextList.append(line)
        elif moduleNotParsed and line[:6] == 'MODULE':
            (operatingSystem, cpu, debugIdentifier, debugFile) = \
                line[7:].split(' ', 3)
            moduleNotParsed = False
        elif line:
            outputTextList.append(line)

    if moduleNotParsed:
        print 'Module not parsed'
        sys.exit(1)

    sendSymbolsToServer(
        breakpadUploadUrl,
        '\n'.join(outputTextList),
        codeFile,
        debugFile,
        debugIdentifier,
        operatingSystem,
        cpu,
        )

    if sys.platform == 'darwin':
        shutil.rmtree(originalBinaryPath + '.dSYM')


def testForBreakpad():
    try:
        dumpsymsPath = toolPath()
        if not dumpsymsPath:
            sys.exit(1)
        subprocess.Popen([dumpsymsPath], stdout=nullfile,
                         stderr=nullfile)
    except (OSError, KeyError):
        print 'No dumpsyms can be executed. Maybe  BREAKPAD_SOURCE_DIR is wrong.'
        sys.exit(1)
    sys.exit(0)


def main():
    usage = 'usage: %prog [options] binary projectpath'
    parser = OptionParser(usage=usage)
    parser.add_option('-v', '--verbose', action='store_true',
                      dest='verbose')
    parser.add_option('-e', '--breakpad-exists', action='store_true',
                      dest='testForBreakpad')

    (options, args) = parser.parse_args()

    if options.testForBreakpad == True:
        testForBreakpad()
    if len(args) > 1:
        generateSymbolFilesAndSend(args[0], args[1])
    else:
        parser.print_help()


if __name__ == '__main__':
    main()