]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - source/Plugins/DynamicLoader/POSIX-DYLD/DYLDRendezvous.cpp
Vendor import of lldb trunk r290819:
[FreeBSD/FreeBSD.git] / source / Plugins / DynamicLoader / POSIX-DYLD / DYLDRendezvous.cpp
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/Error.h"
15 #include "lldb/Core/Log.h"
16 #include "lldb/Core/Module.h"
17 #include "lldb/Symbol/ObjectFile.h"
18 #include "lldb/Symbol/Symbol.h"
19 #include "lldb/Symbol/SymbolContext.h"
20 #include "lldb/Target/Platform.h"
21 #include "lldb/Target/Process.h"
22 #include "lldb/Target/Target.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   Error 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 Linux the executable is indicated by an empty path in the entry. On
383   // FreeBSD and on Android 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     return entry.file_spec == m_exe_file_spec;
389   case llvm::Triple::Linux:
390     if (triple.isAndroid())
391       return entry.file_spec == m_exe_file_spec;
392     return !entry.file_spec;
393   default:
394     return false;
395   }
396 }
397
398 bool DYLDRendezvous::TakeSnapshot(SOEntryList &entry_list) {
399   SOEntry entry;
400
401   if (m_current.map_addr == 0)
402     return false;
403
404   // Clear previous entries since we are about to obtain an up to date list.
405   entry_list.clear();
406
407   for (addr_t cursor = m_current.map_addr; cursor != 0; cursor = entry.next) {
408     if (!ReadSOEntryFromMemory(cursor, entry))
409       return false;
410
411     // Only add shared libraries and not the executable.
412     if (SOEntryIsMainExecutable(entry))
413       continue;
414
415     entry_list.push_back(entry);
416   }
417
418   return true;
419 }
420
421 addr_t DYLDRendezvous::ReadWord(addr_t addr, uint64_t *dst, size_t size) {
422   Error error;
423
424   *dst = m_process->ReadUnsignedIntegerFromMemory(addr, size, 0, error);
425   if (error.Fail())
426     return 0;
427
428   return addr + size;
429 }
430
431 addr_t DYLDRendezvous::ReadPointer(addr_t addr, addr_t *dst) {
432   Error error;
433
434   *dst = m_process->ReadPointerFromMemory(addr, error);
435   if (error.Fail())
436     return 0;
437
438   return addr + m_process->GetAddressByteSize();
439 }
440
441 std::string DYLDRendezvous::ReadStringFromMemory(addr_t addr) {
442   std::string str;
443   Error error;
444
445   if (addr == LLDB_INVALID_ADDRESS)
446     return std::string();
447
448   m_process->ReadCStringFromMemory(addr, str, error);
449
450   return str;
451 }
452
453 // Returns true if the load bias reported by the linker is incorrect for the
454 // given entry. This
455 // function is used to handle cases where we want to work around a bug in the
456 // system linker.
457 static bool isLoadBiasIncorrect(Target &target, const std::string &file_path) {
458   // On Android L (API 21, 22) the load address of the "/system/bin/linker"
459   // isn't filled in
460   // correctly.
461   uint32_t os_major = 0, os_minor = 0, os_update = 0;
462   if (target.GetArchitecture().GetTriple().isAndroid() &&
463       target.GetPlatform()->GetOSVersion(os_major, os_minor, os_update) &&
464       (os_major == 21 || os_major == 22) &&
465       (file_path == "/system/bin/linker" ||
466        file_path == "/system/bin/linker64")) {
467     return true;
468   }
469
470   return false;
471 }
472
473 void DYLDRendezvous::UpdateBaseAddrIfNecessary(SOEntry &entry,
474                                                std::string const &file_path) {
475   // If the load bias reported by the linker is incorrect then fetch the load
476   // address of the file
477   // from the proc file system.
478   if (isLoadBiasIncorrect(m_process->GetTarget(), file_path)) {
479     lldb::addr_t load_addr = LLDB_INVALID_ADDRESS;
480     bool is_loaded = false;
481     Error error =
482         m_process->GetFileLoadAddress(entry.file_spec, is_loaded, load_addr);
483     if (error.Success() && is_loaded)
484       entry.base_addr = load_addr;
485   }
486 }
487
488 bool DYLDRendezvous::ReadSOEntryFromMemory(lldb::addr_t addr, SOEntry &entry) {
489   entry.clear();
490
491   entry.link_addr = addr;
492
493   if (!(addr = ReadPointer(addr, &entry.base_addr)))
494     return false;
495
496   // mips adds an extra load offset field to the link map struct on
497   // FreeBSD and NetBSD (need to validate other OSes).
498   // http://svnweb.freebsd.org/base/head/sys/sys/link_elf.h?revision=217153&view=markup#l57
499   const ArchSpec &arch = m_process->GetTarget().GetArchitecture();
500   if ((arch.GetTriple().getOS() == llvm::Triple::FreeBSD ||
501        arch.GetTriple().getOS() == llvm::Triple::NetBSD) &&
502       (arch.GetMachine() == llvm::Triple::mips ||
503        arch.GetMachine() == llvm::Triple::mipsel ||
504        arch.GetMachine() == llvm::Triple::mips64 ||
505        arch.GetMachine() == llvm::Triple::mips64el)) {
506     addr_t mips_l_offs;
507     if (!(addr = ReadPointer(addr, &mips_l_offs)))
508       return false;
509     if (mips_l_offs != 0 && mips_l_offs != entry.base_addr)
510       return false;
511   }
512
513   if (!(addr = ReadPointer(addr, &entry.path_addr)))
514     return false;
515
516   if (!(addr = ReadPointer(addr, &entry.dyn_addr)))
517     return false;
518
519   if (!(addr = ReadPointer(addr, &entry.next)))
520     return false;
521
522   if (!(addr = ReadPointer(addr, &entry.prev)))
523     return false;
524
525   std::string file_path = ReadStringFromMemory(entry.path_addr);
526   entry.file_spec.SetFile(file_path, false);
527
528   UpdateBaseAddrIfNecessary(entry, file_path);
529
530   return true;
531 }
532
533 bool DYLDRendezvous::FindMetadata(const char *name, PThreadField field,
534                                   uint32_t &value) {
535   Target &target = m_process->GetTarget();
536
537   SymbolContextList list;
538   if (!target.GetImages().FindSymbolsWithNameAndType(ConstString(name),
539                                                      eSymbolTypeAny, list))
540     return false;
541
542   Address address = list[0].symbol->GetAddress();
543   addr_t addr = address.GetLoadAddress(&target);
544   if (addr == LLDB_INVALID_ADDRESS)
545     return false;
546
547   Error error;
548   value = (uint32_t)m_process->ReadUnsignedIntegerFromMemory(
549       addr + field * sizeof(uint32_t), sizeof(uint32_t), 0, error);
550   if (error.Fail())
551     return false;
552
553   if (field == eSize)
554     value /= 8; // convert bits to bytes
555
556   return true;
557 }
558
559 const DYLDRendezvous::ThreadInfo &DYLDRendezvous::GetThreadInfo() {
560   if (!m_thread_info.valid) {
561     bool ok = true;
562
563     ok &= FindMetadata("_thread_db_pthread_dtvp", eOffset,
564                        m_thread_info.dtv_offset);
565     ok &=
566         FindMetadata("_thread_db_dtv_dtv", eSize, m_thread_info.dtv_slot_size);
567     ok &= FindMetadata("_thread_db_link_map_l_tls_modid", eOffset,
568                        m_thread_info.modid_offset);
569     ok &= FindMetadata("_thread_db_dtv_t_pointer_val", eOffset,
570                        m_thread_info.tls_offset);
571
572     if (ok)
573       m_thread_info.valid = true;
574   }
575
576   return m_thread_info;
577 }
578
579 void DYLDRendezvous::DumpToLog(Log *log) const {
580   int state = GetState();
581
582   if (!log)
583     return;
584
585   log->PutCString("DYLDRendezvous:");
586   log->Printf("   Address: %" PRIx64, GetRendezvousAddress());
587   log->Printf("   Version: %" PRIu64, GetVersion());
588   log->Printf("   Link   : %" PRIx64, GetLinkMapAddress());
589   log->Printf("   Break  : %" PRIx64, GetBreakAddress());
590   log->Printf("   LDBase : %" PRIx64, GetLDBase());
591   log->Printf("   State  : %s",
592               (state == eConsistent)
593                   ? "consistent"
594                   : (state == eAdd) ? "add" : (state == eDelete) ? "delete"
595                                                                  : "unknown");
596
597   iterator I = begin();
598   iterator E = end();
599
600   if (I != E)
601     log->PutCString("DYLDRendezvous SOEntries:");
602
603   for (int i = 1; I != E; ++I, ++i) {
604     log->Printf("\n   SOEntry [%d] %s", i, I->file_spec.GetCString());
605     log->Printf("      Base : %" PRIx64, I->base_addr);
606     log->Printf("      Path : %" PRIx64, I->path_addr);
607     log->Printf("      Dyn  : %" PRIx64, I->dyn_addr);
608     log->Printf("      Next : %" PRIx64, I->next);
609     log->Printf("      Prev : %" PRIx64, I->prev);
610   }
611 }