LLDB mainline
DynamicLoaderFreeBSDKernel.cpp
Go to the documentation of this file.
1//===-- DynamicLoaderFreeBSDKernel.cpp
2//------------------------------------------===//
3//
4// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5// See https://llvm.org/LICENSE.txt for license information.
6// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7//
8//===----------------------------------------------------------------------===//
9
11#include "lldb/Core/Debugger.h"
12#include "lldb/Core/Module.h"
15#include "lldb/Core/Section.h"
23#include "lldb/Target/Target.h"
24#include "lldb/Target/Thread.h"
29#include "lldb/Utility/Log.h"
30#include "lldb/Utility/State.h"
31
32#include "llvm/Support/Error.h"
33
35
37#include <memory>
38#include <mutex>
39
40using namespace lldb;
41using namespace lldb_private;
42
44
50
54
56 return "The Dynamic Loader Plugin For FreeBSD Kernel";
57}
58
59static bool is_kernel(Module *module) {
60 if (!module)
61 return false;
62
63 ObjectFile *objfile = module->GetObjectFile();
64 if (!objfile)
65 return false;
66
67 ObjectFile::Type expected_type;
68 switch (module->GetArchitecture().GetMachine()) {
69 case llvm::Triple::x86:
70 case llvm::Triple::x86_64:
71 case llvm::Triple::arm:
72 case llvm::Triple::aarch64:
73 case llvm::Triple::riscv64:
74 expected_type = ObjectFile::eTypeExecutable;
75 break;
76 case llvm::Triple::ppc64:
77 case llvm::Triple::ppc64le:
78 expected_type = ObjectFile::eTypeSharedLibrary;
79 break;
80 default:
81 return false;
82 }
83
84 if (objfile->GetType() != expected_type)
85 return false;
86 if (objfile->GetStrata() != ObjectFile::eStrataUnknown &&
88 return false;
89
90 return true;
91}
92
93static bool is_kmod(Module *module) {
94 if (!module)
95 return false;
96
97 ObjectFile *objfile = module->GetObjectFile();
98 if (!objfile)
99 return false;
100
101 switch (module->GetArchitecture().GetMachine()) {
102 case llvm::Triple::x86_64:
103 return objfile->GetType() == ObjectFile::eTypeObjectFile;
104 case llvm::Triple::x86:
105 case llvm::Triple::arm:
106 case llvm::Triple::aarch64:
107 case llvm::Triple::riscv64:
108 case llvm::Triple::ppc64:
109 case llvm::Triple::ppc64le:
110 return objfile->GetType() == ObjectFile::eTypeSharedLibrary;
111 default:
112 return false;
113 }
114}
115
116static bool set_debug_file(const ModuleSP &module,
117 llvm::StringRef target_path) {
118 if (!module || module->GetSymbolFileFileSpec())
119 return false;
120
121 FileSpec local_file = module->GetFileSpec();
122
123 FileSpec target_file(target_path);
124 if (!target_file.IsAbsolute())
125 return false;
126
127 std::string local_path = local_file.GetPath();
128 std::string normalized_target_path = target_file.GetPath();
129 llvm::StringRef local_sysroot(local_path);
130 if (!local_sysroot.consume_back(normalized_target_path))
131 return false;
132
133 std::string debug_path = local_sysroot.str();
134 debug_path += "/usr/lib/debug";
135 debug_path += normalized_target_path;
136 debug_path += ".debug";
137 FileSpec debug_file(debug_path);
138 if (!FileSystem::Instance().Exists(debug_file))
139 return false;
140
141 module->SetSymbolFileFileSpec(debug_file);
142 return true;
143}
144
145static bool is_reloc(Module *module) {
146 if (!module)
147 return false;
148
149 ObjectFile *objfile = module->GetObjectFile();
150 if (!objfile)
151 return false;
152
153 switch (module->GetArchitecture().GetMachine()) {
154 case llvm::Triple::x86_64:
155 return objfile->GetType() == ObjectFile::eTypeObjectFile;
156 default:
157 return false;
158 }
159}
160
161// Instantiate Function of the FreeBSD Kernel Dynamic Loader Plugin called when
162// Register the Plugin
165 bool force) {
166 // Check the environment when the plugin is not force loaded
167 Module *exec = process->GetTarget().GetExecutableModulePointer();
168 if (exec && !is_kernel(exec)) {
169 return nullptr;
170 }
171 if (!force) {
172 // Check if the target is kernel
173 const llvm::Triple &triple_ref =
174 process->GetTarget().GetArchitecture().GetTriple();
175 if (!triple_ref.isOSFreeBSD()) {
176 return nullptr;
177 }
178 }
179
180 // ProcessFreeBSDKernelCore explicitly selects this plugin after libkvm has
181 // established the kernel's section load addresses. Some architectures do
182 // not map the ELF file and program headers at the kernel's load address, so
183 // use the supplied kernel module instead of requiring an in-memory header.
184 if (force && exec) {
185 Address base_address = exec->GetObjectFile()->GetBaseAddress();
186 addr_t kernel_address = base_address.GetLoadAddress(&process->GetTarget());
187 if (kernel_address == LLDB_INVALID_ADDRESS)
188 kernel_address = base_address.GetFileAddress();
189 return new DynamicLoaderFreeBSDKernel(process, kernel_address);
190 }
191
192 // At this point we have checked the target is a FreeBSD kernel and all we
193 // have to do is to find the kernel address
194 const addr_t kernel_address = FindFreeBSDKernel(process);
195
196 if (CheckForKernelImageAtAddress(process, kernel_address).IsValid())
197 return new DynamicLoaderFreeBSDKernel(process, kernel_address);
198
199 return nullptr;
200}
201
202addr_t
204 addr_t kernel_addr = process->GetImageInfoAddress();
205 if (kernel_addr == LLDB_INVALID_ADDRESS)
206 kernel_addr = FindKernelAtLoadAddress(process);
207 return kernel_addr;
208}
209
210// Get the kernel address if the kernel is not loaded with a slide
212 lldb_private::Process *process) {
213 Module *exe_module = process->GetTarget().GetExecutableModulePointer();
214
215 if (!is_kernel(exe_module))
217
218 ObjectFile *exe_objfile = exe_module->GetObjectFile();
219
220 if (!exe_objfile->GetBaseAddress().IsValid())
222
224 process, exe_objfile->GetBaseAddress().GetFileAddress())
225 .IsValid())
226 return exe_objfile->GetBaseAddress().GetFileAddress();
227
229}
230
231// Read ELF header from memry and return
233 lldb::addr_t addr,
234 llvm::ELF::Elf32_Ehdr &header,
235 bool *read_error) {
237 if (read_error)
238 *read_error = false;
239
240 if (process->ReadMemory(addr, &header, sizeof(header), error) !=
241 sizeof(header) ||
242 error.Fail()) {
243 if (read_error)
244 *read_error = true;
245 return false;
246 }
247
248 if (!header.checkMagic())
249 return false;
250
251 return true;
252}
253
254// Check the correctness of Kernel and return UUID
256 Process *process, lldb::addr_t addr, bool *read_error) {
258 bool local_read_error;
259
260 if (!read_error)
261 read_error = &local_read_error;
262 *read_error = false;
263
264 if (addr == LLDB_INVALID_ADDRESS) {
265 *read_error = true;
266 return UUID();
267 }
268
269 LLDB_LOGF(log,
270 "DynamicLoaderFreeBSDKernel::CheckForKernelImageAtAddress: "
271 "looking for kernel binary at 0x%" PRIx64,
272 addr);
273
274 llvm::ELF::Elf32_Ehdr header;
275 if (!ReadELFHeader(process, addr, header)) {
276 *read_error = true;
277 return UUID();
278 }
279
280 uint16_t expected_type;
281 switch (header.e_machine) {
282 case llvm::ELF::EM_386:
283 case llvm::ELF::EM_X86_64:
284 case llvm::ELF::EM_ARM:
285 case llvm::ELF::EM_AARCH64:
286 case llvm::ELF::EM_RISCV:
287 expected_type = llvm::ELF::ET_EXEC;
288 break;
289 case llvm::ELF::EM_PPC64:
290 expected_type = llvm::ELF::ET_DYN;
291 break;
292 default:
293 return UUID();
294 }
295
296 if (header.e_type != expected_type)
297 return UUID();
298
299 llvm::Expected<ModuleSP> memory_module_sp_or_err =
300 process->ReadModuleFromMemory(FileSpec("temp_freebsd_kernel"), addr);
301 if (auto err = memory_module_sp_or_err.takeError()) {
302 LLDB_LOG_ERROR(log, std::move(err),
303 "DynamicLoaderFreeBSDKernel::CheckForKernelImageAtAddress: "
304 "Failed to read module in memory -- {0}");
305 *read_error = true;
306 return UUID();
307 }
308
309 ModuleSP memory_module_sp = *memory_module_sp_or_err;
310 if (!memory_module_sp.get()) {
311 *read_error = true;
312 return UUID();
313 }
314
315 ObjectFile *exe_objfile = memory_module_sp->GetObjectFile();
316 if (exe_objfile == nullptr) {
317 LLDB_LOGF(log,
318 "DynamicLoaderFreeBSDKernel::CheckForKernelImageAtAddress "
319 "found a binary at 0x%" PRIx64
320 " but could not create an object file from memory",
321 addr);
322 return UUID();
323 }
324
325 // In here, I should check is_kernel for memory_module_sp
326 // However, the ReadModuleFromMemory reads wrong section so that this check
327 // will failed
328 ArchSpec kernel_arch(llvm::ELF::convertEMachineToArchName(header.e_machine));
329
330 if (!process->GetTarget().GetArchitecture().IsCompatibleMatch(kernel_arch))
331 process->GetTarget().SetArchitecture(kernel_arch);
332
333 std::string uuid_str;
334 if (memory_module_sp->GetUUID().IsValid()) {
335 uuid_str = "with UUID ";
336 uuid_str += memory_module_sp->GetUUID().GetAsString();
337 } else {
338 uuid_str = "and no LC_UUID found in load commands ";
339 }
340 LLDB_LOGF(log,
341 "DynamicLoaderFreeBSDKernel::CheckForKernelImageAtAddress: "
342 "kernel binary image found at 0x%" PRIx64 " with arch '%s' %s",
343 addr, kernel_arch.GetTriple().str().c_str(), uuid_str.c_str());
344
345 return memory_module_sp->GetUUID();
346}
347
350
352 addr_t kernel_address)
353 : DynamicLoader(process), m_process(process),
354 m_kernel_load_address(kernel_address), m_mutex() {
355 process->SetCanRunCode(false);
356}
357
359
364
365// Create in memory Module at the load address
367 lldb_private::Process *process) {
370 return true;
372 return false;
373
374 FileSpec file_spec(m_name);
375
376 ModuleSP memory_module_sp;
377
378 llvm::ELF::Elf32_Ehdr elf_eheader;
379 size_t size_to_read = 512;
380
381 if (ReadELFHeader(process, m_load_address, elf_eheader)) {
382 if (elf_eheader.e_ident[llvm::ELF::EI_CLASS] == llvm::ELF::ELFCLASS32) {
383 size_to_read = sizeof(llvm::ELF::Elf32_Ehdr) +
384 elf_eheader.e_phnum * elf_eheader.e_phentsize;
385 } else if (elf_eheader.e_ident[llvm::ELF::EI_CLASS] ==
386 llvm::ELF::ELFCLASS64) {
387 llvm::ELF::Elf64_Ehdr elf_eheader;
389 if (process->ReadMemory(m_load_address, &elf_eheader, sizeof(elf_eheader),
390 error) == sizeof(elf_eheader) &&
391 error.Success())
392 size_to_read = sizeof(llvm::ELF::Elf64_Ehdr) +
393 elf_eheader.e_phnum * elf_eheader.e_phentsize;
394 }
395 }
396
397 llvm::Expected<ModuleSP> memory_module_sp_or_err =
398 process->ReadModuleFromMemory(file_spec, m_load_address, size_to_read);
399 if (auto err = memory_module_sp_or_err.takeError()) {
400 LLDB_LOG_ERROR(log, std::move(err),
401 "KextImageInfo::ReadMemoryModule: Failed to read module "
402 "from memory -- {0}");
403 return false;
404 }
405 memory_module_sp = *memory_module_sp_or_err;
406
407 if (!memory_module_sp)
408 return false;
409
410 bool this_is_kernel = is_kernel(memory_module_sp.get());
411
412 if (!m_uuid.IsValid() && memory_module_sp->GetUUID().IsValid())
413 m_uuid = memory_module_sp->GetUUID();
414
415 m_memory_module_sp = memory_module_sp;
416 m_is_kernel = this_is_kernel;
417
418 // The kernel binary is from memory
419 if (this_is_kernel) {
420 LLDB_LOGF(log, "KextImageInfo::ReadMemoryModule read the kernel binary out "
421 "of memory");
422
423 if (memory_module_sp->GetArchitecture().IsValid())
424 process->GetTarget().SetArchitecture(memory_module_sp->GetArchitecture());
425 }
426
427 return true;
428}
429
431 lldb_private::Process *process) {
433
434 if (IsLoaded())
435 return true;
436
437 Target &target = process->GetTarget();
438
439 if (IsKernel() && m_uuid.IsValid()) {
441 s->Printf("Kernel UUID: %s\n", m_uuid.GetAsString().c_str());
442 s->Printf("Load Address: 0x%" PRIx64 "\n", m_load_address);
443 }
444
445 // Test if the module is loaded into the taget,
446 // maybe the module is loaded manually by user by doing target module add
447 // So that we have to create the module manually
448 if (!m_module_sp) {
449 const ModuleList &target_images = target.GetImages();
450 m_module_sp = target_images.FindModule(m_uuid);
451
452 // Search in the file system
453 if (!m_module_sp) {
454 ModuleSpec module_spec(FileSpec(GetPath()), target.GetArchitecture());
455 if (IsKernel()) {
458 true) &&
459 error.Success()) {
460 if (FileSystem::Instance().Exists(module_spec.GetFileSpec()))
461 m_module_sp = std::make_shared<Module>(module_spec.GetFileSpec(),
462 target.GetArchitecture());
463 }
464 }
465
466 if (!m_module_sp)
467 m_module_sp = target.GetOrCreateModule(module_spec, true);
468 if (IsKernel() && !m_module_sp) {
469 target.GetDebugger().GetAsyncOutputStream()->Printf(
470 "WARNING: Unable to locate kernel binary on the debugger "
471 "system.\n");
472 }
473 }
474
475 if (m_module_sp && !IsKernel())
477
478 if (m_module_sp) {
479 // If the file is not kernel or kmod, the target should be loaded once and
480 // don't reload again
481 if (!IsKernel() && !is_kmod(m_module_sp.get())) {
482 ModuleSP existing_module_sp = target.GetImages().FindModule(m_uuid);
483 if (existing_module_sp &&
484 existing_module_sp->IsLoadedInTarget(&target)) {
485 LLDB_LOGF(log,
486 "'%s' with UUID %s is not a kmod or kernel, and is "
487 "already registered in target, not loading.",
488 m_name.c_str(), m_uuid.GetAsString().c_str());
489 return true;
490 }
491 }
492 m_uuid = m_module_sp->GetUUID();
493
494 // or append to the images
495 target.GetImages().AppendIfNeeded(m_module_sp, false);
496 }
497 }
498
499 // If this file is relocatable kernel module(x86_64), adjust it's
500 // section(PT_LOAD segment) and return Because the kernel module's load
501 // address is the text section. lldb cannot create full memory module upon
502 // relocatable file So what we do is to set the load address only.
503 if (is_kmod(m_module_sp.get()) && is_reloc(m_module_sp.get())) {
504 m_stop_id = process->GetStopID();
505 bool changed = false;
506 m_module_sp->SetLoadAddress(target, m_load_address, true, changed);
507 return true;
508 }
509
510 if (m_module_sp)
511 ReadMemoryModule(process);
512
513 // Calculate the slides of in memory module
515 m_module_sp.reset();
516 return false;
517 }
518
519 ObjectFile *ondisk_object_file = m_module_sp->GetObjectFile();
520 ObjectFile *memory_object_file = m_memory_module_sp->GetObjectFile();
521
522 if (!ondisk_object_file || !memory_object_file)
523 m_module_sp.reset();
524
525 // Find the slide address
526 addr_t fixed_slide = LLDB_INVALID_ADDRESS;
527 if (llvm::dyn_cast<ObjectFileELF>(memory_object_file)) {
528 addr_t load_address = memory_object_file->GetBaseAddress().GetFileAddress();
529
530 if (load_address != LLDB_INVALID_ADDRESS &&
531 m_load_address != load_address) {
532 fixed_slide = m_load_address - load_address;
533 LLDB_LOGF(log,
534 "kmod %s in-memory LOAD vmaddr is not correct, using a "
535 "fixed slide of 0x%" PRIx64,
536 m_name.c_str(), fixed_slide);
537 }
538 }
539
540 SectionList *ondisk_section_list = ondisk_object_file->GetSectionList();
541 SectionList *memory_section_list = memory_object_file->GetSectionList();
542
543 if (memory_section_list && ondisk_object_file) {
544 const uint32_t num_ondisk_sections = ondisk_section_list->GetSize();
545 uint32_t num_load_sections = 0;
546
547 for (uint32_t section_idx = 0; section_idx < num_ondisk_sections;
548 ++section_idx) {
549 SectionSP on_disk_section_sp =
550 ondisk_section_list->GetSectionAtIndex(section_idx);
551
552 if (!on_disk_section_sp)
553 continue;
554 if (fixed_slide != LLDB_INVALID_ADDRESS) {
555 target.SetSectionLoadAddress(on_disk_section_sp,
556 on_disk_section_sp->GetFileAddress() +
557 fixed_slide);
558 ++num_load_sections;
559
560 } else {
561 const Section *memory_section =
562 memory_section_list
563 ->FindSectionByName(on_disk_section_sp->GetName())
564 .get();
565 if (memory_section) {
566 target.SetSectionLoadAddress(on_disk_section_sp,
567 memory_section->GetFileAddress());
568 ++num_load_sections;
569 }
570 }
571 }
572
573 if (num_load_sections)
574 m_stop_id = process->GetStopID();
575 else
576 m_module_sp.reset();
577 } else {
578 m_module_sp.reset();
579 }
580
581 if (IsLoaded() && m_module_sp && IsKernel()) {
583 ObjectFile *kernel_object_file = m_module_sp->GetObjectFile();
584 if (kernel_object_file) {
585 addr_t file_address =
586 kernel_object_file->GetBaseAddress().GetFileAddress();
588 file_address != LLDB_INVALID_ADDRESS) {
589 s->Printf("Kernel slide 0x%" PRIx64 " in memory.\n",
590 m_load_address - file_address);
591 s->Printf("Loaded kernel file %s\n",
592 m_module_sp->GetFileSpec().GetPath().c_str());
593 }
594 }
595 }
596
597 return IsLoaded();
598}
599
600// This function is work for kernel file, others it wil reset load address and
601// return false
603 lldb_private::Process *process) {
604 if (IsLoaded())
605 return true;
606
607 if (m_module_sp) {
608 bool changed = false;
609 if (m_module_sp->SetLoadAddress(process->GetTarget(), 0, true, changed))
610 m_stop_id = process->GetStopID();
611 }
612
613 return false;
614}
615
616// Get the head of found_list
618 std::lock_guard<decltype(m_mutex)> guard(m_mutex);
619
620 if (m_linker_file_list_struct_addr.IsValid()) {
621 // Get tqh_first struct element from linker_files
622 llvm::Expected<lldb::addr_t> address = m_process->ReadPointerFromMemory(
623 m_linker_file_list_struct_addr.GetLoadAddress(&m_process->GetTarget()));
624 if (!address) {
625 llvm::consumeError(address.takeError());
627 return false;
628 }
630
631 if (!m_linker_file_head_addr.IsValid() ||
632 m_linker_file_head_addr.GetFileAddress() == 0) {
634 return false;
635 }
636 }
637 return true;
638}
639
640// Parse Kmod info in found_list
642 std::lock_guard<decltype(m_mutex)> guard(m_mutex);
643 KModImageInfo::collection_type linker_files_list;
645
646 if (!ReadAllKmods(linker_files_head_addr, linker_files_list))
647 return false;
648 LLDB_LOGF(
649 log,
650 "Kmod-changed breakpoint hit, there are %zu kernel modules currently.\n",
651 linker_files_list.size());
652
653 ModuleList &modules = m_process->GetTarget().GetImages();
654 ModuleList remove_modules;
655 ModuleList add_modules;
656
657 for (ModuleSP module : modules.Modules()) {
658 if (is_kernel(module.get()))
659 continue;
660 if (is_kmod(module.get()))
661 remove_modules.AppendIfNeeded(module);
662 }
663
664 m_process->GetTarget().ModulesDidUnload(remove_modules, false);
665
666 for (KModImageInfo &image_info : linker_files_list) {
667 auto it = m_kld_name_to_uuid.find(image_info.GetName());
668 if (it != m_kld_name_to_uuid.end())
669 image_info.SetUUID(it->second);
670 bool failed_to_load = false;
671 if (!image_info.LoadImageUsingMemoryModule(m_process)) {
672 image_info.LoadImageUsingFileAddress(m_process);
673 failed_to_load = true;
674 } else {
675 m_linker_files_list.push_back(image_info);
676 m_kld_name_to_uuid[image_info.GetName()] = image_info.GetUUID();
677 }
678
679 if (!failed_to_load)
680 add_modules.AppendIfNeeded(image_info.GetModule());
681 }
682 m_process->GetTarget().ModulesDidLoad(add_modules);
683 return true;
684}
685
686// Read all kmod from a given arrays of list
688 Address linker_files_head_addr,
689 KModImageInfo::collection_type &kmods_list) {
690
691 // Get offset of next member and load address symbol
692 static ConstString kld_off_address_symbol_name("kld_off_address");
693 static ConstString kld_off_next_symbol_name("kld_off_next");
694 static ConstString kld_off_filename_symbol_name("kld_off_filename");
695 static ConstString kld_off_pathname_symbol_name("kld_off_pathname");
696 const Symbol *kld_off_address_symbol =
697 m_kernel_image_info.GetModule()->FindFirstSymbolWithNameAndType(
698 kld_off_address_symbol_name, eSymbolTypeData);
699 const Symbol *kld_off_next_symbol =
700 m_kernel_image_info.GetModule()->FindFirstSymbolWithNameAndType(
701 kld_off_next_symbol_name, eSymbolTypeData);
702 const Symbol *kld_off_filename_symbol =
703 m_kernel_image_info.GetModule()->FindFirstSymbolWithNameAndType(
704 kld_off_filename_symbol_name, eSymbolTypeData);
705 const Symbol *kld_off_pathname_symbol =
706 m_kernel_image_info.GetModule()->FindFirstSymbolWithNameAndType(
707 kld_off_pathname_symbol_name, eSymbolTypeData);
708
709 if (!kld_off_address_symbol || !kld_off_next_symbol ||
710 !kld_off_filename_symbol || !kld_off_pathname_symbol)
711 return false;
712
714 const int32_t kld_off_address = m_process->ReadSignedIntegerFromMemory(
715 kld_off_address_symbol->GetAddress().GetLoadAddress(
716 &m_process->GetTarget()),
717 4, 0, error);
718 if (error.Fail())
719 return false;
720 const int32_t kld_off_next = m_process->ReadSignedIntegerFromMemory(
721 kld_off_next_symbol->GetAddress().GetLoadAddress(&m_process->GetTarget()),
722 4, 0, error);
723 if (error.Fail())
724 return false;
725 const int32_t kld_off_filename = m_process->ReadSignedIntegerFromMemory(
726 kld_off_filename_symbol->GetAddress().GetLoadAddress(
727 &m_process->GetTarget()),
728 4, 0, error);
729 if (error.Fail())
730 return false;
731
732 const int32_t kld_off_pathname = m_process->ReadSignedIntegerFromMemory(
733 kld_off_pathname_symbol->GetAddress().GetLoadAddress(
734 &m_process->GetTarget()),
735 4, 0, error);
736 if (error.Fail())
737 return false;
738
739 // Parse KMods
740 addr_t kld_load_addr(LLDB_INVALID_ADDRESS);
741 char kld_filename[255];
742 char kld_pathname[255];
743 addr_t current_kld =
744 linker_files_head_addr.GetLoadAddress(&m_process->GetTarget());
745
746 while (current_kld != 0) {
747 llvm::Expected<lldb::addr_t> kld_filename_addr =
748 m_process->ReadPointerFromMemory(current_kld + kld_off_filename);
749 if (!kld_filename_addr) {
750 llvm::consumeError(kld_filename_addr.takeError());
751 return false;
752 }
753 llvm::Expected<lldb::addr_t> kld_pathname_addr =
754 m_process->ReadPointerFromMemory(current_kld + kld_off_pathname);
755 if (!kld_pathname_addr) {
756 llvm::consumeError(kld_pathname_addr.takeError());
757 return false;
758 }
759
760 m_process->ReadCStringFromMemory(*kld_filename_addr, kld_filename,
761 sizeof(kld_filename), error);
762 if (error.Fail())
763 return false;
764 m_process->ReadCStringFromMemory(*kld_pathname_addr, kld_pathname,
765 sizeof(kld_pathname), error);
766 if (error.Fail())
767 return false;
768 llvm::Expected<lldb::addr_t> kld_load_addr_or_err =
769 m_process->ReadPointerFromMemory(current_kld + kld_off_address);
770 if (!kld_load_addr_or_err) {
771 llvm::consumeError(kld_load_addr_or_err.takeError());
772 return false;
773 }
774 kld_load_addr = *kld_load_addr_or_err;
775
776 kmods_list.emplace_back();
777 KModImageInfo &kmod_info = kmods_list.back();
778 kmod_info.SetName(kld_filename);
779 kmod_info.SetLoadAddress(kld_load_addr);
780 kmod_info.SetPath(kld_pathname);
781
782 llvm::Expected<lldb::addr_t> next_kld =
783 m_process->ReadPointerFromMemory(current_kld + kld_off_next);
784
785 if (kmod_info.GetName() == "kernel")
786 kmods_list.pop_back();
787
788 if (!next_kld) {
789 llvm::consumeError(next_kld.takeError());
790 return false;
791 }
792 current_kld = *next_kld;
793 }
794
795 return true;
796}
797
798// Read all kmods
800 std::lock_guard<decltype(m_mutex)> guard(m_mutex);
801
802 if (ReadKmodsListHeader()) {
803 if (m_linker_file_head_addr.IsValid()) {
805 m_linker_files_list.clear();
806 }
807 }
808}
809
810// Load all Kernel Modules
813 LLDB_LOGF(log, "DynamicLoaderFreeBSDKernel::LoadKernelModules "
814 "Start loading Kernel Module");
815
816 // Initialize Kernel Image Information at the first time
817 if (m_kernel_image_info.GetLoadAddress() == LLDB_INVALID_ADDRESS) {
818 ModuleSP module_sp = m_process->GetTarget().GetExecutableModule();
819 if (is_kernel(module_sp.get())) {
820 m_kernel_image_info.SetModule(module_sp);
821 m_kernel_image_info.SetIsKernel(true);
822 }
823
824 // Set name for kernel
825 llvm::StringRef kernel_name("freebsd_kernel");
826 module_sp = m_kernel_image_info.GetModule();
827 if (module_sp.get() && module_sp->GetObjectFile() &&
828 !module_sp->GetObjectFile()->GetFileSpec().GetFilename().empty())
829 kernel_name = module_sp->GetObjectFile()->GetFileSpec().GetFilename();
830 m_kernel_image_info.SetName(kernel_name.data());
831
832 if (m_kernel_image_info.GetLoadAddress() == LLDB_INVALID_ADDRESS) {
834 }
835
836 // Build In memory Module
837 if (m_kernel_image_info.GetLoadAddress() != LLDB_INVALID_ADDRESS) {
838 // If the kernel is not loaded in the memory, use file to load
839 if (!m_kernel_image_info.LoadImageUsingMemoryModule(m_process))
840 m_kernel_image_info.LoadImageUsingFileAddress(m_process);
841 }
842 }
843
845
846 if (!m_kernel_image_info.IsLoaded() || !m_kernel_image_info.GetModule()) {
847 m_kernel_image_info.Clear();
848 return;
849 }
850
851 static ConstString modlist_symbol_name("linker_files");
852
853 const Symbol *symbol =
854 m_kernel_image_info.GetModule()->FindFirstSymbolWithNameAndType(
855 modlist_symbol_name, lldb::eSymbolTypeData);
856
857 if (symbol) {
859 ReadAllKmods();
860 } else {
861 LLDB_LOGF(log, "DynamicLoaderFreeBSDKernel::LoadKernelModules "
862 "cannot file modlist symbol");
863 }
864}
865
866// Update symbol when use kldload by setting callback function on kldload
868
869// Hook called when attach to a process
874
875// Hook called after attach to a process
880
881// Clear all member except kernel address
882void DynamicLoaderFreeBSDKernel::Clear(bool clear_process) {
883 std::lock_guard<decltype(m_mutex)> guard(m_mutex);
884 if (clear_process)
885 m_process = nullptr;
888 m_kernel_image_info.Clear();
889 m_linker_files_list.clear();
890}
891
892// Reinitialize class
894 Clear(true);
895 m_process = process;
896}
897
899 lldb_private::Thread &thread, bool stop_others) {
900 Log *log = GetLog(LLDBLog::Step);
901 LLDB_LOGF(log, "DynamicLoaderFreeBSDKernel::GetStepThroughTrampolinePlan is "
902 "not yet implemented.");
903 return {};
904}
905
907 return Status::FromErrorString("shared object cannot be loaded into kernel");
908}
static llvm::raw_ostream & error(Stream &strm)
static bool is_kernel(Module *module)
static bool is_reloc(Module *module)
static bool set_debug_file(const ModuleSP &module, llvm::StringRef target_path)
static bool is_kernel(Module *module)
static bool is_kmod(Module *module)
#define LLDB_LOGF(log,...)
Definition Log.h:389
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:405
#define LLDB_PLUGIN_DEFINE(PluginName)
bool LoadImageUsingFileAddress(lldb_private::Process *process)
bool ReadMemoryModule(lldb_private::Process *process)
bool LoadImageUsingMemoryModule(lldb_private::Process *process)
void DidAttach() override
Called after attaching a process.
DynamicLoaderFreeBSDKernel(lldb_private::Process *process, lldb::addr_t kernel_addr)
KModImageInfo::collection_type m_linker_files_list
static llvm::StringRef GetPluginNameStatic()
lldb_private::Address m_linker_file_list_struct_addr
void PrivateInitialize(lldb_private::Process *process)
lldb_private::Address m_linker_file_head_addr
lldb::ThreadPlanSP GetStepThroughTrampolinePlan(lldb_private::Thread &thread, bool stop_others) override
Provides a plan to step through the dynamic loader trampoline for the current state of thread.
bool ParseKmods(lldb_private::Address linker_files_head_address)
static void DebuggerInit(lldb_private::Debugger &debugger)
static lldb::addr_t FindFreeBSDKernel(lldb_private::Process *process)
lldb_private::Status CanLoadImage() override
Ask if it is ok to try and load or unload an shared library (image).
std::unordered_map< std::string, lldb_private::UUID > m_kld_name_to_uuid
void DidLaunch() override
Called after launching a process.
static lldb::addr_t FindKernelAtLoadAddress(lldb_private::Process *process)
static llvm::StringRef GetPluginDescriptionStatic()
static lldb_private::UUID CheckForKernelImageAtAddress(lldb_private::Process *process, lldb::addr_t address, bool *read_error=nullptr)
static lldb_private::DynamicLoader * CreateInstance(lldb_private::Process *process, bool force)
static bool ReadELFHeader(lldb_private::Process *process, lldb::addr_t address, llvm::ELF::Elf32_Ehdr &header, bool *read_error=nullptr)
A section + offset based address class.
Definition Address.h:62
lldb::addr_t GetLoadAddress(Target *target) const
Get the load address.
Definition Address.cpp:303
lldb::addr_t GetFileAddress() const
Get the file address.
Definition Address.cpp:283
bool IsValid() const
Check if the object state is valid.
Definition Address.h:355
An architecture specification class.
Definition ArchSpec.h:32
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition ArchSpec.h:545
bool IsCompatibleMatch(const ArchSpec &rhs) const
Shorthand for IsMatch(rhs, CompatibleMatch).
Definition ArchSpec.h:597
llvm::Triple::ArchType GetMachine() const
Returns a machine family for the current architecture.
Definition ArchSpec.cpp:883
A uniqued constant string class.
Definition ConstString.h:40
A class to manage flag bits.
Definition Debugger.h:100
lldb::StreamUP GetAsyncOutputStream()
A plug-in interface definition class for dynamic loaders.
void LoadOperatingSystemPlugin(bool flush)
DynamicLoader(Process *process)
Construct with a process.
A file utility class.
Definition FileSpec.h:56
bool IsAbsolute() const
Returns true if the filespec represents an absolute path.
Definition FileSpec.cpp:518
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:380
static FileSystem & Instance()
A collection class for Module objects.
Definition ModuleList.h:125
bool AppendIfNeeded(const lldb::ModuleSP &new_module, bool notify=true)
Append a module to the module list, if it is not already there.
lldb::ModuleSP FindModule(const Module *module_ptr) const
ModuleIterable Modules() const
Definition ModuleList.h:571
FileSpec & GetFileSpec()
Definition ModuleSpec.h:57
A class that describes an executable image and its associated object and symbol files.
Definition Module.h:91
virtual ObjectFile * GetObjectFile()
Get the object file representation for the current architecture.
Definition Module.cpp:1179
const ArchSpec & GetArchitecture() const
Get const accessor for the module architecture.
Definition Module.cpp:1017
A plug-in interface definition class for object file parsers.
Definition ObjectFile.h:46
@ eTypeExecutable
A normal executable.
Definition ObjectFile.h:55
@ eTypeObjectFile
An intermediate object file.
Definition ObjectFile.h:61
@ eTypeSharedLibrary
A shared library that can be used during execution.
Definition ObjectFile.h:63
virtual SectionList * GetSectionList(bool update_module_section_list=true)
Gets the section list for the currently selected architecture (and object for archives).
virtual lldb_private::Address GetBaseAddress()
Returns base address of this object file.
Definition ObjectFile.h:468
static bool DownloadObjectAndSymbolFile(ModuleSpec &module_spec, Status &error, bool force_lookup=true, bool copy_executable=true)
static bool RegisterPlugin(llvm::StringRef name, llvm::StringRef description, ABICreateInstance create_callback)
static bool UnregisterPlugin(ABICreateInstance create_callback)
A plug-in interface definition class for debugging a process.
Definition Process.h:368
virtual size_t ReadMemory(const ProcessAddress &process_addr, void *buf, size_t size, Status &error)
Read of memory from a process.
Definition Process.cpp:2110
llvm::Expected< lldb::ModuleSP > ReadModuleFromMemory(const FileSpec &file_spec, lldb::addr_t header_addr, size_t size_to_read=512)
Creates and populates a module using an in-memory object file.
Definition Process.cpp:2807
virtual lldb::addr_t GetImageInfoAddress()
Get the image information address for the current process.
Definition Process.cpp:1523
void SetCanRunCode(bool can_run_code)
Sets whether executing code in this process is possible.
Definition Process.cpp:2773
uint32_t GetStopID() const
Definition Process.h:1514
Target & GetTarget()
Get the target object pointer for this module.
Definition Process.h:1267
size_t GetSize() const
Definition Section.h:76
lldb::SectionSP FindSectionByName(llvm::StringRef section_name) const
Definition Section.cpp:562
lldb::SectionSP GetSectionAtIndex(size_t idx) const
Definition Section.cpp:555
lldb::addr_t GetFileAddress() const
Definition Section.cpp:194
An error handling class.
Definition Status.h:118
static Status FromErrorString(const char *str)
Definition Status.h:141
Address GetAddress() const
Definition Symbol.h:98
Module * GetExecutableModulePointer()
Definition Target.cpp:1650
Debugger & GetDebugger() const
Definition Target.h:1356
lldb::ModuleSP GetOrCreateModule(const ModuleSpec &module_spec, bool notify, Status *error_ptr=nullptr)
Find a binary on the system and return its Module, or return an existing Module that is already in th...
Definition Target.cpp:2470
bool SetArchitecture(const ArchSpec &arch_spec, bool set_platform=false, bool merge=true)
Set the architecture for this target.
Definition Target.cpp:1807
const ModuleList & GetImages() const
Get accessor for the images for this process.
Definition Target.h:1273
const ArchSpec & GetArchitecture() const
Definition Target.h:1315
bool SetSectionLoadAddress(const lldb::SectionSP &section, lldb::addr_t load_addr, bool warn_multiple=false)
Definition Target.cpp:3516
Represents UUID's of various sizes.
Definition UUID.h:27
bool IsValid() const
Definition UUID.h:69
#define LLDB_INVALID_ADDRESS
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:338
std::shared_ptr< lldb_private::ThreadPlan > ThreadPlanSP
std::shared_ptr< lldb_private::Section > SectionSP
uint64_t addr_t
Definition lldb-types.h:80
std::unique_ptr< lldb_private::Stream > StreamUP
std::shared_ptr< lldb_private::Module > ModuleSP