]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lldb/source/Host/common/Symbols.cpp
Merge llvm, clang, compiler-rt, libc++, libunwind, lld, lldb and openmp
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lldb / source / Host / common / Symbols.cpp
1 //===-- Symbols.cpp ---------------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "lldb/Host/Symbols.h"
11 #include "lldb/Core/ModuleSpec.h"
12 #include "lldb/Host/FileSystem.h"
13 #include "lldb/Symbol/ObjectFile.h"
14 #include "lldb/Target/Target.h"
15 #include "lldb/Utility/ArchSpec.h"
16 #include "lldb/Utility/DataBuffer.h"
17 #include "lldb/Utility/DataExtractor.h"
18 #include "lldb/Utility/Log.h"
19 #include "lldb/Utility/StreamString.h"
20 #include "lldb/Utility/Timer.h"
21 #include "lldb/Utility/UUID.h"
22
23 #include "llvm/Support/FileSystem.h"
24
25 // From MacOSX system header "mach/machine.h"
26 typedef int cpu_type_t;
27 typedef int cpu_subtype_t;
28
29 using namespace lldb;
30 using namespace lldb_private;
31
32 #if defined(__APPLE__)
33
34 // Forward declaration of method defined in source/Host/macosx/Symbols.cpp
35 int LocateMacOSXFilesUsingDebugSymbols(const ModuleSpec &module_spec,
36                                        ModuleSpec &return_module_spec);
37
38 #else
39
40 int LocateMacOSXFilesUsingDebugSymbols(const ModuleSpec &module_spec,
41                                        ModuleSpec &return_module_spec) {
42   // Cannot find MacOSX files using debug symbols on non MacOSX.
43   return 0;
44 }
45
46 #endif
47
48 static bool FileAtPathContainsArchAndUUID(const FileSpec &file_fspec,
49                                           const ArchSpec *arch,
50                                           const lldb_private::UUID *uuid) {
51   ModuleSpecList module_specs;
52   if (ObjectFile::GetModuleSpecifications(file_fspec, 0, 0, module_specs)) {
53     ModuleSpec spec;
54     for (size_t i = 0; i < module_specs.GetSize(); ++i) {
55       bool got_spec = module_specs.GetModuleSpecAtIndex(i, spec);
56       UNUSED_IF_ASSERT_DISABLED(got_spec);
57       assert(got_spec);
58       if ((uuid == NULL || (spec.GetUUIDPtr() && spec.GetUUID() == *uuid)) &&
59           (arch == NULL || (spec.GetArchitecturePtr() &&
60                             spec.GetArchitecture().IsCompatibleMatch(*arch)))) {
61         return true;
62       }
63     }
64   }
65   return false;
66 }
67
68 // Given a binary exec_fspec, and a ModuleSpec with an architecture/uuid,
69 // return true if there is a matching dSYM bundle next to the exec_fspec,
70 // and return that value in dsym_fspec.  
71 // If there is a .dSYM.yaa compressed archive next to the exec_fspec, 
72 // call through Symbols::DownloadObjectAndSymbolFile to download the
73 // expanded/uncompressed dSYM and return that filepath in dsym_fspec.
74
75 static bool LookForDsymNextToExecutablePath(const ModuleSpec &mod_spec,
76                                             const FileSpec &exec_fspec,
77                                             FileSpec &dsym_fspec) {
78   ConstString filename = exec_fspec.GetFilename();
79   FileSpec dsym_directory = exec_fspec;
80   dsym_directory.RemoveLastPathComponent();
81
82   std::string dsym_filename = filename.AsCString();
83   dsym_filename += ".dSYM";
84   dsym_directory.AppendPathComponent(dsym_filename);
85   dsym_directory.AppendPathComponent("Contents");
86   dsym_directory.AppendPathComponent("Resources");
87   dsym_directory.AppendPathComponent("DWARF");
88
89   if (FileSystem::Instance().Exists(dsym_directory)) {
90
91     // See if the binary name exists in the dSYM DWARF
92     // subdir.
93     dsym_fspec = dsym_directory;
94     dsym_fspec.AppendPathComponent(filename.AsCString());
95     if (FileSystem::Instance().Exists(dsym_fspec) &&
96         FileAtPathContainsArchAndUUID(dsym_fspec, mod_spec.GetArchitecturePtr(),
97                                       mod_spec.GetUUIDPtr())) {
98       return true;
99     }
100
101     // See if we have "../CF.framework" - so we'll look for
102     // CF.framework.dSYM/Contents/Resources/DWARF/CF
103     // We need to drop the last suffix after '.' to match 
104     // 'CF' in the DWARF subdir.
105     std::string binary_name (filename.AsCString());
106     auto last_dot = binary_name.find_last_of('.');
107     if (last_dot != std::string::npos) {
108       binary_name.erase(last_dot);
109       dsym_fspec = dsym_directory;
110       dsym_fspec.AppendPathComponent(binary_name);
111       if (FileSystem::Instance().Exists(dsym_fspec) &&
112           FileAtPathContainsArchAndUUID(dsym_fspec,
113                                         mod_spec.GetArchitecturePtr(),
114                                         mod_spec.GetUUIDPtr())) {
115         return true;
116       }
117     }
118   }
119
120   // See if we have a .dSYM.yaa next to this executable path.
121   FileSpec dsym_yaa_fspec = exec_fspec;
122   dsym_yaa_fspec.RemoveLastPathComponent();
123   std::string dsym_yaa_filename = filename.AsCString();
124   dsym_yaa_filename += ".dSYM.yaa";
125   dsym_yaa_fspec.AppendPathComponent(dsym_yaa_filename);
126
127   if (FileSystem::Instance().Exists(dsym_yaa_fspec)) {
128     ModuleSpec mutable_mod_spec = mod_spec;
129     if (Symbols::DownloadObjectAndSymbolFile(mutable_mod_spec, true) &&
130         FileSystem::Instance().Exists(mutable_mod_spec.GetSymbolFileSpec())) {
131       dsym_fspec = mutable_mod_spec.GetSymbolFileSpec();
132       return true;
133     }
134   }
135
136   return false;
137 }
138
139 // Given a ModuleSpec with a FileSpec and optionally uuid/architecture
140 // filled in, look for a .dSYM bundle next to that binary.  Returns true
141 // if a .dSYM bundle is found, and that path is returned in the dsym_fspec
142 // FileSpec.
143 //
144 // This routine looks a few directory layers above the given exec_path -
145 // exec_path might be /System/Library/Frameworks/CF.framework/CF and the
146 // dSYM might be /System/Library/Frameworks/CF.framework.dSYM.
147 //
148 // If there is a .dSYM.yaa compressed archive found next to the binary,
149 // we'll call DownloadObjectAndSymbolFile to expand it into a plain .dSYM
150
151 static bool LocateDSYMInVincinityOfExecutable(const ModuleSpec &module_spec,
152                                               FileSpec &dsym_fspec) {
153   Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
154   const FileSpec &exec_fspec = module_spec.GetFileSpec();
155   if (exec_fspec) {
156     if (::LookForDsymNextToExecutablePath (module_spec, exec_fspec, dsym_fspec)) {
157         if (log) {
158           log->Printf("dSYM with matching UUID & arch found at %s", dsym_fspec.GetPath().c_str());
159         }
160         return true;
161     } else {
162       FileSpec parent_dirs = exec_fspec;
163
164       // Remove the binary name from the FileSpec
165       parent_dirs.RemoveLastPathComponent();
166
167       // Add a ".dSYM" name to each directory component of the path,
168       // stripping off components.  e.g. we may have a binary like
169       // /S/L/F/Foundation.framework/Versions/A/Foundation and
170       // /S/L/F/Foundation.framework.dSYM
171       //
172       // so we'll need to start with
173       // /S/L/F/Foundation.framework/Versions/A, add the .dSYM part to the
174       // "A", and if that doesn't exist, strip off the "A" and try it again
175       // with "Versions", etc., until we find a dSYM bundle or we've
176       // stripped off enough path components that there's no need to
177       // continue.
178
179       for (int i = 0; i < 4; i++) {
180         // Does this part of the path have a "." character - could it be a
181         // bundle's top level directory?
182         const char *fn = parent_dirs.GetFilename().AsCString();
183         if (fn == nullptr)
184           break;
185         if (::strchr(fn, '.') != nullptr) {
186           if (::LookForDsymNextToExecutablePath (module_spec, parent_dirs, dsym_fspec)) {
187             if (log) {
188               log->Printf("dSYM with matching UUID & arch found at %s",
189                           dsym_fspec.GetPath().c_str());
190             }
191             return true;
192           }
193         }
194         parent_dirs.RemoveLastPathComponent();
195       }
196     }
197   }
198   dsym_fspec.Clear();
199   return false;
200 }
201
202 static FileSpec LocateExecutableSymbolFileDsym(const ModuleSpec &module_spec) {
203   const FileSpec *exec_fspec = module_spec.GetFileSpecPtr();
204   const ArchSpec *arch = module_spec.GetArchitecturePtr();
205   const UUID *uuid = module_spec.GetUUIDPtr();
206
207   static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
208   Timer scoped_timer(
209       func_cat,
210       "LocateExecutableSymbolFileDsym (file = %s, arch = %s, uuid = %p)",
211       exec_fspec ? exec_fspec->GetFilename().AsCString("<NULL>") : "<NULL>",
212       arch ? arch->GetArchitectureName() : "<NULL>", (const void *)uuid);
213
214   FileSpec symbol_fspec;
215   ModuleSpec dsym_module_spec;
216   // First try and find the dSYM in the same directory as the executable or in
217   // an appropriate parent directory
218   if (!LocateDSYMInVincinityOfExecutable(module_spec, symbol_fspec)) {
219     // We failed to easily find the dSYM above, so use DebugSymbols
220     LocateMacOSXFilesUsingDebugSymbols(module_spec, dsym_module_spec);
221   } else {
222     dsym_module_spec.GetSymbolFileSpec() = symbol_fspec;
223   }
224   return dsym_module_spec.GetSymbolFileSpec();
225 }
226
227 ModuleSpec Symbols::LocateExecutableObjectFile(const ModuleSpec &module_spec) {
228   ModuleSpec result;
229   const FileSpec *exec_fspec = module_spec.GetFileSpecPtr();
230   const ArchSpec *arch = module_spec.GetArchitecturePtr();
231   const UUID *uuid = module_spec.GetUUIDPtr();
232   static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
233   Timer scoped_timer(
234       func_cat, "LocateExecutableObjectFile (file = %s, arch = %s, uuid = %p)",
235       exec_fspec ? exec_fspec->GetFilename().AsCString("<NULL>") : "<NULL>",
236       arch ? arch->GetArchitectureName() : "<NULL>", (const void *)uuid);
237
238   ModuleSpecList module_specs;
239   ModuleSpec matched_module_spec;
240   if (exec_fspec &&
241       ObjectFile::GetModuleSpecifications(*exec_fspec, 0, 0, module_specs) &&
242       module_specs.FindMatchingModuleSpec(module_spec, matched_module_spec)) {
243     result.GetFileSpec() = exec_fspec;
244   } else {
245     LocateMacOSXFilesUsingDebugSymbols(module_spec, result);
246   }
247   return result;
248 }
249
250 // Keep "symbols.enable-external-lookup" description in sync with this function.
251
252 FileSpec Symbols::LocateExecutableSymbolFile(const ModuleSpec &module_spec) {
253   FileSpec symbol_file_spec = module_spec.GetSymbolFileSpec();
254   if (symbol_file_spec.IsAbsolute() &&
255       FileSystem::Instance().Exists(symbol_file_spec))
256     return symbol_file_spec;
257
258   const char *symbol_filename = symbol_file_spec.GetFilename().AsCString();
259   if (symbol_filename && symbol_filename[0]) {
260     FileSpecList debug_file_search_paths(
261         Target::GetDefaultDebugFileSearchPaths());
262
263     // Add module directory.
264     FileSpec module_file_spec = module_spec.GetFileSpec();
265     // We keep the unresolved pathname if it fails.
266     FileSystem::Instance().ResolveSymbolicLink(module_file_spec, module_file_spec);
267
268     const ConstString &file_dir = module_file_spec.GetDirectory();
269     {
270       FileSpec file_spec(file_dir.AsCString("."));
271       FileSystem::Instance().Resolve(file_spec);
272       debug_file_search_paths.AppendIfUnique(file_spec);
273     }
274
275     if (ModuleList::GetGlobalModuleListProperties().GetEnableExternalLookup()) {
276
277       // Add current working directory.
278       {
279         FileSpec file_spec(".");
280         FileSystem::Instance().Resolve(file_spec);
281         debug_file_search_paths.AppendIfUnique(file_spec);
282       }
283
284 #ifndef _WIN32
285 #if defined(__NetBSD__)
286       // Add /usr/libdata/debug directory.
287       {
288         FileSpec file_spec("/usr/libdata/debug");
289         FileSystem::Instance().Resolve(file_spec);
290         debug_file_search_paths.AppendIfUnique(file_spec);
291       }
292 #else
293       // Add /usr/lib/debug directory.
294       {
295         FileSpec file_spec("/usr/lib/debug");
296         FileSystem::Instance().Resolve(file_spec);
297         debug_file_search_paths.AppendIfUnique(file_spec);
298       }
299 #endif
300 #endif // _WIN32
301     }
302
303     std::string uuid_str;
304     const UUID &module_uuid = module_spec.GetUUID();
305     if (module_uuid.IsValid()) {
306       // Some debug files are stored in the .build-id directory like this:
307       //   /usr/lib/debug/.build-id/ff/e7fe727889ad82bb153de2ad065b2189693315.debug
308       uuid_str = module_uuid.GetAsString("");
309       std::transform(uuid_str.begin(), uuid_str.end(), uuid_str.begin(),
310           ::tolower);
311       uuid_str.insert(2, 1, '/');
312       uuid_str = uuid_str + ".debug";
313     }
314
315     size_t num_directories = debug_file_search_paths.GetSize();
316     for (size_t idx = 0; idx < num_directories; ++idx) {
317       FileSpec dirspec = debug_file_search_paths.GetFileSpecAtIndex(idx);
318       FileSystem::Instance().Resolve(dirspec);
319       if (!FileSystem::Instance().IsDirectory(dirspec))
320         continue;
321
322       std::vector<std::string> files;
323       std::string dirname = dirspec.GetPath();
324
325       files.push_back(dirname + "/" + symbol_filename);
326       files.push_back(dirname + "/.debug/" + symbol_filename);
327       files.push_back(dirname + "/.build-id/" + uuid_str);
328
329       // Some debug files may stored in the module directory like this:
330       //   /usr/lib/debug/usr/lib/library.so.debug
331       if (!file_dir.IsEmpty())
332         files.push_back(dirname + file_dir.AsCString() + "/" + symbol_filename);
333
334       const uint32_t num_files = files.size();
335       for (size_t idx_file = 0; idx_file < num_files; ++idx_file) {
336         const std::string &filename = files[idx_file];
337         FileSpec file_spec(filename);
338         FileSystem::Instance().Resolve(file_spec);
339
340         if (llvm::sys::fs::equivalent(file_spec.GetPath(),
341                                       module_file_spec.GetPath()))
342           continue;
343
344         if (FileSystem::Instance().Exists(file_spec)) {
345           lldb_private::ModuleSpecList specs;
346           const size_t num_specs =
347               ObjectFile::GetModuleSpecifications(file_spec, 0, 0, specs);
348           assert(num_specs <= 1 &&
349                  "Symbol Vendor supports only a single architecture");
350           if (num_specs == 1) {
351             ModuleSpec mspec;
352             if (specs.GetModuleSpecAtIndex(0, mspec)) {
353               // Skip the uuids check if module_uuid is invalid. For example,
354               // this happens for *.dwp files since at the moment llvm-dwp
355               // doesn't output build ids, nor does binutils dwp.
356               if (!module_uuid.IsValid() || module_uuid == mspec.GetUUID())
357                 return file_spec;
358             }
359           }
360         }
361       }
362     }
363   }
364
365   return LocateExecutableSymbolFileDsym(module_spec);
366 }
367
368 #if !defined(__APPLE__)
369
370 FileSpec Symbols::FindSymbolFileInBundle(const FileSpec &symfile_bundle,
371                                          const lldb_private::UUID *uuid,
372                                          const ArchSpec *arch) {
373   // FIXME
374   return FileSpec();
375 }
376
377 bool Symbols::DownloadObjectAndSymbolFile(ModuleSpec &module_spec,
378                                           bool force_lookup) {
379   // Fill in the module_spec.GetFileSpec() for the object file and/or the
380   // module_spec.GetSymbolFileSpec() for the debug symbols file.
381   return false;
382 }
383
384 #endif