Debian Codegraph @

toolkit/crashreporter/tools/symbolstore.py

raw
1 #!/bin/env python
2 # This Source Code Form is subject to the terms of the Mozilla Public
3 # License, v. 2.0. If a copy of the MPL was not distributed with this
4 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 #
6 # Usage: symbolstore.py <params> <dump_syms path> <symbol store path>
7 # <debug info files or dirs>
8 # Runs dump_syms on each debug info file specified on the command line,
9 # then places the resulting symbol file in the proper directory
10 # structure in the symbol store path. Accepts multiple files
11 # on the command line, so can be called as part of a pipe using
12 # find <dir> | xargs symbolstore.pl <dump_syms> <storepath>
13 # But really, you might just want to pass it <dir>.
14 #
15 # Parameters accepted:
16 # -c : Copy debug info files to the same directory structure
17 # as sym files. On Windows, this will also copy
18 # binaries into the symbol store.
19 # -a "<archs>" : Run dump_syms -a <arch> for each space separated
20 # cpu architecture in <archs> (only on OS X)
21 # -s <srcdir> : Use <srcdir> as the top source directory to
22 # generate relative filenames.
23
24 import ctypes
25 import errno
26 import os
27 import platform
28 import re
29 import shutil
30 import subprocess
31 import sys
32 import textwrap
33 import time
34 from optparse import OptionParser
35 from pathlib import Path
36
37 import buildconfig
38 from mozbuild.generated_sources import (
39 GENERATED_SOURCE_EXTS,
40 get_filename_with_digest,
41 get_s3_region_and_bucket,
42 )
43 from mozbuild.util import memoize
44 from mozpack import executables
45 from mozpack.copier import FileRegistry
46 from mozpack.manifests import InstallManifest, UnreadableInstallManifest
47 from variables import get_buildid
48
49 # Utility classes
50
51
52 class VCSFileInfo:
53 """A base class for version-controlled file information. Ensures that the
54 following attributes are generated only once (successfully):
55
56 self.root
57 self.clean_root
58 self.revision
59 self.filename
60
61 The attributes are generated by a single call to the GetRoot,
62 GetRevision, and GetFilename methods. Those methods are explicitly not
63 implemented here and must be implemented in derived classes."""
64
65 def __init__(self, file):
66 if not file:
67 raise ValueError
68 self.file = file
69
70 def __getattr__(self, name):
71 """__getattr__ is only called for attributes that are not set on self,
72 so setting self.[attr] will prevent future calls to the GetRoot,
73 GetRevision, and GetFilename methods. We don't set the values on
74 failure on the off chance that a future call might succeed."""
75
76 if name == "root":
77 root = self.GetRoot()
78 if root:
79 self.root = root
80 return root
81
82 elif name == "clean_root":
83 clean_root = self.GetCleanRoot()
84 if clean_root:
85 self.clean_root = clean_root
86 return clean_root
87
88 elif name == "revision":
89 revision = self.GetRevision()
90 if revision:
91 self.revision = revision
92 return revision
93
94 elif name == "filename":
95 filename = self.GetFilename()
96 if filename:
97 self.filename = filename
98 return filename
99
100 raise AttributeError
101
102 def GetRoot(self):
103 """This method should return the unmodified root for the file or 'None'
104 on failure."""
105 raise NotImplementedError
106
107 def GetCleanRoot(self):
108 """This method should return the repository root for the file or 'None'
109 on failure."""
110 raise NotImplementedError
111
112 def GetRevision(self):
113 """This method should return the revision number for the file or 'None'
114 on failure."""
115 raise NotImplementedError
116
117 def GetFilename(self):
118 """This method should return the repository-specific filename for the
119 file or 'None' on failure."""
120 raise NotImplementedError
121
122
123 # This regex separates protocol and optional username/password from a url.
124 # For instance, all the following urls will be transformed into
125 # 'foo.com/bar':
126 #
127 # http://foo.com/bar
128 # svn+ssh://[email protected]/bar
129 # svn+ssh://user:[email protected]/bar
130 #
131 rootRegex = re.compile(r"^\S+?:/+(?:[^\s/]*@)?(\S+)$")
132
133
134 def read_output(*args):
135 (stdout, _) = subprocess.Popen(
136 args=args, universal_newlines=True, stdout=subprocess.PIPE
137 ).communicate()
138 return stdout.rstrip()
139
140
141 class HGRepoInfo:
142 def __init__(self, path):
143 self.path = path
144
145 rev = os.environ.get("MOZ_SOURCE_CHANGESET")
146 if not rev:
147 rev = read_output("hg", "-R", path, "parent", "--template={node}")
148
149 # Look for the default hg path. If MOZ_SOURCE_REPO is set, we
150 # don't bother asking hg.
151 hg_root = os.environ.get("MOZ_SOURCE_REPO")
152 if hg_root:
153 root = hg_root
154 else:
155 root = read_output("hg", "-R", path, "showconfig", "paths.default")
156 if not root:
157 print("Failed to get HG Repo for %s" % path, file=sys.stderr)
158 cleanroot = None
159 if root:
160 match = rootRegex.match(root)
161 if match:
162 cleanroot = match.group(1)
163 if cleanroot.endswith("/"):
164 cleanroot = cleanroot[:-1]
165 if cleanroot is None:
166 print(
167 textwrap.dedent(
168 """\
169 Could not determine repo info for %s. This is either not a clone of the web-based
170 repository, or you have not specified MOZ_SOURCE_REPO, or the clone is corrupt."""
171 )
172 % path,
173 sys.stderr,
174 )
175 sys.exit(1)
176 self.rev = rev
177 self.root = root
178 self.cleanroot = cleanroot
179
180 def GetFileInfo(self, file):
181 return HGFileInfo(file, self)
182
183
184 class HGFileInfo(VCSFileInfo):
185 def __init__(self, file, repo):
186 VCSFileInfo.__init__(self, file)
187 self.repo = repo
188 self.file = os.path.relpath(file, repo.path)
189
190 def GetRoot(self):
191 return self.repo.root
192
193 def GetCleanRoot(self):
194 return self.repo.cleanroot
195
196 def GetRevision(self):
197 return self.repo.rev
198
199 def GetFilename(self):
200 if self.revision and self.clean_root:
201 return "hg:%s:%s:%s" % (self.clean_root, self.file, self.revision)
202 return self.file
203
204
205 class GitRepoInfo:
206 """
207 Info about a local git repository. Does not currently
208 support discovering info about a git clone, the info must be
209 provided out-of-band.
210 """
211
212 def __init__(self, path, rev, root):
213 self.path = path
214 cleanroot = None
215 if root:
216 match = rootRegex.match(root)
217 if match:
218 cleanroot = match.group(1)
219 if cleanroot.endswith("/"):
220 cleanroot = cleanroot[:-1]
221 if cleanroot is None:
222 print(
223 textwrap.dedent(
224 """\
225 Could not determine repo info for %s (%s). This is either not a clone of a web-based
226 repository, or you have not specified MOZ_SOURCE_REPO, or the clone is corrupt."""
227 )
228 % (path, root),
229 file=sys.stderr,
230 )
231 sys.exit(1)
232 self.rev = rev
233 self.cleanroot = cleanroot
234
235 def GetFileInfo(self, file):
236 return GitFileInfo(file, self)
237
238
239 class GitFileInfo(VCSFileInfo):
240 def __init__(self, file, repo):
241 VCSFileInfo.__init__(self, file)
242 self.repo = repo
243 self.file = os.path.relpath(file, repo.path)
244
245 def GetRoot(self):
246 return self.repo.path
247
248 def GetCleanRoot(self):
249 return self.repo.cleanroot
250
251 def GetRevision(self):
252 return self.repo.rev
253
254 def GetFilename(self):
255 if self.revision and self.clean_root:
256 return "git:%s:%s:%s" % (self.clean_root, self.file, self.revision)
257 return self.file
258
259
260 # Utility functions
261
262
263 # A cache of files for which VCS info has already been determined. Used to
264 # prevent extra filesystem activity or process launching.
265 vcsFileInfoCache = {}
266
267 if platform.system() == "Windows":
268
269 def realpath(path):
270 """
271 Normalize a path using `GetFinalPathNameByHandleW` to get the
272 path with all components in the case they exist in on-disk, so
273 that making links to a case-sensitive server (hg.mozilla.org) works.
274
275 This function also resolves any symlinks in the path.
276 """
277 # Return the original path if something fails, which can happen for paths that
278 # don't exist on this system (like paths from the CRT).
279 result = path
280
281 ctypes.windll.kernel32.SetErrorMode(ctypes.c_uint(1))
282 handle = ctypes.windll.kernel32.CreateFileW(
283 path,
284 # GENERIC_READ
285 0x80000000,
286 # FILE_SHARE_READ
287 1,
288 None,
289 # OPEN_EXISTING
290 3,
291 # FILE_FLAG_BACKUP_SEMANTICS
292 # This is necessary to open
293 # directory handles.
294 0x02000000,
295 None,
296 )
297 if handle != -1:
298 size = ctypes.windll.kernel32.GetFinalPathNameByHandleW(handle, None, 0, 0)
299 buf = ctypes.create_unicode_buffer(size)
300 if (
301 ctypes.windll.kernel32.GetFinalPathNameByHandleW(handle, buf, size, 0)
302 > 0
303 ):
304 # The return value of GetFinalPathNameByHandleW uses the
305 # '\\?\' prefix.
306 result = buf.value[4:]
307 ctypes.windll.kernel32.CloseHandle(handle)
308 return result
309
310 else:
311 # Just use the os.path version otherwise.
312 realpath = os.path.realpath
313
314
315 def IsInDir(file, dir):
316 try:
317 Path(file).relative_to(dir)
318 return True
319 except ValueError:
320 return False
321
322
323 def GetVCSFilenameFromSrcdir(file, srcdir):
324 if srcdir not in Dumper.srcdirRepoInfo:
325 # Not in cache, so find it adnd cache it
326 if os.path.isdir(os.path.join(srcdir, ".hg")):
327 Dumper.srcdirRepoInfo[srcdir] = HGRepoInfo(srcdir)
328 else:
329 # Unknown VCS or file is not in a repo.
330 return None
331 return Dumper.srcdirRepoInfo[srcdir].GetFileInfo(file)
332
333
334 def GetVCSFilename(file, srcdirs):
335 """Given a full path to a file, and the top source directory,
336 look for version control information about this file, and return
337 a tuple containing
338 1) a specially formatted filename that contains the VCS type,
339 VCS location, relative filename, and revision number, formatted like:
340 vcs:vcs location:filename:revision
341 For example:
342 cvs:cvs.mozilla.org/cvsroot:mozilla/browser/app/nsBrowserApp.cpp:1.36
343 2) the unmodified root information if it exists"""
344 (path, filename) = os.path.split(file)
345 if path == "" or filename == "":
346 return (file, None)
347
348 fileInfo = None
349 root = ""
350 if file in vcsFileInfoCache:
351 # Already cached this info, use it.
352 fileInfo = vcsFileInfoCache[file]
353 else:
354 for srcdir in srcdirs:
355 if not IsInDir(file, srcdir):
356 continue
357 fileInfo = GetVCSFilenameFromSrcdir(file, srcdir)
358 if fileInfo:
359 vcsFileInfoCache[file] = fileInfo
360 break
361
362 if fileInfo:
363 file = fileInfo.filename
364 root = fileInfo.root
365
366 # we want forward slashes on win32 paths
367 return (file.replace("\\", "/"), root)
368
369
370 def validate_install_manifests(install_manifest_args):
371 args = []
372 for arg in install_manifest_args:
373 bits = arg.split(",")
374 if len(bits) != 2:
375 raise ValueError(
376 "Invalid format for --install-manifest: " "specify manifest,target_dir"
377 )
378 manifest_file, destination = [os.path.abspath(b) for b in bits]
379 if not os.path.isfile(manifest_file):
380 raise OSError(errno.ENOENT, "Manifest file not found", manifest_file)
381 if not os.path.isdir(destination):
382 raise OSError(errno.ENOENT, "Install directory not found", destination)
383 try:
384 manifest = InstallManifest(manifest_file)
385 except UnreadableInstallManifest:
386 raise OSError(errno.EINVAL, "Error parsing manifest file", manifest_file)
387 args.append((manifest, destination))
388 return args
389
390
391 def make_file_mapping(install_manifests):
392 file_mapping = {}
393 for manifest, destination in install_manifests:
394 absolute_destination = os.path.abspath(destination)
395 reg = FileRegistry()
396 manifest.populate_registry(reg)
397 for dst, src in reg:
398 if hasattr(src, "path"):
399 # Any paths that get compared to source file names need to go through realpath.
400 abs_dest = realpath(os.path.join(absolute_destination, dst))
401 file_mapping[abs_dest] = realpath(src.path)
402 return file_mapping
403
404
405 @memoize
406 def get_generated_file_s3_path(filename, rel_path, bucket):
407 """Given a filename, return a path formatted similarly to
408 GetVCSFilename but representing a file available in an s3 bucket."""
409 with open(filename, "rb") as f:
410 path = get_filename_with_digest(rel_path, f.read())
411 return f"s3:{bucket}:{path}:"
412
413
414 def GetPlatformSpecificDumper(**kwargs):
415 """This function simply returns a instance of a subclass of Dumper
416 that is appropriate for the current platform."""
417 return {"WINNT": Dumper_Win32, "Linux": Dumper_Linux, "Darwin": Dumper_Mac}[
418 buildconfig.substs["OS_ARCH"]
419 ](**kwargs)
420
421
422 def SourceIndex(fileStream, outputPath, vcs_root, s3_bucket):
423 """Takes a list of files, writes info to a data block in a .stream file"""
424 # Creates a .pdb.stream file in the mozilla\objdir to be used for source indexing
425 # Create the srcsrv data block that indexes the pdb file
426 result = True
427 pdbStreamFile = open(outputPath, "w")
428 pdbStreamFile.write(
429 "SRCSRV: ini ------------------------------------------------\r\n"
430 + "VERSION=2\r\n"
431 + "INDEXVERSION=2\r\n"
432 + "VERCTRL=http\r\n"
433 + "SRCSRV: variables ------------------------------------------\r\n"
434 + "SRCSRVVERCTRL=http\r\n"
435 + "RUST_GITHUB_TARGET=https://github.com/rust-lang/rust/raw/%var4%/%var3%\r\n"
436 )
437 pdbStreamFile.write("HGSERVER=" + vcs_root + "\r\n")
438 pdbStreamFile.write("HG_TARGET=%hgserver%/raw-file/%var4%/%var3%\r\n")
439
440 if s3_bucket:
441 pdbStreamFile.write("S3_BUCKET=" + s3_bucket + "\r\n")
442 pdbStreamFile.write("S3_TARGET=https://%s3_bucket%.s3.amazonaws.com/%var3%\r\n")
443
444 # Allow each entry to choose its template via "var2".
445 # Possible values for var2 are: HG_TARGET / S3_TARGET / RUST_GITHUB_TARGET
446 pdbStreamFile.write("SRCSRVTRG=%fnvar%(%var2%)\r\n")
447
448 pdbStreamFile.write(
449 "SRCSRV: source files ---------------------------------------\r\n"
450 )
451 pdbStreamFile.write(fileStream)
452 pdbStreamFile.write(
453 "SRCSRV: end ------------------------------------------------\r\n\n"
454 )
455 pdbStreamFile.close()
456 return result
457
458
459 class Dumper:
460 """This class can dump symbols from a file with debug info, and
461 store the output in a directory structure that is valid for use as
462 a Breakpad symbol server. Requires a path to a dump_syms binary--
463 |dump_syms| and a directory to store symbols in--|symbol_path|.
464 Optionally takes a list of processor architectures to process from
465 each debug file--|archs|, the full path to the top source
466 directory--|srcdir|, for generating relative source file names,
467 and an option to copy debug info files alongside the dumped
468 symbol files--|copy_debug|, mostly useful for creating a
469 Microsoft Symbol Server from the resulting output.
470
471 You don't want to use this directly if you intend to process files.
472 Instead, call GetPlatformSpecificDumper to get an instance of a
473 subclass."""
474
475 srcdirRepoInfo = {}
476
477 def __init__(
478 self,
479 dump_syms,
480 symbol_path,
481 archs=None,
482 srcdirs=[],
483 copy_debug=False,
484 vcsinfo=False,
485 srcsrv=False,
486 s3_bucket=None,
487 file_mapping=None,
488 ):
489 # popen likes absolute paths, at least on windows
490 self.dump_syms = os.path.abspath(dump_syms)
491 self.symbol_path = symbol_path
492 if archs is None:
493 # makes the loop logic simpler
494 self.archs = [""]
495 else:
496 self.archs = ["-a %s" % a for a in archs.split()]
497 # Any paths that get compared to source file names need to go through realpath.
498 self.srcdirs = [realpath(s) for s in srcdirs]
499 self.copy_debug = copy_debug
500 self.vcsinfo = vcsinfo
501 self.srcsrv = srcsrv
502 self.s3_bucket = s3_bucket
503 self.file_mapping = file_mapping or {}
504 # Add a static mapping for Rust sources. Since Rust 1.30 official Rust builds map
505 # source paths to start with "/rust/<sha>/".
506 rust_sha = buildconfig.substs["RUSTC_COMMIT"]
507 rust_srcdir = "/rustc/" + rust_sha
508 self.srcdirs.append(rust_srcdir)
509 Dumper.srcdirRepoInfo[rust_srcdir] = GitRepoInfo(
510 rust_srcdir, rust_sha, "https://github.com/rust-lang/rust/"
511 )
512
513 # subclasses override this
514 def ShouldProcess(self, file):
515 return True
516
517 # This is a no-op except on Win32
518 def SourceServerIndexing(
519 self, debug_file, guid, sourceFileStream, vcs_root, s3_bucket
520 ):
521 return ""
522
523 # subclasses override this if they want to support this
524 def CopyExeAndDebugInfo(self, file, debug_file, guid, code_file, code_id):
525 """This function will copy a library or executable and the file holding the
526 debug information to |symbol_path|"""
527 pass
528
529 def Process(self, file_to_process, count_ctors=False):
530 """Process the given file."""
531 if self.ShouldProcess(os.path.abspath(file_to_process)):
532 self.ProcessFile(file_to_process, count_ctors=count_ctors)
533
534 def ProcessFile(self, file, dsymbundle=None, count_ctors=False):
535 """Dump symbols from these files into a symbol file, stored
536 in the proper directory structure in |symbol_path|; processing is performed
537 asynchronously, and Finish must be called to wait for it complete and cleanup.
538 All files after the first are fallbacks in case the first file does not process
539 successfully; if it does, no other files will be touched."""
540 print("Beginning work for file: %s" % file, file=sys.stderr)
541
542 # tries to get the vcs root from the .mozconfig first - if it's not set
543 # the tinderbox vcs path will be assigned further down
544 vcs_root = os.environ.get("MOZ_SOURCE_REPO")
545 for arch_num, arch in enumerate(self.archs):
546 self.ProcessFileWork(
547 file, arch_num, arch, vcs_root, dsymbundle, count_ctors=count_ctors
548 )
549
550 def dump_syms_cmdline(self, file, arch, dsymbundle=None):
551 """
552 Get the commandline used to invoke dump_syms.
553 """
554 # The Mac dumper overrides this.
555 cmdline = [
556 self.dump_syms,
557 "--inlines",
558 ]
559
560 cmdline.extend(self.dump_syms_extra_info())
561 cmdline.append(file)
562
563 return cmdline
564
565 def dump_syms_extra_info(self):
566 """
567 Returns an array with the additional parameters to add information
568 about the build to the dump_syms command-line
569 """
570 cmdline = [
571 "--extra-info",
572 "RELEASECHANNEL " + buildconfig.substs["MOZ_UPDATE_CHANNEL"],
573 "--extra-info",
574 "VERSION " + buildconfig.substs["MOZ_APP_VERSION"],
575 ]
576
577 if buildconfig.substs.get("MOZ_APP_VENDOR") is not None:
578 cmdline.extend(
579 [
580 "--extra-info",
581 "VENDOR " + buildconfig.substs["MOZ_APP_VENDOR"],
582 ]
583 )
584
585 if buildconfig.substs.get("MOZ_APP_BASENAME") is not None:
586 cmdline.extend(
587 [
588 "--extra-info",
589 "PRODUCTNAME " + buildconfig.substs["MOZ_APP_BASENAME"],
590 ]
591 )
592
593 # Add the build ID if it's present
594 try:
595 buildid = get_buildid()
596 cmdline.extend(
597 [
598 "--extra-info",
599 "BUILDID " + buildid,
600 ]
601 )
602 except Exception:
603 pass
604
605 return cmdline
606
607 def ProcessFileWork(
608 self, file, arch_num, arch, vcs_root, dsymbundle=None, count_ctors=False
609 ):
610 ctors = 0
611 t_start = time.time()
612 print("Processing file: %s" % file, file=sys.stderr)
613
614 sourceFileStream = ""
615 code_id, code_file = None, None
616 try:
617 cmd = self.dump_syms_cmdline(file, arch, dsymbundle=dsymbundle)
618 print(" ".join(cmd), file=sys.stderr)
619 proc = subprocess.Popen(
620 cmd,
621 universal_newlines=True,
622 stdout=subprocess.PIPE,
623 )
624 try:
625 module_line = next(proc.stdout)
626 except StopIteration:
627 module_line = ""
628 if module_line.startswith("MODULE"):
629 # MODULE os cpu guid debug_file
630 (guid, debug_file) = (module_line.split())[3:5]
631 # strip off .pdb extensions, and append .sym
632 sym_file = re.sub(r"\.pdb$", "", debug_file) + ".sym"
633 # we do want forward slashes here
634 rel_path = os.path.join(debug_file, guid, sym_file).replace("\\", "/")
635 full_path = os.path.normpath(os.path.join(self.symbol_path, rel_path))
636 try:
637 os.makedirs(os.path.dirname(full_path))
638 except OSError: # already exists
639 pass
640 f = open(full_path, "w")
641 f.write(module_line)
642 # now process the rest of the output
643 for line in proc.stdout:
644 if line.startswith("FILE"):
645 # FILE index filename
646 (x, index, filename) = line.rstrip().split(None, 2)
647 # We want original file paths for the source server.
648 sourcepath = filename
649 filename = realpath(filename)
650 if filename in self.file_mapping:
651 filename = self.file_mapping[filename]
652 if self.vcsinfo:
653 try:
654 gen_path = Path(filename)
655 rel_gen_path = gen_path.relative_to(
656 buildconfig.topobjdir
657 )
658 except ValueError:
659 gen_path = None
660 if (
661 gen_path
662 and gen_path.exists()
663 and gen_path.suffix in GENERATED_SOURCE_EXTS
664 and self.s3_bucket
665 ):
666 filename = get_generated_file_s3_path(
667 filename, str(rel_gen_path), self.s3_bucket
668 )
669 rootname = ""
670 else:
671 (filename, rootname) = GetVCSFilename(
672 filename, self.srcdirs
673 )
674 # sets vcs_root in case the loop through files were to end
675 # on an empty rootname
676 if vcs_root is None:
677 if rootname:
678 vcs_root = rootname
679 # Emit an entry for the file mapping for the srcsrv stream
680 if filename.startswith("hg:"):
681 (vcs, repo, source_file, revision) = filename.split(":", 3)
682 sourceFileStream += sourcepath + "*HG_TARGET*" + source_file
683 sourceFileStream += "*" + revision + "\r\n"
684 elif filename.startswith("s3:"):
685 (vcs, bucket, source_file, nothing) = filename.split(":", 3)
686 sourceFileStream += sourcepath + "*S3_TARGET*"
687 sourceFileStream += source_file + "\r\n"
688 elif filename.startswith("git:github.com/rust-lang/rust:"):
689 (vcs, repo, source_file, revision) = filename.split(":", 3)
690 sourceFileStream += sourcepath + "*RUST_GITHUB_TARGET*"
691 sourceFileStream += source_file + "*" + revision + "\r\n"
692 f.write("FILE %s %s\n" % (index, filename))
693 elif line.startswith("INFO CODE_ID "):
694 # INFO CODE_ID code_id code_file
695 # This gives some info we can use to
696 # store binaries in the symbol store.
697 bits = line.rstrip().split(None, 3)
698 if len(bits) == 4:
699 code_id, code_file = bits[2:]
700 f.write(line)
701 else:
702 if count_ctors and line.startswith("FUNC "):
703 # Static initializers, as created by clang and gcc
704 # have symbols that start with "_GLOBAL_sub"
705 if "_GLOBAL__sub_" in line:
706 ctors += 1
707 # MSVC creates `dynamic initializer for '...'`
708 # symbols.
709 elif "`dynamic initializer for '" in line:
710 ctors += 1
711
712 # pass through all other lines unchanged
713 f.write(line)
714 f.close()
715 retcode = proc.wait()
716 if retcode != 0:
717 raise RuntimeError(
718 "dump_syms failed with error code %d while processing %s\n"
719 % (retcode, file)
720 )
721 # we output relative paths so callers can get a list of what
722 # was generated
723 print(rel_path)
724 if self.srcsrv and vcs_root:
725 # add source server indexing to the pdb file
726 self.SourceServerIndexing(
727 debug_file, guid, sourceFileStream, vcs_root, self.s3_bucket
728 )
729 # only copy debug the first time if we have multiple architectures
730 if self.copy_debug and arch_num == 0:
731 self.CopyExeAndDebugInfo(file, debug_file, guid, code_file, code_id)
732 else:
733 # For some reason, we didn't see the MODULE line as the first
734 # line of output, this is strictly required so fail irrespective
735 # of the process' return code.
736 retcode = proc.wait()
737 message = [
738 "dump_syms failed to produce the expected output",
739 "file: %s" % file,
740 "return code: %d" % retcode,
741 "first line of output: %s" % module_line,
742 ]
743 raise RuntimeError("\n----------\n".join(message))
744 except Exception as e:
745 print("Unexpected error: %s" % str(e), file=sys.stderr)
746 raise
747
748 if dsymbundle:
749 shutil.rmtree(dsymbundle)
750
751 if count_ctors:
752 import json
753
754 perfherder_data = {
755 "framework": {"name": "build_metrics"},
756 "suites": [
757 {
758 "name": "compiler_metrics",
759 "subtests": [
760 {
761 "name": "num_static_constructors",
762 "value": ctors,
763 "alertChangeType": "absolute",
764 "alertThreshold": 3,
765 }
766 ],
767 }
768 ],
769 }
770 perfherder_extra_options = os.environ.get("PERFHERDER_EXTRA_OPTIONS", "")
771 for opt in perfherder_extra_options.split():
772 for suite in perfherder_data["suites"]:
773 if opt not in suite.get("extraOptions", []):
774 suite.setdefault("extraOptions", []).append(opt)
775
776 if "asan" not in perfherder_extra_options.lower():
777 print(
778 "PERFHERDER_DATA: %s" % json.dumps(perfherder_data), file=sys.stderr
779 )
780
781 elapsed = time.time() - t_start
782 print("Finished processing %s in %.2fs" % (file, elapsed), file=sys.stderr)
783
784
785 # Platform-specific subclasses. For the most part, these just have
786 # logic to determine what files to extract symbols from.
787
788
789 def locate_pdb(path):
790 """Given a path to a binary, attempt to locate the matching pdb file with simple heuristics:
791 * Look for a pdb file with the same base name next to the binary
792 * Look for a pdb file with the same base name in the cwd
793
794 Returns the path to the pdb file if it exists, or None if it could not be located.
795 """
796 path, ext = os.path.splitext(path)
797 pdb = path + ".pdb"
798 if os.path.isfile(pdb):
799 return pdb
800 # If there's no pdb next to the file, see if there's a pdb with the same root name
801 # in the cwd. We build some binaries directly into dist/bin, but put the pdb files
802 # in the relative objdir, which is the cwd when running this script.
803 base = os.path.basename(pdb)
804 pdb = os.path.join(os.getcwd(), base)
805 if os.path.isfile(pdb):
806 return pdb
807 return None
808
809
810 class Dumper_Win32(Dumper):
811 fixedFilenameCaseCache = {}
812
813 def ShouldProcess(self, file):
814 """This function will allow processing of exe or dll files that have pdb
815 files with the same base name next to them."""
816 if file.endswith(".exe") or file.endswith(".dll"):
817 if locate_pdb(file) is not None:
818 return True
819 return False
820
821 def CopyExeAndDebugInfo(self, file, debug_file, guid, code_file, code_id):
822 """This function will copy the executable or dll and pdb files to |symbol_path|"""
823 pdb_file = locate_pdb(file)
824
825 rel_path = os.path.join(debug_file, guid, debug_file).replace("\\", "/")
826 full_path = os.path.normpath(os.path.join(self.symbol_path, rel_path))
827 shutil.copyfile(pdb_file, full_path)
828 print(rel_path)
829
830 # Copy the binary file as well
831 if code_file and code_id:
832 full_code_path = os.path.join(os.path.dirname(file), code_file)
833 if os.path.exists(full_code_path):
834 rel_path = os.path.join(code_file, code_id, code_file).replace(
835 "\\", "/"
836 )
837 full_path = os.path.normpath(os.path.join(self.symbol_path, rel_path))
838 try:
839 os.makedirs(os.path.dirname(full_path))
840 except OSError as e:
841 if e.errno != errno.EEXIST:
842 raise
843 shutil.copyfile(full_code_path, full_path)
844 print(rel_path)
845
846 def SourceServerIndexing(
847 self, debug_file, guid, sourceFileStream, vcs_root, s3_bucket
848 ):
849 # Creates a .pdb.stream file in the mozilla\objdir to be used for source indexing
850 streamFilename = debug_file + ".stream"
851 stream_output_path = os.path.abspath(streamFilename)
852 # Call SourceIndex to create the .stream file
853 result = SourceIndex(sourceFileStream, stream_output_path, vcs_root, s3_bucket)
854 if self.copy_debug:
855 pdbstr = buildconfig.substs["PDBSTR"]
856 wine = buildconfig.substs.get("WINE")
857 if wine:
858 cmd = [wine, pdbstr]
859 else:
860 cmd = [pdbstr]
861 subprocess.call(
862 cmd
863 + [
864 "-w",
865 "-p:" + os.path.basename(debug_file),
866 "-i:" + os.path.basename(streamFilename),
867 "-s:srcsrv",
868 ],
869 cwd=os.path.dirname(stream_output_path),
870 )
871 # clean up all the .stream files when done
872 os.remove(stream_output_path)
873 return result
874
875
876 class Dumper_Linux(Dumper):
877 objcopy = os.environ["OBJCOPY"] if "OBJCOPY" in os.environ else "objcopy"
878
879 def ShouldProcess(self, file):
880 """This function will allow processing of files that are
881 executable, or end with the .so extension, and additionally
882 file(1) reports as being ELF files. It expects to find the file
883 command in PATH."""
884 if file.endswith(".so") or os.access(file, os.X_OK):
885 return executables.get_type(file) == executables.ELF
886 return False
887
888 def CopyExeAndDebugInfo(self, file, debug_file, guid, code_file, code_id):
889 # We want to strip out the debug info, and add a
890 # .gnu_debuglink section to the object, so the debugger can
891 # actually load our debug info later.
892 # In some odd cases, the object might already have an irrelevant
893 # .gnu_debuglink section, and objcopy doesn't want to add one in
894 # such cases, so we make it remove it any existing one first.
895 file_dbg = file + ".dbg"
896 if (
897 subprocess.call([self.objcopy, "--only-keep-debug", file, file_dbg]) == 0
898 and subprocess.call(
899 [
900 self.objcopy,
901 "--remove-section",
902 ".gnu_debuglink",
903 "--add-gnu-debuglink=%s" % file_dbg,
904 file,
905 ]
906 )
907 == 0
908 ):
909 rel_path = os.path.join(debug_file, guid, debug_file + ".dbg")
910 full_path = os.path.normpath(os.path.join(self.symbol_path, rel_path))
911 shutil.move(file_dbg, full_path)
912 print(rel_path)
913 elif os.path.isfile(file_dbg):
914 os.unlink(file_dbg)
915
916
917 class Dumper_Solaris(Dumper):
918 def ShouldProcess(self, file):
919 """This function will allow processing of files that are
920 executable, or end with the .so extension, and additionally
921 file(1) reports as being ELF files. It expects to find the file
922 command in PATH."""
923 if file.endswith(".so") or os.access(file, os.X_OK):
924 return executables.get_type(file) == executables.ELF
925 return False
926
927
928 class Dumper_Mac(Dumper):
929 def ShouldProcess(self, file):
930 """This function will allow processing of files that are
931 executable, or end with the .dylib extension, and additionally
932 file(1) reports as being Mach-O files. It expects to find the file
933 command in PATH."""
934 if file.endswith(".dylib") or os.access(file, os.X_OK):
935 return executables.get_type(file) == executables.MACHO
936 return False
937
938 def ProcessFile(self, file, count_ctors=False):
939 print("Starting Mac pre-processing on file: %s" % file, file=sys.stderr)
940 dsymbundle = self.GenerateDSYM(file)
941 if dsymbundle:
942 # kick off new jobs per-arch with our new list of files
943 Dumper.ProcessFile(
944 self, file, dsymbundle=dsymbundle, count_ctors=count_ctors
945 )
946
947 def dump_syms_cmdline(self, file, arch, dsymbundle=None):
948 """
949 Get the commandline used to invoke dump_syms.
950 """
951 # dump_syms wants the path to the original binary and the .dSYM
952 # in order to dump all the symbols.
953 if dsymbundle:
954 # This is the .dSYM bundle.
955 cmdline = [self.dump_syms]
956
957 cmdline.extend(arch.split())
958 cmdline.extend(
959 [
960 "--inlines",
961 "-j",
962 "2",
963 ]
964 )
965
966 cmdline.extend(self.dump_syms_extra_info())
967 cmdline.extend([dsymbundle, file])
968
969 return cmdline
970
971 return Dumper.dump_syms_cmdline(self, file, arch)
972
973 def GenerateDSYM(self, file):
974 """dump_syms on Mac needs to be run on a dSYM bundle produced
975 by dsymutil(1), so run dsymutil here and pass the bundle name
976 down to the superclass method instead."""
977 t_start = time.time()
978 print("Running Mac pre-processing on file: %s" % (file,), file=sys.stderr)
979
980 dsymbundle = file + ".dSYM"
981 if os.path.exists(dsymbundle):
982 shutil.rmtree(dsymbundle)
983 dsymutil = buildconfig.substs["DSYMUTIL"]
984 # dsymutil takes --arch=foo instead of -a foo like everything else
985 cmd = (
986 [dsymutil] + [a.replace("-a ", "--arch=") for a in self.archs if a] + [file]
987 )
988 print(" ".join(cmd), file=sys.stderr)
989
990 dsymutil_proc = subprocess.Popen(
991 cmd, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
992 )
993 dsymout, dsymerr = dsymutil_proc.communicate()
994 if dsymutil_proc.returncode != 0:
995 raise RuntimeError("Error running dsymutil: %s" % dsymerr)
996
997 # Regular dsymutil won't produce a .dSYM for files without symbols.
998 if not os.path.exists(dsymbundle):
999 print("No symbols found in file: %s" % (file,), file=sys.stderr)
1000 return False
1001
1002 # llvm-dsymutil will produce a .dSYM for files without symbols or
1003 # debug information, but only sometimes will it warn you about this.
1004 # We don't want to run dump_syms on such bundles, because asserts
1005 # will fire in debug mode and who knows what will happen in release.
1006 #
1007 # So we check for the error message and bail if it appears. If it
1008 # doesn't, we carefully check the bundled DWARF to see if dump_syms
1009 # will be OK with it.
1010 if "warning: no debug symbols in" in dsymerr:
1011 print(dsymerr, file=sys.stderr)
1012 return False
1013
1014 contents_dir = os.path.join(dsymbundle, "Contents", "Resources", "DWARF")
1015 if not os.path.exists(contents_dir):
1016 print(
1017 "No DWARF information in .dSYM bundle %s" % (dsymbundle,),
1018 file=sys.stderr,
1019 )
1020 return False
1021
1022 files = os.listdir(contents_dir)
1023 if len(files) != 1:
1024 print("Unexpected files in .dSYM bundle %s" % (files,), file=sys.stderr)
1025 return False
1026
1027 otool_out = subprocess.check_output(
1028 [buildconfig.substs["OTOOL"], "-l", os.path.join(contents_dir, files[0])],
1029 universal_newlines=True,
1030 )
1031 if "sectname __debug_info" not in otool_out:
1032 print("No symbols in .dSYM bundle %s" % (dsymbundle,), file=sys.stderr)
1033 return False
1034
1035 elapsed = time.time() - t_start
1036 print("Finished processing %s in %.2fs" % (file, elapsed), file=sys.stderr)
1037 return dsymbundle
1038
1039 def CopyExeAndDebugInfo(self, file, debug_file, guid, code_file, code_id):
1040 """ProcessFile has already produced a dSYM bundle, so we should just
1041 copy that to the destination directory. However, we'll package it
1042 into a .tar because it's a bundle, so it's a directory. |file| here is
1043 the original filename."""
1044 dsymbundle = file + ".dSYM"
1045 rel_path = os.path.join(debug_file, guid, os.path.basename(dsymbundle) + ".tar")
1046 full_path = os.path.abspath(os.path.join(self.symbol_path, rel_path))
1047 success = subprocess.call(
1048 ["tar", "cf", full_path, os.path.basename(dsymbundle)],
1049 cwd=os.path.dirname(dsymbundle),
1050 stdout=open(os.devnull, "w"),
1051 stderr=subprocess.STDOUT,
1052 )
1053 if success == 0 and os.path.exists(full_path):
1054 print(rel_path)
1055
1056
1057 # Entry point if called as a standalone program
1058
1059
1060 def main():
1061 parser = OptionParser(
1062 usage="usage: %prog [options] <dump_syms binary> <symbol store path> <debug info files>"
1063 )
1064 parser.add_option(
1065 "-c",
1066 "--copy",
1067 action="store_true",
1068 dest="copy_debug",
1069 default=False,
1070 help="Copy debug info files into the same directory structure as symbol files",
1071 )
1072 parser.add_option(
1073 "-a",
1074 "--archs",
1075 action="store",
1076 dest="archs",
1077 help="Run dump_syms -a <arch> for each space separated"
1078 + "cpu architecture in ARCHS (only on OS X)",
1079 )
1080 parser.add_option(
1081 "-s",
1082 "--srcdir",
1083 action="append",
1084 dest="srcdir",
1085 default=[],
1086 help="Use SRCDIR to determine relative paths to source files",
1087 )
1088 parser.add_option(
1089 "-v",
1090 "--vcs-info",
1091 action="store_true",
1092 dest="vcsinfo",
1093 help="Try to retrieve VCS info for each FILE listed in the output",
1094 )
1095 parser.add_option(
1096 "-i",
1097 "--source-index",
1098 action="store_true",
1099 dest="srcsrv",
1100 default=False,
1101 help="Add source index information to debug files, making them suitable"
1102 + " for use in a source server.",
1103 )
1104 parser.add_option(
1105 "--install-manifest",
1106 action="append",
1107 dest="install_manifests",
1108 default=[],
1109 help="""Use this install manifest to map filenames back
1110 to canonical locations in the source repository. Specify
1111 <install manifest filename>,<install destination> as a comma-separated pair.""",
1112 )
1113 parser.add_option(
1114 "--count-ctors",
1115 action="store_true",
1116 dest="count_ctors",
1117 default=False,
1118 help="Count static initializers",
1119 )
1120 (options, args) = parser.parse_args()
1121
1122 # check to see if the pdbstr.exe exists
1123 if options.srcsrv:
1124 if "PDBSTR" not in buildconfig.substs:
1125 print("pdbstr was not found by configure.\n", file=sys.stderr)
1126 sys.exit(1)
1127
1128 if len(args) < 3:
1129 parser.error("not enough arguments")
1130 sys.exit(1)
1131
1132 try:
1133 manifests = validate_install_manifests(options.install_manifests)
1134 except (OSError, ValueError) as e:
1135 parser.error(str(e))
1136 sys.exit(1)
1137 file_mapping = make_file_mapping(manifests)
1138 _, bucket = get_s3_region_and_bucket()
1139 dumper = GetPlatformSpecificDumper(
1140 dump_syms=args[0],
1141 symbol_path=args[1],
1142 copy_debug=options.copy_debug,
1143 archs=options.archs,
1144 srcdirs=options.srcdir,
1145 vcsinfo=options.vcsinfo,
1146 srcsrv=options.srcsrv,
1147 s3_bucket=bucket,
1148 file_mapping=file_mapping,
1149 )
1150
1151 dumper.Process(args[2], options.count_ctors)
1152
1153
1154 # run main if run directly
1155 if __name__ == "__main__":
1156 main()