1 //===-- DYLDRendezvous.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 // C Includes
11 // C++ Includes
12 // Other libraries and framework includes
13 #include "lldb/Core/ArchSpec.h"
14 #include "lldb/Core/Module.h"
15 #include "lldb/Symbol/ObjectFile.h"
16 #include "lldb/Symbol/Symbol.h"
17 #include "lldb/Symbol/SymbolContext.h"
18 #include "lldb/Target/Platform.h"
19 #include "lldb/Target/Process.h"
20 #include "lldb/Target/Target.h"
21 #include "lldb/Utility/Log.h"
22 #include "lldb/Utility/Status.h"
23 
24 #include "llvm/Support/Path.h"
25 
26 #include "DYLDRendezvous.h"
27 
28 using namespace lldb;
29 using namespace lldb_private;
30 
31 /// Locates the address of the rendezvous structure.  Returns the address on
32 /// success and LLDB_INVALID_ADDRESS on failure.
33 static addr_t ResolveRendezvousAddress(Process *process) {
34   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
35   addr_t info_location;
36   addr_t info_addr;
37   Status error;
38 
39   if (!process) {
40     if (log)
41       log->Printf("%s null process provided", __FUNCTION__);
42     return LLDB_INVALID_ADDRESS;
43   }
44 
45   // Try to get it from our process.  This might be a remote process and might
46   // grab it via some remote-specific mechanism.
47   info_location = process->GetImageInfoAddress();
48   if (log)
49     log->Printf("%s info_location = 0x%" PRIx64, __FUNCTION__, info_location);
50 
51   // If the process fails to return an address, fall back to seeing if the local
52   // object file can help us find it.
53   if (info_location == LLDB_INVALID_ADDRESS) {
54     Target *target = &process->GetTarget();
55     if (target) {
56       ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
57       Address addr = obj_file->GetImageInfoAddress(target);
58 
59       if (addr.IsValid()) {
60         info_location = addr.GetLoadAddress(target);
61         if (log)
62           log->Printf(
63               "%s resolved via direct object file approach to 0x%" PRIx64,
64               __FUNCTION__, info_location);
65       } else {
66         if (log)
67           log->Printf("%s FAILED - direct object file approach did not yield a "
68                       "valid address",
69                       __FUNCTION__);
70       }
71     }
72   }
73 
74   if (info_location == LLDB_INVALID_ADDRESS) {
75     if (log)
76       log->Printf("%s FAILED - invalid info address", __FUNCTION__);
77     return LLDB_INVALID_ADDRESS;
78   }
79 
80   if (log)
81     log->Printf("%s reading pointer (%" PRIu32 " bytes) from 0x%" PRIx64,
82                 __FUNCTION__, process->GetAddressByteSize(), info_location);
83 
84   info_addr = process->ReadPointerFromMemory(info_location, error);
85   if (error.Fail()) {
86     if (log)
87       log->Printf("%s FAILED - could not read from the info location: %s",
88                   __FUNCTION__, error.AsCString());
89     return LLDB_INVALID_ADDRESS;
90   }
91 
92   if (info_addr == 0) {
93     if (log)
94       log->Printf("%s FAILED - the rendezvous address contained at 0x%" PRIx64
95                   " returned a null value",
96                   __FUNCTION__, info_location);
97     return LLDB_INVALID_ADDRESS;
98   }
99 
100   return info_addr;
101 }
102 
103 DYLDRendezvous::DYLDRendezvous(Process *process)
104     : m_process(process), m_rendezvous_addr(LLDB_INVALID_ADDRESS), m_current(),
105       m_previous(), m_loaded_modules(), m_soentries(), m_added_soentries(),
106       m_removed_soentries() {
107   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
108 
109   m_thread_info.valid = false;
110 
111   // Cache a copy of the executable path
112   if (m_process) {
113     Module *exe_mod = m_process->GetTarget().GetExecutableModulePointer();
114     if (exe_mod) {
115       m_exe_file_spec = exe_mod->GetPlatformFileSpec();
116       if (log)
117         log->Printf("DYLDRendezvous::%s exe module executable path set: '%s'",
118                     __FUNCTION__, m_exe_file_spec.GetCString());
119     } else {
120       if (log)
121         log->Printf("DYLDRendezvous::%s cannot cache exe module path: null "
122                     "executable module pointer",
123                     __FUNCTION__);
124     }
125   }
126 }
127 
128 bool DYLDRendezvous::Resolve() {
129   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
130 
131   const size_t word_size = 4;
132   Rendezvous info;
133   size_t address_size;
134   size_t padding;
135   addr_t info_addr;
136   addr_t cursor;
137 
138   address_size = m_process->GetAddressByteSize();
139   padding = address_size - word_size;
140   if (log)
141     log->Printf("DYLDRendezvous::%s address size: %" PRIu64
142                 ", padding %" PRIu64,
143                 __FUNCTION__, uint64_t(address_size), uint64_t(padding));
144 
145   if (m_rendezvous_addr == LLDB_INVALID_ADDRESS)
146     cursor = info_addr = ResolveRendezvousAddress(m_process);
147   else
148     cursor = info_addr = m_rendezvous_addr;
149   if (log)
150     log->Printf("DYLDRendezvous::%s cursor = 0x%" PRIx64, __FUNCTION__, cursor);
151 
152   if (cursor == LLDB_INVALID_ADDRESS)
153     return false;
154 
155   if (!(cursor = ReadWord(cursor, &info.version, word_size)))
156     return false;
157 
158   if (!(cursor = ReadPointer(cursor + padding, &info.map_addr)))
159     return false;
160 
161   if (!(cursor = ReadPointer(cursor, &info.brk)))
162     return false;
163 
164   if (!(cursor = ReadWord(cursor, &info.state, word_size)))
165     return false;
166 
167   if (!(cursor = ReadPointer(cursor + padding, &info.ldbase)))
168     return false;
169 
170   // The rendezvous was successfully read.  Update our internal state.
171   m_rendezvous_addr = info_addr;
172   m_previous = m_current;
173   m_current = info;
174 
175   if (UpdateSOEntries(true))
176     return true;
177 
178   return UpdateSOEntries();
179 }
180 
181 bool DYLDRendezvous::IsValid() {
182   return m_rendezvous_addr != LLDB_INVALID_ADDRESS;
183 }
184 
185 bool DYLDRendezvous::UpdateSOEntries(bool fromRemote) {
186   SOEntry entry;
187   LoadedModuleInfoList module_list;
188 
189   // If we can't get the SO info from the remote, return failure.
190   if (fromRemote && m_process->LoadModules(module_list) == 0)
191     return false;
192 
193   if (!fromRemote && m_current.map_addr == 0)
194     return false;
195 
196   // When the previous and current states are consistent this is the first
197   // time we have been asked to update.  Just take a snapshot of the currently
198   // loaded modules.
199   if (m_previous.state == eConsistent && m_current.state == eConsistent)
200     return fromRemote ? SaveSOEntriesFromRemote(module_list)
201                       : TakeSnapshot(m_soentries);
202 
203   // If we are about to add or remove a shared object clear out the current
204   // state and take a snapshot of the currently loaded images.
205   if (m_current.state == eAdd || m_current.state == eDelete) {
206     // Some versions of the android dynamic linker might send two
207     // notifications with state == eAdd back to back. Ignore them
208     // until we get an eConsistent notification.
209     if (!(m_previous.state == eConsistent ||
210           (m_previous.state == eAdd && m_current.state == eDelete)))
211       return false;
212 
213     m_soentries.clear();
214     if (fromRemote)
215       return SaveSOEntriesFromRemote(module_list);
216 
217     m_added_soentries.clear();
218     m_removed_soentries.clear();
219     return TakeSnapshot(m_soentries);
220   }
221   assert(m_current.state == eConsistent);
222 
223   // Otherwise check the previous state to determine what to expect and update
224   // accordingly.
225   if (m_previous.state == eAdd)
226     return fromRemote ? AddSOEntriesFromRemote(module_list) : AddSOEntries();
227   else if (m_previous.state == eDelete)
228     return fromRemote ? RemoveSOEntriesFromRemote(module_list)
229                       : RemoveSOEntries();
230 
231   return false;
232 }
233 
234 bool DYLDRendezvous::FillSOEntryFromModuleInfo(
235     LoadedModuleInfoList::LoadedModuleInfo const &modInfo, SOEntry &entry) {
236   addr_t link_map_addr;
237   addr_t base_addr;
238   addr_t dyn_addr;
239   std::string name;
240 
241   if (!modInfo.get_link_map(link_map_addr) || !modInfo.get_base(base_addr) ||
242       !modInfo.get_dynamic(dyn_addr) || !modInfo.get_name(name))
243     return false;
244 
245   entry.link_addr = link_map_addr;
246   entry.base_addr = base_addr;
247   entry.dyn_addr = dyn_addr;
248 
249   entry.file_spec.SetFile(name, false);
250 
251   UpdateBaseAddrIfNecessary(entry, name);
252 
253   // not needed if we're using ModuleInfos
254   entry.next = 0;
255   entry.prev = 0;
256   entry.path_addr = 0;
257 
258   return true;
259 }
260 
261 bool DYLDRendezvous::SaveSOEntriesFromRemote(
262     LoadedModuleInfoList &module_list) {
263   for (auto const &modInfo : module_list.m_list) {
264     SOEntry entry;
265     if (!FillSOEntryFromModuleInfo(modInfo, entry))
266       return false;
267 
268     // Only add shared libraries and not the executable.
269     if (!SOEntryIsMainExecutable(entry))
270       m_soentries.push_back(entry);
271   }
272 
273   m_loaded_modules = module_list;
274   return true;
275 }
276 
277 bool DYLDRendezvous::AddSOEntriesFromRemote(LoadedModuleInfoList &module_list) {
278   for (auto const &modInfo : module_list.m_list) {
279     bool found = false;
280     for (auto const &existing : m_loaded_modules.m_list) {
281       if (modInfo == existing) {
282         found = true;
283         break;
284       }
285     }
286 
287     if (found)
288       continue;
289 
290     SOEntry entry;
291     if (!FillSOEntryFromModuleInfo(modInfo, entry))
292       return false;
293 
294     // Only add shared libraries and not the executable.
295     if (!SOEntryIsMainExecutable(entry))
296       m_soentries.push_back(entry);
297   }
298 
299   m_loaded_modules = module_list;
300   return true;
301 }
302 
303 bool DYLDRendezvous::RemoveSOEntriesFromRemote(
304     LoadedModuleInfoList &module_list) {
305   for (auto const &existing : m_loaded_modules.m_list) {
306     bool found = false;
307     for (auto const &modInfo : module_list.m_list) {
308       if (modInfo == existing) {
309         found = true;
310         break;
311       }
312     }
313 
314     if (found)
315       continue;
316 
317     SOEntry entry;
318     if (!FillSOEntryFromModuleInfo(existing, entry))
319       return false;
320 
321     // Only add shared libraries and not the executable.
322     if (!SOEntryIsMainExecutable(entry)) {
323       auto pos = std::find(m_soentries.begin(), m_soentries.end(), entry);
324       if (pos == m_soentries.end())
325         return false;
326 
327       m_soentries.erase(pos);
328     }
329   }
330 
331   m_loaded_modules = module_list;
332   return true;
333 }
334 
335 bool DYLDRendezvous::AddSOEntries() {
336   SOEntry entry;
337   iterator pos;
338 
339   assert(m_previous.state == eAdd);
340 
341   if (m_current.map_addr == 0)
342     return false;
343 
344   for (addr_t cursor = m_current.map_addr; cursor != 0; cursor = entry.next) {
345     if (!ReadSOEntryFromMemory(cursor, entry))
346       return false;
347 
348     // Only add shared libraries and not the executable.
349     if (SOEntryIsMainExecutable(entry))
350       continue;
351 
352     pos = std::find(m_soentries.begin(), m_soentries.end(), entry);
353     if (pos == m_soentries.end()) {
354       m_soentries.push_back(entry);
355       m_added_soentries.push_back(entry);
356     }
357   }
358 
359   return true;
360 }
361 
362 bool DYLDRendezvous::RemoveSOEntries() {
363   SOEntryList entry_list;
364   iterator pos;
365 
366   assert(m_previous.state == eDelete);
367 
368   if (!TakeSnapshot(entry_list))
369     return false;
370 
371   for (iterator I = begin(); I != end(); ++I) {
372     pos = std::find(entry_list.begin(), entry_list.end(), *I);
373     if (pos == entry_list.end())
374       m_removed_soentries.push_back(*I);
375   }
376 
377   m_soentries = entry_list;
378   return true;
379 }
380 
381 bool DYLDRendezvous::SOEntryIsMainExecutable(const SOEntry &entry) {
382   // On some systes the executable is indicated by an empty path in the entry.
383   // On others it is the full path to the executable.
384 
385   auto triple = m_process->GetTarget().GetArchitecture().GetTriple();
386   switch (triple.getOS()) {
387   case llvm::Triple::FreeBSD:
388   case llvm::Triple::NetBSD:
389     return entry.file_spec == m_exe_file_spec;
390   case llvm::Triple::Linux:
391     if (triple.isAndroid())
392       return entry.file_spec == m_exe_file_spec;
393     return !entry.file_spec;
394   default:
395     return false;
396   }
397 }
398 
399 bool DYLDRendezvous::TakeSnapshot(SOEntryList &entry_list) {
400   SOEntry entry;
401 
402   if (m_current.map_addr == 0)
403     return false;
404 
405   // Clear previous entries since we are about to obtain an up to date list.
406   entry_list.clear();
407 
408   for (addr_t cursor = m_current.map_addr; cursor != 0; cursor = entry.next) {
409     if (!ReadSOEntryFromMemory(cursor, entry))
410       return false;
411 
412     // Only add shared libraries and not the executable.
413     if (SOEntryIsMainExecutable(entry))
414       continue;
415 
416     entry_list.push_back(entry);
417   }
418 
419   return true;
420 }
421 
422 addr_t DYLDRendezvous::ReadWord(addr_t addr, uint64_t *dst, size_t size) {
423   Status error;
424 
425   *dst = m_process->ReadUnsignedIntegerFromMemory(addr, size, 0, error);
426   if (error.Fail())
427     return 0;
428 
429   return addr + size;
430 }
431 
432 addr_t DYLDRendezvous::ReadPointer(addr_t addr, addr_t *dst) {
433   Status error;
434 
435   *dst = m_process->ReadPointerFromMemory(addr, error);
436   if (error.Fail())
437     return 0;
438 
439   return addr + m_process->GetAddressByteSize();
440 }
441 
442 std::string DYLDRendezvous::ReadStringFromMemory(addr_t addr) {
443   std::string str;
444   Status error;
445 
446   if (addr == LLDB_INVALID_ADDRESS)
447     return std::string();
448 
449   m_process->ReadCStringFromMemory(addr, str, error);
450 
451   return str;
452 }
453 
454 // Returns true if the load bias reported by the linker is incorrect for the
455 // given entry. This
456 // function is used to handle cases where we want to work around a bug in the
457 // system linker.
458 static bool isLoadBiasIncorrect(Target &target, const std::string &file_path) {
459   // On Android L (API 21, 22) the load address of the "/system/bin/linker"
460   // isn't filled in
461   // correctly.
462   uint32_t os_major = 0, os_minor = 0, os_update = 0;
463   if (target.GetArchitecture().GetTriple().isAndroid() &&
464       target.GetPlatform()->GetOSVersion(os_major, os_minor, os_update) &&
465       (os_major == 21 || os_major == 22) &&
466       (file_path == "/system/bin/linker" ||
467        file_path == "/system/bin/linker64")) {
468     return true;
469   }
470 
471   return false;
472 }
473 
474 void DYLDRendezvous::UpdateBaseAddrIfNecessary(SOEntry &entry,
475                                                std::string const &file_path) {
476   // If the load bias reported by the linker is incorrect then fetch the load
477   // address of the file
478   // from the proc file system.
479   if (isLoadBiasIncorrect(m_process->GetTarget(), file_path)) {
480     lldb::addr_t load_addr = LLDB_INVALID_ADDRESS;
481     bool is_loaded = false;
482     Status error =
483         m_process->GetFileLoadAddress(entry.file_spec, is_loaded, load_addr);
484     if (error.Success() && is_loaded)
485       entry.base_addr = load_addr;
486   }
487 }
488 
489 bool DYLDRendezvous::ReadSOEntryFromMemory(lldb::addr_t addr, SOEntry &entry) {
490   entry.clear();
491 
492   entry.link_addr = addr;
493 
494   if (!(addr = ReadPointer(addr, &entry.base_addr)))
495     return false;
496 
497   // mips adds an extra load offset field to the link map struct on
498   // FreeBSD and NetBSD (need to validate other OSes).
499   // http://svnweb.freebsd.org/base/head/sys/sys/link_elf.h?revision=217153&view=markup#l57
500   const ArchSpec &arch = m_process->GetTarget().GetArchitecture();
501   if ((arch.GetTriple().getOS() == llvm::Triple::FreeBSD ||
502        arch.GetTriple().getOS() == llvm::Triple::NetBSD) &&
503       (arch.GetMachine() == llvm::Triple::mips ||
504        arch.GetMachine() == llvm::Triple::mipsel ||
505        arch.GetMachine() == llvm::Triple::mips64 ||
506        arch.GetMachine() == llvm::Triple::mips64el)) {
507     addr_t mips_l_offs;
508     if (!(addr = ReadPointer(addr, &mips_l_offs)))
509       return false;
510     if (mips_l_offs != 0 && mips_l_offs != entry.base_addr)
511       return false;
512   }
513 
514   if (!(addr = ReadPointer(addr, &entry.path_addr)))
515     return false;
516 
517   if (!(addr = ReadPointer(addr, &entry.dyn_addr)))
518     return false;
519 
520   if (!(addr = ReadPointer(addr, &entry.next)))
521     return false;
522 
523   if (!(addr = ReadPointer(addr, &entry.prev)))
524     return false;
525 
526   std::string file_path = ReadStringFromMemory(entry.path_addr);
527   entry.file_spec.SetFile(file_path, false);
528 
529   UpdateBaseAddrIfNecessary(entry, file_path);
530 
531   return true;
532 }
533 
534 bool DYLDRendezvous::FindMetadata(const char *name, PThreadField field,
535                                   uint32_t &value) {
536   Target &target = m_process->GetTarget();
537 
538   SymbolContextList list;
539   if (!target.GetImages().FindSymbolsWithNameAndType(ConstString(name),
540                                                      eSymbolTypeAny, list))
541     return false;
542 
543   Address address = list[0].symbol->GetAddress();
544   addr_t addr = address.GetLoadAddress(&target);
545   if (addr == LLDB_INVALID_ADDRESS)
546     return false;
547 
548   Status error;
549   value = (uint32_t)m_process->ReadUnsignedIntegerFromMemory(
550       addr + field * sizeof(uint32_t), sizeof(uint32_t), 0, error);
551   if (error.Fail())
552     return false;
553 
554   if (field == eSize)
555     value /= 8; // convert bits to bytes
556 
557   return true;
558 }
559 
560 const DYLDRendezvous::ThreadInfo &DYLDRendezvous::GetThreadInfo() {
561   if (!m_thread_info.valid) {
562     bool ok = true;
563 
564     ok &= FindMetadata("_thread_db_pthread_dtvp", eOffset,
565                        m_thread_info.dtv_offset);
566     ok &=
567         FindMetadata("_thread_db_dtv_dtv", eSize, m_thread_info.dtv_slot_size);
568     ok &= FindMetadata("_thread_db_link_map_l_tls_modid", eOffset,
569                        m_thread_info.modid_offset);
570     ok &= FindMetadata("_thread_db_dtv_t_pointer_val", eOffset,
571                        m_thread_info.tls_offset);
572 
573     if (ok)
574       m_thread_info.valid = true;
575   }
576 
577   return m_thread_info;
578 }
579 
580 void DYLDRendezvous::DumpToLog(Log *log) const {
581   int state = GetState();
582 
583   if (!log)
584     return;
585 
586   log->PutCString("DYLDRendezvous:");
587   log->Printf("   Address: %" PRIx64, GetRendezvousAddress());
588   log->Printf("   Version: %" PRIu64, GetVersion());
589   log->Printf("   Link   : %" PRIx64, GetLinkMapAddress());
590   log->Printf("   Break  : %" PRIx64, GetBreakAddress());
591   log->Printf("   LDBase : %" PRIx64, GetLDBase());
592   log->Printf("   State  : %s",
593               (state == eConsistent)
594                   ? "consistent"
595                   : (state == eAdd) ? "add" : (state == eDelete) ? "delete"
596                                                                  : "unknown");
597 
598   iterator I = begin();
599   iterator E = end();
600 
601   if (I != E)
602     log->PutCString("DYLDRendezvous SOEntries:");
603 
604   for (int i = 1; I != E; ++I, ++i) {
605     log->Printf("\n   SOEntry [%d] %s", i, I->file_spec.GetCString());
606     log->Printf("      Base : %" PRIx64, I->base_addr);
607     log->Printf("      Path : %" PRIx64, I->path_addr);
608     log->Printf("      Dyn  : %" PRIx64, I->dyn_addr);
609     log->Printf("      Next : %" PRIx64, I->next);
610     log->Printf("      Prev : %" PRIx64, I->prev);
611   }
612 }
613