1 //===-- SymbolVendorMacOSX.cpp --------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "SymbolVendorMacOSX.h"
10 
11 #include <cstring>
12 
13 #include "Plugins/ObjectFile/Mach-O/ObjectFileMachO.h"
14 #include "lldb/Core/Module.h"
15 #include "lldb/Core/ModuleSpec.h"
16 #include "lldb/Core/PluginManager.h"
17 #include "lldb/Core/Section.h"
18 #include "lldb/Host/Host.h"
19 #include "lldb/Host/XML.h"
20 #include "lldb/Symbol/LocateSymbolFile.h"
21 #include "lldb/Symbol/ObjectFile.h"
22 #include "lldb/Target/Target.h"
23 #include "lldb/Utility/ReproducerProvider.h"
24 #include "lldb/Utility/StreamString.h"
25 #include "lldb/Utility/Timer.h"
26 
27 using namespace lldb;
28 using namespace lldb_private;
29 
30 LLDB_PLUGIN_DEFINE(SymbolVendorMacOSX)
31 
32 // SymbolVendorMacOSX constructor
33 SymbolVendorMacOSX::SymbolVendorMacOSX(const lldb::ModuleSP &module_sp)
34     : SymbolVendor(module_sp) {}
35 
36 static bool UUIDsMatch(Module *module, ObjectFile *ofile,
37                        lldb_private::Stream *feedback_strm) {
38   if (module && ofile) {
39     // Make sure the UUIDs match
40     lldb_private::UUID dsym_uuid = ofile->GetUUID();
41     if (!dsym_uuid) {
42       if (feedback_strm) {
43         feedback_strm->PutCString(
44             "warning: failed to get the uuid for object file: '");
45         ofile->GetFileSpec().Dump(feedback_strm->AsRawOstream());
46         feedback_strm->PutCString("\n");
47       }
48       return false;
49     }
50 
51     if (dsym_uuid == module->GetUUID())
52       return true;
53 
54     // Emit some warning messages since the UUIDs do not match!
55     if (feedback_strm) {
56       feedback_strm->PutCString(
57           "warning: UUID mismatch detected between modules:\n    ");
58       module->GetUUID().Dump(feedback_strm);
59       feedback_strm->PutChar(' ');
60       module->GetFileSpec().Dump(feedback_strm->AsRawOstream());
61       feedback_strm->PutCString("\n    ");
62       dsym_uuid.Dump(feedback_strm);
63       feedback_strm->PutChar(' ');
64       ofile->GetFileSpec().Dump(feedback_strm->AsRawOstream());
65       feedback_strm->EOL();
66     }
67   }
68   return false;
69 }
70 
71 void SymbolVendorMacOSX::Initialize() {
72   PluginManager::RegisterPlugin(GetPluginNameStatic(),
73                                 GetPluginDescriptionStatic(), CreateInstance);
74 }
75 
76 void SymbolVendorMacOSX::Terminate() {
77   PluginManager::UnregisterPlugin(CreateInstance);
78 }
79 
80 llvm::StringRef SymbolVendorMacOSX::GetPluginDescriptionStatic() {
81   return "Symbol vendor for MacOSX that looks for dSYM files that match "
82          "executables.";
83 }
84 
85 // CreateInstance
86 //
87 // Platforms can register a callback to use when creating symbol vendors to
88 // allow for complex debug information file setups, and to also allow for
89 // finding separate debug information files.
90 SymbolVendor *
91 SymbolVendorMacOSX::CreateInstance(const lldb::ModuleSP &module_sp,
92                                    lldb_private::Stream *feedback_strm) {
93   if (!module_sp)
94     return NULL;
95 
96   ObjectFile *obj_file =
97       llvm::dyn_cast_or_null<ObjectFileMachO>(module_sp->GetObjectFile());
98   if (!obj_file)
99     return NULL;
100 
101   static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
102   Timer scoped_timer(func_cat,
103                      "SymbolVendorMacOSX::CreateInstance (module = %s)",
104                      module_sp->GetFileSpec().GetPath().c_str());
105   SymbolVendorMacOSX *symbol_vendor = new SymbolVendorMacOSX(module_sp);
106   if (symbol_vendor) {
107     char path[PATH_MAX];
108     path[0] = '\0';
109 
110     // Try and locate the dSYM file on Mac OS X
111     static Timer::Category func_cat2(
112         "SymbolVendorMacOSX::CreateInstance() locate dSYM");
113     Timer scoped_timer2(
114         func_cat2,
115         "SymbolVendorMacOSX::CreateInstance (module = %s) locate dSYM",
116         module_sp->GetFileSpec().GetPath().c_str());
117 
118     // First check to see if the module has a symbol file in mind already. If
119     // it does, then we MUST use that.
120     FileSpec dsym_fspec(module_sp->GetSymbolFileFileSpec());
121 
122     ObjectFileSP dsym_objfile_sp;
123     if (!dsym_fspec) {
124       // No symbol file was specified in the module, lets try and find one
125       // ourselves.
126       FileSpec file_spec = obj_file->GetFileSpec();
127       if (!file_spec)
128         file_spec = module_sp->GetFileSpec();
129 
130       ModuleSpec module_spec(file_spec, module_sp->GetArchitecture());
131       module_spec.GetUUID() = module_sp->GetUUID();
132       FileSpecList search_paths = Target::GetDefaultDebugFileSearchPaths();
133       dsym_fspec =
134           Symbols::LocateExecutableSymbolFile(module_spec, search_paths);
135       if (module_spec.GetSourceMappingList().GetSize())
136         module_sp->GetSourceMappingList().Append(
137             module_spec.GetSourceMappingList(), true);
138     }
139 
140     if (dsym_fspec) {
141       // Compute dSYM root.
142       std::string dsym_root = dsym_fspec.GetPath();
143       const size_t pos = dsym_root.find("/Contents/Resources/");
144       dsym_root = pos != std::string::npos ? dsym_root.substr(0, pos) : "";
145 
146       DataBufferSP dsym_file_data_sp;
147       lldb::offset_t dsym_file_data_offset = 0;
148       dsym_objfile_sp =
149           ObjectFile::FindPlugin(module_sp, &dsym_fspec, 0,
150                                  FileSystem::Instance().GetByteSize(dsym_fspec),
151                                  dsym_file_data_sp, dsym_file_data_offset);
152       if (UUIDsMatch(module_sp.get(), dsym_objfile_sp.get(), feedback_strm)) {
153         // We need a XML parser if we hope to parse a plist...
154         if (XMLDocument::XMLEnabled()) {
155           if (module_sp->GetSourceMappingList().IsEmpty()) {
156             lldb_private::UUID dsym_uuid = dsym_objfile_sp->GetUUID();
157             if (dsym_uuid) {
158               std::string uuid_str = dsym_uuid.GetAsString();
159               if (!uuid_str.empty() && !dsym_root.empty()) {
160                 char dsym_uuid_plist_path[PATH_MAX];
161                 snprintf(dsym_uuid_plist_path, sizeof(dsym_uuid_plist_path),
162                          "%s/Contents/Resources/%s.plist", dsym_root.c_str(),
163                          uuid_str.c_str());
164                 FileSpec dsym_uuid_plist_spec(dsym_uuid_plist_path);
165                 if (FileSystem::Instance().Exists(dsym_uuid_plist_spec)) {
166                   ApplePropertyList plist(dsym_uuid_plist_path);
167                   if (plist) {
168                     std::string DBGBuildSourcePath;
169                     std::string DBGSourcePath;
170 
171                     // DBGSourcePathRemapping is a dictionary in the plist
172                     // with keys which are DBGBuildSourcePath file paths and
173                     // values which are DBGSourcePath file paths
174 
175                     StructuredData::ObjectSP plist_sp =
176                         plist.GetStructuredData();
177                     if (plist_sp.get() && plist_sp->GetAsDictionary() &&
178                         plist_sp->GetAsDictionary()->HasKey(
179                             "DBGSourcePathRemapping") &&
180                         plist_sp->GetAsDictionary()
181                             ->GetValueForKey("DBGSourcePathRemapping")
182                             ->GetAsDictionary()) {
183 
184                       // If DBGVersion 1 or DBGVersion missing, ignore
185                       // DBGSourcePathRemapping. If DBGVersion 2, strip last two
186                       // components of path remappings from
187                       //                  entries to fix an issue with a
188                       //                  specific set of DBGSourcePathRemapping
189                       //                  entries that lldb worked with.
190                       // If DBGVersion 3, trust & use the source path remappings
191                       // as-is.
192                       //
193 
194                       bool new_style_source_remapping_dictionary = false;
195                       bool do_truncate_remapping_names = false;
196                       std::string original_DBGSourcePath_value = DBGSourcePath;
197                       if (plist_sp->GetAsDictionary()->HasKey("DBGVersion")) {
198                         std::string version_string =
199                             std::string(plist_sp->GetAsDictionary()
200                                             ->GetValueForKey("DBGVersion")
201                                             ->GetStringValue(""));
202                         if (!version_string.empty() &&
203                             isdigit(version_string[0])) {
204                           int version_number = atoi(version_string.c_str());
205                           if (version_number > 1) {
206                             new_style_source_remapping_dictionary = true;
207                           }
208                           if (version_number == 2) {
209                             do_truncate_remapping_names = true;
210                           }
211                         }
212                       }
213 
214                       StructuredData::Dictionary *remappings_dict =
215                           plist_sp->GetAsDictionary()
216                               ->GetValueForKey("DBGSourcePathRemapping")
217                               ->GetAsDictionary();
218                       remappings_dict->ForEach(
219                           [&module_sp, new_style_source_remapping_dictionary,
220                            original_DBGSourcePath_value,
221                            do_truncate_remapping_names](
222                               ConstString key,
223                               StructuredData::Object *object) -> bool {
224                             if (object && object->GetAsString()) {
225 
226                               // key is DBGBuildSourcePath
227                               // object is DBGSourcePath
228                               std::string DBGSourcePath =
229                                   std::string(object->GetStringValue());
230                               if (!new_style_source_remapping_dictionary &&
231                                   !original_DBGSourcePath_value.empty()) {
232                                 DBGSourcePath = original_DBGSourcePath_value;
233                               }
234                               if (DBGSourcePath[0] == '~') {
235                                 FileSpec resolved_source_path(
236                                     DBGSourcePath.c_str());
237                                 FileSystem::Instance().Resolve(
238                                     resolved_source_path);
239                                 DBGSourcePath = resolved_source_path.GetPath();
240                               }
241                               module_sp->GetSourceMappingList().Append(
242                                   key.GetStringRef(), DBGSourcePath, true);
243                               // With version 2 of DBGSourcePathRemapping, we
244                               // can chop off the last two filename parts
245                               // from the source remapping and get a more
246                               // general source remapping that still works.
247                               // Add this as another option in addition to
248                               // the full source path remap.
249                               if (do_truncate_remapping_names) {
250                                 FileSpec build_path(key.AsCString());
251                                 FileSpec source_path(DBGSourcePath.c_str());
252                                 build_path.RemoveLastPathComponent();
253                                 build_path.RemoveLastPathComponent();
254                                 source_path.RemoveLastPathComponent();
255                                 source_path.RemoveLastPathComponent();
256                                 module_sp->GetSourceMappingList().Append(
257                                     build_path.GetPath(), source_path.GetPath(),
258                                     true);
259                               }
260                             }
261                             return true;
262                           });
263                     }
264 
265                     // If we have a DBGBuildSourcePath + DBGSourcePath pair,
266                     // append those to the source path remappings.
267 
268                     plist.GetValueAsString("DBGBuildSourcePath",
269                                            DBGBuildSourcePath);
270                     plist.GetValueAsString("DBGSourcePath", DBGSourcePath);
271                     if (!DBGBuildSourcePath.empty() && !DBGSourcePath.empty()) {
272                       if (DBGSourcePath[0] == '~') {
273                         FileSpec resolved_source_path(DBGSourcePath.c_str());
274                         FileSystem::Instance().Resolve(resolved_source_path);
275                         DBGSourcePath = resolved_source_path.GetPath();
276                       }
277                       module_sp->GetSourceMappingList().Append(
278                           DBGBuildSourcePath, DBGSourcePath, true);
279                     }
280                   }
281                 }
282               }
283             }
284           }
285         }
286 
287         symbol_vendor->AddSymbolFileRepresentation(dsym_objfile_sp);
288         if (!dsym_root.empty()) {
289           if (repro::Generator *g =
290                   repro::Reproducer::Instance().GetGenerator()) {
291             repro::FileProvider &fp = g->GetOrCreate<repro::FileProvider>();
292             fp.RecordInterestingDirectoryRecursive(dsym_root);
293           }
294         }
295         return symbol_vendor;
296       }
297     }
298 
299     // Just create our symbol vendor using the current objfile as this is
300     // either an executable with no dSYM (that we could locate), an executable
301     // with a dSYM that has a UUID that doesn't match.
302     symbol_vendor->AddSymbolFileRepresentation(obj_file->shared_from_this());
303   }
304   return symbol_vendor;
305 }
306