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