LLDB mainline
PlatformDarwin.cpp
Go to the documentation of this file.
1//===-- PlatformDarwin.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 "PlatformDarwin.h"
10
11#include <cstring>
12
13#include <algorithm>
14#include <memory>
15#include <mutex>
16#include <optional>
17
20#include "lldb/Core/Debugger.h"
21#include "lldb/Core/Module.h"
24#include "lldb/Core/Section.h"
25#include "lldb/Host/Host.h"
26#include "lldb/Host/HostInfo.h"
27#include "lldb/Host/XML.h"
37#include "lldb/Target/Process.h"
38#include "lldb/Target/Target.h"
40#include "lldb/Utility/Log.h"
42#include "lldb/Utility/Status.h"
43#include "lldb/Utility/Timer.h"
44#include "llvm/ADT/STLExtras.h"
45#include "llvm/ADT/StringTable.h"
46#include "llvm/Support/Error.h"
47#include "llvm/Support/FileSystem.h"
48#include "llvm/Support/Threading.h"
49#include "llvm/Support/VersionTuple.h"
50
51#if defined(__APPLE__)
52#include <TargetConditionals.h>
53#endif
54
55using namespace lldb;
56using namespace lldb_private;
57
58#define OPTTABLE_STR_TABLE_CODE
59#include "clang/Driver/Options.inc"
60#undef OPTTABLE_STR_TABLE_CODE
61
62static Status ExceptionMaskValidator(const char *string, void *unused) {
64 llvm::StringRef str_ref(string);
65 llvm::SmallVector<llvm::StringRef> candidates;
66 str_ref.split(candidates, '|');
67 for (auto candidate : candidates) {
68 if (!(candidate == "EXC_BAD_ACCESS"
69 || candidate == "EXC_BAD_INSTRUCTION"
70 || candidate == "EXC_ARITHMETIC"
71 || candidate == "EXC_RESOURCE"
72 || candidate == "EXC_GUARD"
73 || candidate == "EXC_SYSCALL")) {
74 error = Status::FromErrorStringWithFormat("invalid exception type: '%s'",
75 candidate.str().c_str());
76 return error;
77 }
78 }
79 return {};
80}
81
82/// Destructor.
83///
84/// The destructor is virtual since this class is designed to be
85/// inherited from by the plug-in instance.
87
88// Static Variables
89static uint32_t g_initialize_count = 0;
90
101
111
113 return "Darwin platform plug-in.";
114}
115
117 // We only create subclasses of the PlatformDarwin plugin.
118 return PlatformSP();
119}
120
121#define LLDB_PROPERTIES_platformdarwin
122#include "PlatformMacOSXProperties.inc"
123
124#define LLDB_PROPERTIES_platformdarwin
125enum {
126#include "PlatformMacOSXPropertiesEnum.inc"
127};
128
130public:
131 static llvm::StringRef GetSettingName() {
132 static constexpr llvm::StringLiteral g_setting_name("darwin");
133 return g_setting_name;
134 }
135
137 m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName());
138 m_collection_sp->Initialize(g_platformdarwin_properties);
139 }
140
141 ~PlatformDarwinProperties() override = default;
142
143 const char *GetIgnoredExceptions() const {
144 const uint32_t idx = ePropertyIgnoredExceptions;
145 const OptionValueString *option_value =
146 m_collection_sp->GetPropertyAtIndexAsOptionValueString(idx);
147 assert(option_value);
148 return option_value->GetCurrentValue();
149 }
150
152 const uint32_t idx = ePropertyIgnoredExceptions;
153 OptionValueString *option_value =
154 m_collection_sp->GetPropertyAtIndexAsOptionValueString(idx);
155 assert(option_value);
156 return option_value;
157 }
158};
159
161 static PlatformDarwinProperties g_settings;
162 return g_settings;
163}
164
166 lldb_private::Debugger &debugger) {
169 const bool is_global_setting = false;
171 debugger, GetGlobalProperties().GetValueProperties(),
172 "Properties for the Darwin platform plug-in.", is_global_setting);
173 OptionValueString *value = GetGlobalProperties().GetIgnoredExceptionValue();
175 }
176}
177
178Args
180 std::string ignored_exceptions
181 = GetGlobalProperties().GetIgnoredExceptions();
182 if (ignored_exceptions.empty())
183 return {};
184 Args ret_args;
185 std::string packet = "QSetIgnoredExceptions:";
186 packet.append(ignored_exceptions);
187 ret_args.AppendArgument(packet);
188 return ret_args;
189}
190
193 const lldb_private::FileSpec &destination, uint32_t uid,
194 uint32_t gid) {
195 // Unconditionally unlink the destination. If it is an executable,
196 // simply opening it and truncating its contents would invalidate
197 // its cached code signature.
198 Unlink(destination);
199 return PlatformPOSIX::PutFile(source, destination, uid, gid);
200}
201
203 Target *target, Module &module, Stream &feedback_stream) {
204 FileSpecList file_list;
205 if (target &&
207 // NB some extensions might be meaningful and should not be stripped -
208 // "this.binary.file"
209 // should not lose ".file" but GetFileNameStrippingExtension() will do
210 // precisely that. Ideally, we should have a per-platform list of
211 // extensions (".exe", ".app", ".dSYM", ".framework") which should be
212 // stripped while leaving "this.binary.file" as-is.
213
214 FileSpec module_spec = module.GetFileSpec();
215
216 if (module_spec) {
217 if (SymbolFile *symfile = module.GetSymbolFile()) {
218 ObjectFile *objfile = symfile->GetObjectFile();
219 if (objfile) {
220 FileSpec symfile_spec(objfile->GetFileSpec());
221 if (symfile_spec &&
222 llvm::StringRef(symfile_spec.GetPath())
223 .contains_insensitive(".dSYM/Contents/Resources/DWARF") &&
224 FileSystem::Instance().Exists(symfile_spec)) {
225 while (module_spec.GetFilename()) {
226 std::string module_basename(
227 module_spec.GetFilename().GetCString());
228 std::string original_module_basename(module_basename);
229
230 bool was_keyword = false;
231
232 // FIXME: for Python, we cannot allow certain characters in
233 // module
234 // filenames we import. Theoretically, different scripting
235 // languages may have different sets of forbidden tokens in
236 // filenames, and that should be dealt with by each
237 // ScriptInterpreter. For now, we just replace dots with
238 // underscores, but if we ever support anything other than
239 // Python we will need to rework this
240 llvm::replace(module_basename, '.', '_');
241 llvm::replace(module_basename, ' ', '_');
242 llvm::replace(module_basename, '-', '_');
243 ScriptInterpreter *script_interpreter =
245 if (script_interpreter &&
246 script_interpreter->IsReservedWord(module_basename.c_str())) {
247 module_basename.insert(module_basename.begin(), '_');
248 was_keyword = true;
249 }
250
251 StreamString path_string;
252 StreamString original_path_string;
253 // for OSX we are going to be in
254 // .dSYM/Contents/Resources/DWARF/<basename> let us go to
255 // .dSYM/Contents/Resources/Python/<basename>.py and see if the
256 // file exists
257 path_string.Printf("%s/../Python/%s.py",
258 symfile_spec.GetDirectory().GetCString(),
259 module_basename.c_str());
260 original_path_string.Printf(
261 "%s/../Python/%s.py",
262 symfile_spec.GetDirectory().GetCString(),
263 original_module_basename.c_str());
264 FileSpec script_fspec(path_string.GetString());
265 FileSystem::Instance().Resolve(script_fspec);
266 FileSpec orig_script_fspec(original_path_string.GetString());
267 FileSystem::Instance().Resolve(orig_script_fspec);
268
269 // if we did some replacements of reserved characters, and a
270 // file with the untampered name exists, then warn the user
271 // that the file as-is shall not be loaded
272 if (module_basename != original_module_basename &&
273 FileSystem::Instance().Exists(orig_script_fspec)) {
274 const char *reason_for_complaint =
275 was_keyword ? "conflicts with a keyword"
276 : "contains reserved characters";
277 if (FileSystem::Instance().Exists(script_fspec))
278 feedback_stream.Printf(
279 "warning: the symbol file '%s' contains a debug "
280 "script. However, its name"
281 " '%s' %s and as such cannot be loaded. LLDB will"
282 " load '%s' instead. Consider removing the file with "
283 "the malformed name to"
284 " eliminate this warning.\n",
285 symfile_spec.GetPath().c_str(),
286 original_path_string.GetData(), reason_for_complaint,
287 path_string.GetData());
288 else
289 feedback_stream.Printf(
290 "warning: the symbol file '%s' contains a debug "
291 "script. However, its name"
292 " %s and as such cannot be loaded. If you intend"
293 " to have this script loaded, please rename '%s' to "
294 "'%s' and retry.\n",
295 symfile_spec.GetPath().c_str(), reason_for_complaint,
296 original_path_string.GetData(), path_string.GetData());
297 }
298
299 if (FileSystem::Instance().Exists(script_fspec)) {
300 file_list.Append(script_fspec);
301 break;
302 }
303
304 // If we didn't find the python file, then keep stripping the
305 // extensions and try again
306 ConstString filename_no_extension(
307 module_spec.GetFileNameStrippingExtension());
308 if (module_spec.GetFilename() == filename_no_extension)
309 break;
310
311 module_spec.SetFilename(filename_no_extension);
312 }
313 }
314 }
315 }
316 }
317 }
318 return file_list;
319}
320
322 const ModuleSpec &sym_spec,
323 FileSpec &sym_file) {
324 sym_file = sym_spec.GetSymbolFileSpec();
325 if (FileSystem::Instance().IsDirectory(sym_file)) {
327 sym_file, sym_spec.GetUUIDPtr(), sym_spec.GetArchitecturePtr());
328 }
329 return {};
330}
331
333 const ModuleSpec &module_spec, Process *process, ModuleSP &module_sp,
334 const FileSpecList *module_search_paths_ptr,
335 llvm::SmallVectorImpl<ModuleSP> *old_modules, bool *did_create_ptr) {
337 module_sp.reset();
338
339 if (IsRemote()) {
340 // If we have a remote platform always, let it try and locate the shared
341 // module first.
343 error = m_remote_platform_sp->GetSharedModule(
344 module_spec, process, module_sp, module_search_paths_ptr, old_modules,
345 did_create_ptr);
346 }
347 }
348
349 if (!module_sp) {
350 // Fall back to the local platform and find the file locally
351 error = Platform::GetSharedModule(module_spec, process, module_sp,
352 module_search_paths_ptr, old_modules,
353 did_create_ptr);
354
355 const FileSpec &platform_file = module_spec.GetFileSpec();
356 if (!module_sp && module_search_paths_ptr && platform_file) {
357 // We can try to pull off part of the file path up to the bundle
358 // directory level and try any module search paths...
359 FileSpec bundle_directory;
360 if (Host::GetBundleDirectory(platform_file, bundle_directory)) {
361 if (platform_file == bundle_directory) {
362 ModuleSpec new_module_spec(module_spec);
363 new_module_spec.GetFileSpec() = bundle_directory;
364 if (Host::ResolveExecutableInBundle(new_module_spec.GetFileSpec())) {
366 new_module_spec, process, module_sp, nullptr, old_modules,
367 did_create_ptr));
368
369 if (module_sp)
370 return new_error;
371 }
372 } else {
373 char platform_path[PATH_MAX];
374 char bundle_dir[PATH_MAX];
375 platform_file.GetPath(platform_path, sizeof(platform_path));
376 const size_t bundle_directory_len =
377 bundle_directory.GetPath(bundle_dir, sizeof(bundle_dir));
378 char new_path[PATH_MAX];
379 size_t num_module_search_paths = module_search_paths_ptr->GetSize();
380 for (size_t i = 0; i < num_module_search_paths; ++i) {
381 const size_t search_path_len =
382 module_search_paths_ptr->GetFileSpecAtIndex(i).GetPath(
383 new_path, sizeof(new_path));
384 if (search_path_len < sizeof(new_path)) {
385 snprintf(new_path + search_path_len,
386 sizeof(new_path) - search_path_len, "/%s",
387 platform_path + bundle_directory_len);
388 FileSpec new_file_spec(new_path);
389 if (FileSystem::Instance().Exists(new_file_spec)) {
390 ModuleSpec new_module_spec(module_spec);
391 new_module_spec.GetFileSpec() = new_file_spec;
393 new_module_spec, process, module_sp, nullptr, old_modules,
394 did_create_ptr));
395
396 if (module_sp) {
397 module_sp->SetPlatformFileSpec(new_file_spec);
398 return new_error;
399 }
400 }
401 }
402 }
403 }
404 }
405 }
406 }
407 if (module_sp)
408 module_sp->SetPlatformFileSpec(module_spec.GetFileSpec());
409 return error;
410}
411
412size_t
414 BreakpointSite *bp_site) {
415 const uint8_t *trap_opcode = nullptr;
416 uint32_t trap_opcode_size = 0;
417 bool bp_is_thumb = false;
418
419 llvm::Triple::ArchType machine = target.GetArchitecture().GetMachine();
420 switch (machine) {
421 case llvm::Triple::aarch64_32:
422 case llvm::Triple::aarch64: {
423 // 'brk #0' or 0xd4200000 in BE byte order
424 static const uint8_t g_arm64_breakpoint_opcode[] = {0x00, 0x00, 0x20, 0xD4};
425 trap_opcode = g_arm64_breakpoint_opcode;
426 trap_opcode_size = sizeof(g_arm64_breakpoint_opcode);
427 } break;
428
429 case llvm::Triple::thumb:
430 bp_is_thumb = true;
431 [[fallthrough]];
432 case llvm::Triple::arm: {
433 static const uint8_t g_arm_breakpoint_opcode[] = {0xFE, 0xDE, 0xFF, 0xE7};
434 static const uint8_t g_thumb_breakpooint_opcode[] = {0xFE, 0xDE};
435
436 // Auto detect arm/thumb if it wasn't explicitly specified
437 if (!bp_is_thumb) {
439 if (bp_loc_sp)
440 bp_is_thumb = bp_loc_sp->GetAddress().GetAddressClass() ==
442 }
443 if (bp_is_thumb) {
444 trap_opcode = g_thumb_breakpooint_opcode;
445 trap_opcode_size = sizeof(g_thumb_breakpooint_opcode);
446 break;
447 }
448 trap_opcode = g_arm_breakpoint_opcode;
449 trap_opcode_size = sizeof(g_arm_breakpoint_opcode);
450 } break;
451
452 case llvm::Triple::ppc:
453 case llvm::Triple::ppc64: {
454 static const uint8_t g_ppc_breakpoint_opcode[] = {0x7F, 0xC0, 0x00, 0x08};
455 trap_opcode = g_ppc_breakpoint_opcode;
456 trap_opcode_size = sizeof(g_ppc_breakpoint_opcode);
457 } break;
458
459 default:
460 return Platform::GetSoftwareBreakpointTrapOpcode(target, bp_site);
461 }
462
463 if (trap_opcode && trap_opcode_size) {
464 if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size))
465 return trap_opcode_size;
466 }
467 return 0;
468}
469
471 lldb_private::Target &target, const lldb::ModuleSP &module_sp) {
472 if (!module_sp)
473 return false;
474
475 ObjectFile *obj_file = module_sp->GetObjectFile();
476 if (!obj_file)
477 return false;
478
479 ObjectFile::Type obj_type = obj_file->GetType();
480 return obj_type == ObjectFile::eTypeDynamicLinker;
481}
482
484 std::vector<ArchSpec> &archs) {
485 ArchSpec host_arch = HostInfo::GetArchitecture(HostInfo::eArchKindDefault);
486 archs.push_back(host_arch);
487
488 if (host_arch.GetCore() == ArchSpec::eCore_x86_64_x86_64h) {
489 archs.push_back(ArchSpec("x86_64-apple-macosx"));
490 archs.push_back(HostInfo::GetArchitecture(HostInfo::eArchKind32));
491 } else {
492 ArchSpec host_arch64 = HostInfo::GetArchitecture(HostInfo::eArchKind64);
493 if (host_arch.IsExactMatch(host_arch64))
494 archs.push_back(HostInfo::GetArchitecture(HostInfo::eArchKind32));
495 }
496}
497
498static llvm::ArrayRef<const char *> GetCompatibleArchs(ArchSpec::Core core) {
499 switch (core) {
500 default:
501 [[fallthrough]];
503 static const char *g_arm64e_compatible_archs[] = {
504 "arm64e", "arm64", "armv7", "armv7f", "armv7k", "armv7s",
505 "armv7m", "armv7em", "armv6m", "armv6", "armv5", "armv4",
506 "arm", "thumbv7", "thumbv7f", "thumbv7k", "thumbv7s", "thumbv7m",
507 "thumbv7em", "thumbv6m", "thumbv6", "thumbv5", "thumbv4t", "thumb",
508 };
509 return {g_arm64e_compatible_archs};
510 }
512 static const char *g_arm64_compatible_archs[] = {
513 "arm64", "armv7", "armv7f", "armv7k", "armv7s", "armv7m",
514 "armv7em", "armv6m", "armv6", "armv5", "armv4", "arm",
515 "thumbv7", "thumbv7f", "thumbv7k", "thumbv7s", "thumbv7m", "thumbv7em",
516 "thumbv6m", "thumbv6", "thumbv5", "thumbv4t", "thumb",
517 };
518 return {g_arm64_compatible_archs};
519 }
521 static const char *g_armv7_compatible_archs[] = {
522 "armv7", "armv6m", "armv6", "armv5", "armv4", "arm",
523 "thumbv7", "thumbv6m", "thumbv6", "thumbv5", "thumbv4t", "thumb",
524 };
525 return {g_armv7_compatible_archs};
526 }
528 static const char *g_armv7f_compatible_archs[] = {
529 "armv7f", "armv7", "armv6m", "armv6", "armv5",
530 "armv4", "arm", "thumbv7f", "thumbv7", "thumbv6m",
531 "thumbv6", "thumbv5", "thumbv4t", "thumb",
532 };
533 return {g_armv7f_compatible_archs};
534 }
536 static const char *g_armv7k_compatible_archs[] = {
537 "armv7k", "armv7", "armv6m", "armv6", "armv5",
538 "armv4", "arm", "thumbv7k", "thumbv7", "thumbv6m",
539 "thumbv6", "thumbv5", "thumbv4t", "thumb",
540 };
541 return {g_armv7k_compatible_archs};
542 }
544 static const char *g_armv7s_compatible_archs[] = {
545 "armv7s", "armv7", "armv6m", "armv6", "armv5",
546 "armv4", "arm", "thumbv7s", "thumbv7", "thumbv6m",
547 "thumbv6", "thumbv5", "thumbv4t", "thumb",
548 };
549 return {g_armv7s_compatible_archs};
550 }
552 static const char *g_armv7m_compatible_archs[] = {
553 "armv7m", "armv7", "armv6m", "armv6", "armv5",
554 "armv4", "arm", "thumbv7m", "thumbv7", "thumbv6m",
555 "thumbv6", "thumbv5", "thumbv4t", "thumb",
556 };
557 return {g_armv7m_compatible_archs};
558 }
560 static const char *g_armv7em_compatible_archs[] = {
561 "armv7em", "armv7", "armv6m", "armv6", "armv5",
562 "armv4", "arm", "thumbv7em", "thumbv7", "thumbv6m",
563 "thumbv6", "thumbv5", "thumbv4t", "thumb",
564 };
565 return {g_armv7em_compatible_archs};
566 }
568 static const char *g_armv6m_compatible_archs[] = {
569 "armv6m", "armv6", "armv5", "armv4", "arm",
570 "thumbv6m", "thumbv6", "thumbv5", "thumbv4t", "thumb",
571 };
572 return {g_armv6m_compatible_archs};
573 }
575 static const char *g_armv6_compatible_archs[] = {
576 "armv6", "armv5", "armv4", "arm",
577 "thumbv6", "thumbv5", "thumbv4t", "thumb",
578 };
579 return {g_armv6_compatible_archs};
580 }
582 static const char *g_armv5_compatible_archs[] = {
583 "armv5", "armv4", "arm", "thumbv5", "thumbv4t", "thumb",
584 };
585 return {g_armv5_compatible_archs};
586 }
588 static const char *g_armv4_compatible_archs[] = {
589 "armv4",
590 "arm",
591 "thumbv4t",
592 "thumb",
593 };
594 return {g_armv4_compatible_archs};
595 }
596 }
597 return {};
598}
599
600/// The architecture selection rules for arm processors These cpu subtypes have
601/// distinct names (e.g. armv7f) but armv7 binaries run fine on an armv7f
602/// processor.
604 std::vector<ArchSpec> &archs, std::optional<llvm::Triple::OSType> os) {
605 const ArchSpec system_arch = GetSystemArchitecture();
606 const ArchSpec::Core system_core = system_arch.GetCore();
607 for (const char *arch : GetCompatibleArchs(system_core)) {
608 llvm::Triple triple;
609 triple.setArchName(arch);
610 triple.setVendor(llvm::Triple::VendorType::Apple);
611 if (os)
612 triple.setOS(*os);
613 archs.push_back(ArchSpec(triple));
614 }
615}
616
618 static FileSpec g_xcode_select_filespec;
619
620 if (!g_xcode_select_filespec) {
621 FileSpec xcode_select_cmd("/usr/bin/xcode-select");
622 if (FileSystem::Instance().Exists(xcode_select_cmd)) {
623 int exit_status = -1;
624 int signo = -1;
625 std::string command_output;
626 Status status =
627 Host::RunShellCommand("/usr/bin/xcode-select --print-path",
628 FileSpec(), // current working directory
629 &exit_status, &signo, &command_output,
630 std::chrono::seconds(2), // short timeout
631 false); // don't run in a shell
632 if (status.Success() && exit_status == 0 && !command_output.empty()) {
633 size_t first_non_newline = command_output.find_last_not_of("\r\n");
634 if (first_non_newline != std::string::npos) {
635 command_output.erase(first_non_newline + 1);
636 }
637 g_xcode_select_filespec = FileSpec(command_output);
638 }
639 }
640 }
641
642 return g_xcode_select_filespec;
643}
644
646 BreakpointSP bp_sp;
647 static const char *g_bp_names[] = {
648 "start_wqthread", "_pthread_wqthread", "_pthread_start",
649 };
650
651 static const char *g_bp_modules[] = {"libsystem_c.dylib", "libSystem.B.dylib",
652 "libsystem_pthread.dylib"};
653
654 FileSpecList bp_modules;
655 for (size_t i = 0; i < std::size(g_bp_modules); i++) {
656 const char *bp_module = g_bp_modules[i];
657 bp_modules.EmplaceBack(bp_module);
658 }
659
660 bool internal = true;
661 bool hardware = false;
662 LazyBool skip_prologue = eLazyBoolNo;
663 bp_sp = target.CreateBreakpoint(&bp_modules, nullptr, g_bp_names,
664 std::size(g_bp_names), eFunctionNameTypeFull,
665 eLanguageTypeUnknown, 0, skip_prologue,
666 internal, hardware);
667 bp_sp->SetBreakpointKind("thread-creation");
668
669 return bp_sp;
670}
671
672uint32_t
674 const FileSpec &shell = launch_info.GetShell();
675 if (!shell)
676 return 1;
677
678 std::string shell_string = shell.GetPath();
679 const char *shell_name = strrchr(shell_string.c_str(), '/');
680 if (shell_name == nullptr)
681 shell_name = shell_string.c_str();
682 else
683 shell_name++;
684
685 if (strcmp(shell_name, "sh") == 0) {
686 // /bin/sh re-exec's itself as /bin/bash requiring another resume. But it
687 // only does this if the COMMAND_MODE environment variable is set to
688 // "legacy".
689 if (launch_info.GetEnvironment().lookup("COMMAND_MODE") == "legacy")
690 return 2;
691 return 1;
692 } else if (strcmp(shell_name, "csh") == 0 ||
693 strcmp(shell_name, "tcsh") == 0 ||
694 strcmp(shell_name, "zsh") == 0) {
695 // csh and tcsh always seem to re-exec themselves.
696 return 2;
697 } else
698 return 1;
699}
700
702 Debugger &debugger, Target &target,
703 Status &error) {
704 ProcessSP process_sp;
705
706 if (IsHost()) {
707 // We are going to hand this process off to debugserver which will be in
708 // charge of setting the exit status. However, we still need to reap it
709 // from lldb. So, make sure we use a exit callback which does not set exit
710 // status.
711 launch_info.SetMonitorProcessCallback(
713 process_sp = Platform::DebugProcess(launch_info, debugger, target, error);
714 } else {
716 process_sp = m_remote_platform_sp->DebugProcess(launch_info, debugger,
717 target, error);
718 else
719 error =
720 Status::FromErrorString("the platform is not currently connected");
721 }
722 return process_sp;
723}
724
728
730 static FileSpec g_command_line_tools_filespec;
731
732 if (!g_command_line_tools_filespec) {
733 FileSpec command_line_tools_path(GetXcodeSelectPath());
734 command_line_tools_path.AppendPathComponent("Library");
735 if (FileSystem::Instance().Exists(command_line_tools_path)) {
736 g_command_line_tools_filespec = command_line_tools_path;
737 }
738 }
739
740 return g_command_line_tools_filespec;
741}
742
744 void *baton, llvm::sys::fs::file_type file_type, llvm::StringRef path) {
745 SDKEnumeratorInfo *enumerator_info = static_cast<SDKEnumeratorInfo *>(baton);
746
747 FileSpec spec(path);
748 if (XcodeSDK::SDKSupportsModules(enumerator_info->sdk_type, spec)) {
749 enumerator_info->found_path = spec;
751 }
752
754}
755
757 const FileSpec &sdks_spec) {
758 // Look inside Xcode for the required installed iOS SDK version
759
760 if (!FileSystem::Instance().IsDirectory(sdks_spec)) {
761 return FileSpec();
762 }
763
764 const bool find_directories = true;
765 const bool find_files = false;
766 const bool find_other = true; // include symlinks
767
768 SDKEnumeratorInfo enumerator_info;
769
770 enumerator_info.sdk_type = sdk_type;
771
773 sdks_spec.GetPath(), find_directories, find_files, find_other,
774 DirectoryEnumerator, &enumerator_info);
775
776 if (FileSystem::Instance().IsDirectory(enumerator_info.found_path))
777 return enumerator_info.found_path;
778 else
779 return FileSpec();
780}
781
783 FileSpec sdks_spec = HostInfo::GetXcodeContentsDirectory();
784 sdks_spec.AppendPathComponent("Developer");
785 sdks_spec.AppendPathComponent("Platforms");
786
787 switch (sdk_type) {
789 sdks_spec.AppendPathComponent("MacOSX.platform");
790 break;
792 sdks_spec.AppendPathComponent("iPhoneSimulator.platform");
793 break;
795 sdks_spec.AppendPathComponent("iPhoneOS.platform");
796 break;
798 sdks_spec.AppendPathComponent("WatchSimulator.platform");
799 break;
801 sdks_spec.AppendPathComponent("AppleTVSimulator.platform");
802 break;
804 sdks_spec.AppendPathComponent("XRSimulator.platform");
805 break;
806 default:
807 llvm_unreachable("unsupported sdk");
808 }
809
810 sdks_spec.AppendPathComponent("Developer");
811 sdks_spec.AppendPathComponent("SDKs");
812
813 if (sdk_type == XcodeSDK::Type::MacOSX) {
814 llvm::VersionTuple version = HostInfo::GetOSVersion();
815
816 if (!version.empty()) {
818 // If the Xcode SDKs are not available then try to use the
819 // Command Line Tools one which is only for MacOSX.
820 if (!FileSystem::Instance().Exists(sdks_spec)) {
821 sdks_spec = GetCommandLineToolsLibraryPath();
822 sdks_spec.AppendPathComponent("SDKs");
823 }
824
825 // We slightly prefer the exact SDK for this machine. See if it is
826 // there.
827
828 FileSpec native_sdk_spec = sdks_spec;
829 StreamString native_sdk_name;
830 native_sdk_name.Printf("MacOSX%u.%u.sdk", version.getMajor(),
831 version.getMinor().value_or(0));
832 native_sdk_spec.AppendPathComponent(native_sdk_name.GetString());
833
834 if (FileSystem::Instance().Exists(native_sdk_spec)) {
835 return native_sdk_spec;
836 }
837 }
838 }
839 }
840
841 return FindSDKInXcodeForModules(sdk_type, sdks_spec);
842}
843
844std::tuple<llvm::VersionTuple, llvm::StringRef>
846 llvm::StringRef build;
847 llvm::StringRef version_str;
848 llvm::StringRef build_str;
849 std::tie(version_str, build_str) = dir.split(' ');
850 llvm::VersionTuple version;
851 if (!version.tryParse(version_str) ||
852 build_str.empty()) {
853 if (build_str.consume_front("(")) {
854 size_t pos = build_str.find(')');
855 build = build_str.slice(0, pos);
856 }
857 }
858
859 return std::make_tuple(version, build);
860}
861
862llvm::Expected<StructuredData::DictionarySP>
864 static constexpr llvm::StringLiteral crash_info_key("Crash-Info Annotations");
865 static constexpr llvm::StringLiteral asi_info_key(
866 "Application Specific Information");
867
868 // We cache the information we find in the process extended info dict:
869 StructuredData::DictionarySP process_dict_sp =
870 process.GetExtendedCrashInfoDict();
871 StructuredData::Array *annotations = nullptr;
872 StructuredData::ArraySP new_annotations_sp;
873 if (!process_dict_sp->GetValueForKeyAsArray(crash_info_key, annotations)) {
874 new_annotations_sp = ExtractCrashInfoAnnotations(process);
875 if (new_annotations_sp && new_annotations_sp->GetSize()) {
876 process_dict_sp->AddItem(crash_info_key, new_annotations_sp);
877 annotations = new_annotations_sp.get();
878 }
879 }
880
881 StructuredData::Dictionary *app_specific_info;
882 StructuredData::DictionarySP new_app_specific_info_sp;
883 if (!process_dict_sp->GetValueForKeyAsDictionary(asi_info_key,
884 app_specific_info)) {
885 new_app_specific_info_sp = ExtractAppSpecificInfo(process);
886 if (new_app_specific_info_sp && new_app_specific_info_sp->GetSize()) {
887 process_dict_sp->AddItem(asi_info_key, new_app_specific_info_sp);
888 app_specific_info = new_app_specific_info_sp.get();
889 }
890 }
891
892 // Now get anything else that was in the process info dict, and add it to the
893 // return here:
894 return process_dict_sp->GetSize() ? process_dict_sp : nullptr;
895}
896
900
901 ConstString section_name("__crash_info");
902 Target &target = process.GetTarget();
903 StructuredData::ArraySP array_sp = std::make_shared<StructuredData::Array>();
904
905 for (ModuleSP module : target.GetImages().Modules()) {
906 SectionList *sections = module->GetSectionList();
907
908 std::string module_name = module->GetSpecificationDescription();
909
910 // The DYDL module is skipped since it's always loaded when running the
911 // binary.
912 if (module_name == "/usr/lib/dyld")
913 continue;
914
915 if (!sections) {
916 LLDB_LOG(log, "Module {0} doesn't have any section!", module_name);
917 continue;
918 }
919
920 SectionSP crash_info = sections->FindSectionByName(section_name);
921 if (!crash_info) {
922 LLDB_LOG(log, "Module {0} doesn't have section {1}!", module_name,
923 section_name);
924 continue;
925 }
926
927 addr_t load_addr = crash_info->GetLoadBaseAddress(&target);
928
929 if (load_addr == LLDB_INVALID_ADDRESS) {
930 LLDB_LOG(log, "Module {0} has an invalid '{1}' section load address: {2}",
931 module_name, section_name, load_addr);
932 continue;
933 }
934
936 CrashInfoAnnotations annotations;
937 size_t expected_size = sizeof(CrashInfoAnnotations);
938 size_t bytes_read = process.ReadMemoryFromInferior(load_addr, &annotations,
939 expected_size, error);
940
941 if (expected_size != bytes_read || error.Fail()) {
942 LLDB_LOG(log, "Failed to read {0} section from memory in module {1}: {2}",
943 section_name, module_name, error);
944 continue;
945 }
946
947 // initial support added for version 5
948 if (annotations.version < 5) {
949 LLDB_LOG(log,
950 "Annotation version lower than 5 unsupported! Module {0} has "
951 "version {1} instead.",
952 module_name, annotations.version);
953 continue;
954 }
955
956 if (!annotations.message) {
957 LLDB_LOG(log, "No message available for module {0}.", module_name);
958 continue;
959 }
960
961 std::string message;
962 bytes_read =
963 process.ReadCStringFromMemory(annotations.message, message, error);
964
965 if (message.empty() || bytes_read != message.size() || error.Fail()) {
966 LLDB_LOG(log, "Failed to read the message from memory in module {0}: {1}",
967 module_name, error);
968 continue;
969 }
970
971 // Remove trailing newline from message
972 if (message.back() == '\n')
973 message.pop_back();
974
975 if (!annotations.message2)
976 LLDB_LOG(log, "No message2 available for module {0}.", module_name);
977
978 std::string message2;
979 bytes_read =
980 process.ReadCStringFromMemory(annotations.message2, message2, error);
981
982 if (!message2.empty() && bytes_read == message2.size() && error.Success())
983 if (message2.back() == '\n')
984 message2.pop_back();
985
987 std::make_shared<StructuredData::Dictionary>();
988
989 entry_sp->AddStringItem("image", module->GetFileSpec().GetPath(false));
990 entry_sp->AddStringItem("uuid", module->GetUUID().GetAsString());
991 entry_sp->AddStringItem("message", message);
992 entry_sp->AddStringItem("message2", message2);
993 entry_sp->AddIntegerItem("abort-cause", annotations.abort_cause);
994
995 array_sp->AddItem(entry_sp);
996 }
997
998 return array_sp;
999}
1000
1003 StructuredData::DictionarySP metadata_sp = process.GetMetadata();
1004
1005 if (!metadata_sp || !metadata_sp->GetSize() || !metadata_sp->HasKey("asi"))
1006 return {};
1007
1009 if (!metadata_sp->GetValueForKeyAsDictionary("asi", asi))
1010 return {};
1011
1013 std::make_shared<StructuredData::Dictionary>();
1014
1015 auto flatten_asi_dict = [&dict_sp](llvm::StringRef key,
1016 StructuredData::Object *val) -> bool {
1017 if (!val)
1018 return false;
1019
1020 StructuredData::Array *arr = val->GetAsArray();
1021 if (!arr || !arr->GetSize())
1022 return false;
1023
1024 dict_sp->AddItem(key, arr->GetItemAtIndex(0));
1025 return true;
1026 };
1027
1028 asi->ForEach(flatten_asi_dict);
1029
1030 return dict_sp;
1031}
1032
1033static llvm::Expected<lldb_private::FileSpec>
1035
1036 ModuleSP exe_module_sp = target->GetExecutableModule();
1037 if (!exe_module_sp)
1038 return llvm::createStringError("Failed to get module from target");
1039
1040 SymbolFile *sym_file = exe_module_sp->GetSymbolFile();
1041 if (!sym_file)
1042 return llvm::createStringError("Failed to get symbol file from executable");
1043
1044 if (sym_file->GetNumCompileUnits() == 0)
1045 return llvm::createStringError(
1046 "Failed to resolve SDK for target: executable's symbol file has no "
1047 "compile units");
1048
1049 XcodeSDK merged_sdk;
1050 for (unsigned i = 0; i < sym_file->GetNumCompileUnits(); ++i) {
1051 if (auto cu_sp = sym_file->GetCompileUnitAtIndex(i)) {
1052 auto cu_sdk = sym_file->ParseXcodeSDK(*cu_sp);
1053 merged_sdk.Merge(cu_sdk);
1054 }
1055 }
1056
1057 // TODO: The result of this loop is almost equivalent to deriving the SDK
1058 // from the target triple, which would be a lot cheaper.
1059 FileSpec sdk_path = merged_sdk.GetSysroot();
1060 if (FileSystem::Instance().Exists(sdk_path)) {
1061 return sdk_path;
1062 }
1063 auto path_or_err = HostInfo::GetSDKRoot(HostInfo::SDKOptions{merged_sdk});
1064 if (!path_or_err)
1065 return llvm::createStringError(
1066 llvm::formatv("Failed to resolve SDK path: {0}",
1067 llvm::toString(path_or_err.takeError())));
1068
1069 return FileSpec(*path_or_err);
1070}
1071
1073 Target *target, std::vector<std::string> &options, XcodeSDK::Type sdk_type) {
1074 const std::vector<std::string> apple_arguments = {
1075 "-x", "objective-c++", "-fobjc-arc",
1076 "-fblocks", "-D_ISO646_H", "-D__ISO646_H",
1077 "-fgnuc-version=4.2.1"};
1078
1079 options.insert(options.end(), apple_arguments.begin(), apple_arguments.end());
1080
1081 StreamString minimum_version_option;
1082 bool use_current_os_version = false;
1083 // If the SDK type is for the host OS, use its version number.
1084 auto get_host_os = []() { return HostInfo::GetTargetTriple().getOS(); };
1085 switch (sdk_type) {
1087 use_current_os_version = get_host_os() == llvm::Triple::MacOSX;
1088 break;
1090 use_current_os_version = get_host_os() == llvm::Triple::IOS;
1091 break;
1093 use_current_os_version = get_host_os() == llvm::Triple::TvOS;
1094 break;
1096 use_current_os_version = get_host_os() == llvm::Triple::WatchOS;
1097 break;
1099 use_current_os_version = get_host_os() == llvm::Triple::XROS;
1100 break;
1101 default:
1102 break;
1103 }
1104
1105 llvm::VersionTuple version;
1106 if (use_current_os_version)
1107 version = GetOSVersion();
1108 else if (target) {
1109 // Our OS doesn't match our executable so we need to get the min OS version
1110 // from the object file
1111 ModuleSP exe_module_sp = target->GetExecutableModule();
1112 if (exe_module_sp) {
1113 ObjectFile *object_file = exe_module_sp->GetObjectFile();
1114 if (object_file)
1115 version = object_file->GetMinimumOSVersion();
1116 }
1117 }
1118 // Only add the version-min options if we got a version from somewhere.
1119 // clang has no version-min clang flag for XROS.
1120 if (!version.empty() && sdk_type != XcodeSDK::Type::Linux &&
1121 sdk_type != XcodeSDK::Type::XROS) {
1122#define OPTION(PREFIX_OFFSET, NAME_OFFSET, VAR, ...) \
1123 llvm::StringRef opt_##VAR = OptionStrTable[NAME_OFFSET]; \
1124 (void)opt_##VAR;
1125#include "clang/Driver/Options.inc"
1126#undef OPTION
1127 minimum_version_option << '-';
1128 switch (sdk_type) {
1130 minimum_version_option << opt_mmacos_version_min_EQ;
1131 break;
1133 minimum_version_option << opt_mios_simulator_version_min_EQ;
1134 break;
1136 minimum_version_option << opt_mios_version_min_EQ;
1137 break;
1139 minimum_version_option << opt_mtvos_simulator_version_min_EQ;
1140 break;
1142 minimum_version_option << opt_mtvos_version_min_EQ;
1143 break;
1145 minimum_version_option << opt_mwatchos_simulator_version_min_EQ;
1146 break;
1148 minimum_version_option << opt_mwatchos_version_min_EQ;
1149 break;
1152 // FIXME: Pass the right argument once it exists.
1156 if (Log *log = GetLog(LLDBLog::Host)) {
1157 XcodeSDK::Info info;
1158 info.type = sdk_type;
1159 LLDB_LOGF(log, "Clang modules on %s are not supported",
1160 XcodeSDK::GetCanonicalName(info).c_str());
1161 }
1162 return;
1163 }
1164 minimum_version_option << version.getAsString();
1165 options.emplace_back(std::string(minimum_version_option.GetString()));
1166 }
1167
1168 FileSpec sysroot_spec;
1169
1170 if (target) {
1171 auto sysroot_spec_or_err = ::ResolveSDKPathFromDebugInfo(target);
1172 if (!sysroot_spec_or_err) {
1174 sysroot_spec_or_err.takeError(),
1175 "Failed to resolve sysroot: {0}");
1176 } else {
1177 sysroot_spec = *sysroot_spec_or_err;
1178 }
1179 }
1180
1181 if (!FileSystem::Instance().IsDirectory(sysroot_spec.GetPath())) {
1182 std::lock_guard<std::mutex> guard(m_mutex);
1183 sysroot_spec = GetSDKDirectoryForModules(sdk_type);
1184 }
1185
1186 if (FileSystem::Instance().IsDirectory(sysroot_spec.GetPath())) {
1187 options.push_back("-isysroot");
1188 options.push_back(sysroot_spec.GetPath());
1189 }
1190}
1191
1193 if (basename.IsEmpty())
1194 return basename;
1195
1196 StreamString stream;
1197 stream.Printf("lib%s.dylib", basename.GetCString());
1198 return ConstString(stream.GetString());
1199}
1200
1201llvm::VersionTuple PlatformDarwin::GetOSVersion(Process *process) {
1202 if (process && GetPluginName().contains("-simulator")) {
1204 if (Host::GetProcessInfo(process->GetID(), proc_info)) {
1205 const Environment &env = proc_info.GetEnvironment();
1206
1207 llvm::VersionTuple result;
1208 if (!result.tryParse(env.lookup("SIMULATOR_RUNTIME_VERSION")))
1209 return result;
1210
1211 std::string dyld_root_path = env.lookup("DYLD_ROOT_PATH");
1212 if (!dyld_root_path.empty()) {
1213 dyld_root_path += "/System/Library/CoreServices/SystemVersion.plist";
1214 ApplePropertyList system_version_plist(dyld_root_path.c_str());
1215 std::string product_version;
1216 if (system_version_plist.GetValueAsString("ProductVersion",
1217 product_version)) {
1218 if (!result.tryParse(product_version))
1219 return result;
1220 }
1221 }
1222 }
1223 // For simulator platforms, do NOT call back through
1224 // Platform::GetOSVersion() as it might call Process::GetHostOSVersion()
1225 // which we don't want as it will be incorrect
1226 return llvm::VersionTuple();
1227 }
1228
1229 return Platform::GetOSVersion(process);
1230}
1231
1233 // A collection of SBFileSpec whose SBFileSpec.m_directory members are filled
1234 // in with any executable directories that should be searched.
1235 static std::vector<FileSpec> g_executable_dirs;
1236
1237 // Find the global list of directories that we will search for executables
1238 // once so we don't keep doing the work over and over.
1239 static llvm::once_flag g_once_flag;
1240 llvm::call_once(g_once_flag, []() {
1241
1242 // When locating executables, trust the DEVELOPER_DIR first if it is set
1243 FileSpec xcode_contents_dir = HostInfo::GetXcodeContentsDirectory();
1244 if (xcode_contents_dir) {
1245 FileSpec xcode_lldb_resources = xcode_contents_dir;
1246 xcode_lldb_resources.AppendPathComponent("SharedFrameworks");
1247 xcode_lldb_resources.AppendPathComponent("LLDB.framework");
1248 xcode_lldb_resources.AppendPathComponent("Resources");
1249 if (FileSystem::Instance().Exists(xcode_lldb_resources)) {
1250 FileSpec dir;
1251 dir.SetDirectory(xcode_lldb_resources.GetPathAsConstString());
1252 g_executable_dirs.push_back(dir);
1253 }
1254 }
1255 // Xcode might not be installed so we also check for the Command Line Tools.
1256 FileSpec command_line_tools_dir = GetCommandLineToolsLibraryPath();
1257 if (command_line_tools_dir) {
1258 FileSpec cmd_line_lldb_resources = command_line_tools_dir;
1259 cmd_line_lldb_resources.AppendPathComponent("PrivateFrameworks");
1260 cmd_line_lldb_resources.AppendPathComponent("LLDB.framework");
1261 cmd_line_lldb_resources.AppendPathComponent("Resources");
1262 if (FileSystem::Instance().Exists(cmd_line_lldb_resources)) {
1263 FileSpec dir;
1264 dir.SetDirectory(cmd_line_lldb_resources.GetPathAsConstString());
1265 g_executable_dirs.push_back(dir);
1266 }
1267 }
1268 });
1269
1270 // Now search the global list of executable directories for the executable we
1271 // are looking for
1272 for (const auto &executable_dir : g_executable_dirs) {
1273 FileSpec executable_file;
1274 executable_file.SetDirectory(executable_dir.GetDirectory());
1275 executable_file.SetFilename(basename);
1276 if (FileSystem::Instance().Exists(executable_file))
1277 return executable_file;
1278 }
1279
1280 return FileSpec();
1281}
1282
1285 // Starting in Fall 2016 OSes, NSLog messages only get mirrored to stderr if
1286 // the OS_ACTIVITY_DT_MODE environment variable is set. (It doesn't require
1287 // any specific value; rather, it just needs to exist). We will set it here
1288 // as long as the IDE_DISABLED_OS_ACTIVITY_DT_MODE flag is not set. Xcode
1289 // makes use of IDE_DISABLED_OS_ACTIVITY_DT_MODE to tell
1290 // LLDB *not* to muck with the OS_ACTIVITY_DT_MODE flag when they
1291 // specifically want it unset.
1292 const char *disable_env_var = "IDE_DISABLED_OS_ACTIVITY_DT_MODE";
1293 auto &env_vars = launch_info.GetEnvironment();
1294 if (!env_vars.count(disable_env_var)) {
1295 // We want to make sure that OS_ACTIVITY_DT_MODE is set so that we get
1296 // os_log and NSLog messages mirrored to the target process stderr.
1297 env_vars.try_emplace("OS_ACTIVITY_DT_MODE", "enable");
1298 }
1299
1300 // Let our parent class do the real launching.
1301 return PlatformPOSIX::LaunchProcess(launch_info);
1302}
1303
1305 const ModuleSpec &module_spec, Process *process, ModuleSP &module_sp,
1306 const FileSpecList *module_search_paths_ptr,
1307 llvm::SmallVectorImpl<ModuleSP> *old_modules, bool *did_create_ptr) {
1308 const FileSpec &platform_file = module_spec.GetFileSpec();
1309 // See if the file is present in any of the module_search_paths_ptr
1310 // directories.
1311 if (!module_sp && module_search_paths_ptr && platform_file) {
1312 // create a vector of all the file / directory names in platform_file e.g.
1313 // this might be
1314 // /System/Library/PrivateFrameworks/UIFoundation.framework/UIFoundation
1315 //
1316 // We'll need to look in the module_search_paths_ptr directories for both
1317 // "UIFoundation" and "UIFoundation.framework" -- most likely the latter
1318 // will be the one we find there.
1319
1320 std::vector<llvm::StringRef> path_parts = platform_file.GetComponents();
1321 // We want the components in reverse order.
1322 std::reverse(path_parts.begin(), path_parts.end());
1323 const size_t path_parts_size = path_parts.size();
1324
1325 size_t num_module_search_paths = module_search_paths_ptr->GetSize();
1326 for (size_t i = 0; i < num_module_search_paths; ++i) {
1327 Log *log_verbose = GetLog(LLDBLog::Host);
1328 LLDB_LOGF(
1329 log_verbose,
1330 "PlatformRemoteDarwinDevice::GetSharedModule searching for binary in "
1331 "search-path %s",
1332 module_search_paths_ptr->GetFileSpecAtIndex(i).GetPath().c_str());
1333 // Create a new FileSpec with this module_search_paths_ptr plus just the
1334 // filename ("UIFoundation"), then the parent dir plus filename
1335 // ("UIFoundation.framework/UIFoundation") etc - up to four names (to
1336 // handle "Foo.framework/Contents/MacOS/Foo")
1337
1338 for (size_t j = 0; j < 4 && j < path_parts_size - 1; ++j) {
1339 FileSpec path_to_try(module_search_paths_ptr->GetFileSpecAtIndex(i));
1340
1341 // Add the components backwards. For
1342 // .../PrivateFrameworks/UIFoundation.framework/UIFoundation path_parts
1343 // is
1344 // [0] UIFoundation
1345 // [1] UIFoundation.framework
1346 // [2] PrivateFrameworks
1347 //
1348 // and if 'j' is 2, we want to append path_parts[1] and then
1349 // path_parts[0], aka 'UIFoundation.framework/UIFoundation', to the
1350 // module_search_paths_ptr path.
1351
1352 for (int k = j; k >= 0; --k) {
1353 path_to_try.AppendPathComponent(path_parts[k]);
1354 }
1355
1356 if (FileSystem::Instance().Exists(path_to_try)) {
1357 ModuleSpec new_module_spec(module_spec);
1358 new_module_spec.GetFileSpec() = path_to_try;
1359 Status new_error(
1360 Platform::GetSharedModule(new_module_spec, process, module_sp,
1361 nullptr, old_modules, did_create_ptr));
1362
1363 if (module_sp) {
1364 module_sp->SetPlatformFileSpec(path_to_try);
1365 return new_error;
1366 }
1367 }
1368 }
1369 }
1370 }
1371 return Status();
1372}
1373
1374llvm::Triple::OSType PlatformDarwin::GetHostOSType() {
1375#if !defined(__APPLE__)
1376 return llvm::Triple::MacOSX;
1377#else
1378#if TARGET_OS_OSX
1379 return llvm::Triple::MacOSX;
1380#elif TARGET_OS_IOS
1381 return llvm::Triple::IOS;
1382#elif TARGET_OS_WATCH
1383 return llvm::Triple::WatchOS;
1384#elif TARGET_OS_TV
1385 return llvm::Triple::TvOS;
1386#elif TARGET_OS_BRIDGE
1387 return llvm::Triple::BridgeOS;
1388#elif TARGET_OS_XR
1389 return llvm::Triple::XROS;
1390#else
1391#error "LLDB being compiled for an unrecognized Darwin OS"
1392#endif
1393#endif // __APPLE__
1394}
1395
1396llvm::Expected<std::pair<XcodeSDK, bool>>
1398 SymbolFile *sym_file = module.GetSymbolFile();
1399 if (!sym_file)
1400 return llvm::createStringError(
1401 llvm::inconvertibleErrorCode(),
1402 llvm::formatv("No symbol file available for module '{0}'",
1403 module.GetFileSpec().GetFilename().AsCString("")));
1404
1405 if (sym_file->GetNumCompileUnits() == 0)
1406 return llvm::createStringError(
1407 llvm::formatv("Could not resolve SDK for module '{0}'. Symbol file has "
1408 "no compile units.",
1409 module.GetFileSpec()));
1410
1411 bool found_public_sdk = false;
1412 bool found_internal_sdk = false;
1413 XcodeSDK merged_sdk;
1414 for (unsigned i = 0; i < sym_file->GetNumCompileUnits(); ++i) {
1415 if (auto cu_sp = sym_file->GetCompileUnitAtIndex(i)) {
1416 auto cu_sdk = sym_file->ParseXcodeSDK(*cu_sp);
1417 bool is_internal_sdk = cu_sdk.IsAppleInternalSDK();
1418 found_public_sdk |= !is_internal_sdk;
1419 found_internal_sdk |= is_internal_sdk;
1420
1421 merged_sdk.Merge(cu_sdk);
1422 }
1423 }
1424
1425 const bool found_mismatch = found_internal_sdk && found_public_sdk;
1426
1427 return std::pair{std::move(merged_sdk), found_mismatch};
1428}
1429
1430llvm::Expected<std::string>
1432 auto sdk_or_err = GetSDKPathFromDebugInfo(module);
1433 if (!sdk_or_err)
1434 return llvm::createStringError(
1435 llvm::inconvertibleErrorCode(),
1436 llvm::formatv("Failed to parse SDK path from debug-info: {0}",
1437 llvm::toString(sdk_or_err.takeError())));
1438
1439 auto [sdk, _] = std::move(*sdk_or_err);
1440
1441 if (FileSystem::Instance().Exists(sdk.GetSysroot()))
1442 return sdk.GetSysroot().GetPath();
1443
1444 auto path_or_err = HostInfo::GetSDKRoot(HostInfo::SDKOptions{sdk});
1445 if (!path_or_err)
1446 return llvm::createStringError(
1447 llvm::inconvertibleErrorCode(),
1448 llvm::formatv("Error while searching for SDK (XcodeSDK '{0}'): {1}",
1449 sdk.GetString(),
1450 llvm::toString(path_or_err.takeError())));
1451
1452 return path_or_err->str();
1453}
1454
1455llvm::Expected<XcodeSDK>
1457 ModuleSP module_sp = unit.CalculateSymbolContextModule();
1458 if (!module_sp)
1459 return llvm::createStringError("compile unit has no module");
1460 SymbolFile *sym_file = module_sp->GetSymbolFile();
1461 if (!sym_file)
1462 return llvm::createStringError(
1463 llvm::formatv("No symbol file available for module '{0}'",
1464 module_sp->GetFileSpec().GetFilename()));
1465
1466 return sym_file->ParseXcodeSDK(unit);
1467}
1468
1469llvm::Expected<std::string>
1471 auto sdk_or_err = GetSDKPathFromDebugInfo(unit);
1472 if (!sdk_or_err)
1473 return llvm::createStringError(
1474 llvm::inconvertibleErrorCode(),
1475 llvm::formatv("Failed to parse SDK path from debug-info: {0}",
1476 llvm::toString(sdk_or_err.takeError())));
1477
1478 auto sdk = std::move(*sdk_or_err);
1479
1480 auto path_or_err = HostInfo::GetSDKRoot(HostInfo::SDKOptions{sdk});
1481 if (!path_or_err)
1482 return llvm::createStringError(
1483 llvm::inconvertibleErrorCode(),
1484 llvm::formatv("Error while searching for SDK (XcodeSDK '{0}'): {1}",
1485 sdk.GetString(),
1486 llvm::toString(path_or_err.takeError())));
1487
1488 return path_or_err->str();
1489}
static llvm::raw_ostream & error(Stream &strm)
static DynamicLoaderDarwinKernelProperties & GetGlobalProperties()
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:369
#define LLDB_LOGF(log,...)
Definition Log.h:376
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:392
static uint32_t g_initialize_count
static llvm::Expected< lldb_private::FileSpec > ResolveSDKPathFromDebugInfo(lldb_private::Target *target)
static Status ExceptionMaskValidator(const char *string, void *unused)
static llvm::ArrayRef< const char * > GetCompatibleArchs(ArchSpec::Core core)
static FileSpec GetXcodeSelectPath()
static FileSpec GetCommandLineToolsLibraryPath()
static llvm::StringRef GetSettingName()
OptionValueString * GetIgnoredExceptionValue()
const char * GetIgnoredExceptions() const
~PlatformDarwinProperties() override=default
lldb_private::Status PutFile(const lldb_private::FileSpec &source, const lldb_private::FileSpec &destination, uint32_t uid=UINT32_MAX, uint32_t gid=UINT32_MAX) override
bool GetValueAsString(const char *key, std::string &value) const
Definition XML.cpp:404
An architecture specification class.
Definition ArchSpec.h:31
bool IsExactMatch(const ArchSpec &rhs) const
Shorthand for IsMatch(rhs, ExactMatch).
Definition ArchSpec.h:515
llvm::Triple::ArchType GetMachine() const
Returns a machine family for the current architecture.
Definition ArchSpec.cpp:677
Core GetCore() const
Definition ArchSpec.h:447
A command line argument class.
Definition Args.h:33
void AppendArgument(llvm::StringRef arg_str, char quote_char='\0')
Appends a new argument to the end of the list argument list.
Definition Args.cpp:332
Class that manages the actual breakpoint that will be inserted into the running program.
bool SetTrapOpcode(const uint8_t *trap_opcode, uint32_t trap_opcode_size)
Sets the trap opcode.
lldb::BreakpointLocationSP GetConstituentAtIndex(size_t idx)
This method returns the breakpoint location at index index located at this breakpoint site.
A class that describes a compilation unit.
Definition CompileUnit.h:43
lldb::ModuleSP CalculateSymbolContextModule() override
A uniqued constant string class.
Definition ConstString.h:40
const char * AsCString(const char *value_if_empty=nullptr) const
Get the string value as a C string.
bool IsEmpty() const
Test for empty string.
const char * GetCString() const
Get the string value as a C string.
A class to manage flag bits.
Definition Debugger.h:80
lldb::ScriptLanguage GetScriptLanguage() const
Definition Debugger.cpp:366
ScriptInterpreter * GetScriptInterpreter(bool can_create=true, std::optional< lldb::ScriptLanguage > language={})
A file collection class.
const FileSpec & GetFileSpecAtIndex(size_t idx) const
Get file at index.
void EmplaceBack(Args &&...args)
Inserts a new FileSpec into the FileSpecList constructed in-place with the given arguments.
void Append(const FileSpec &file)
Append a FileSpec object to the list.
size_t GetSize() const
Get the number of files in the file list.
A file utility class.
Definition FileSpec.h:57
void AppendPathComponent(llvm::StringRef component)
Definition FileSpec.cpp:454
void SetDirectory(ConstString directory)
Directory string set accessor.
Definition FileSpec.cpp:342
const ConstString & GetFilename() const
Filename string const get accessor.
Definition FileSpec.h:251
std::vector< llvm::StringRef > GetComponents() const
Gets the components of the FileSpec's path.
Definition FileSpec.cpp:475
const ConstString & GetDirectory() const
Directory string const get accessor.
Definition FileSpec.h:234
ConstString GetFileNameStrippingExtension() const
Return the filename without the extension part.
Definition FileSpec.cpp:414
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:374
ConstString GetPathAsConstString(bool denormalize=true) const
Get the full path as a ConstString.
Definition FileSpec.cpp:390
void SetFilename(ConstString filename)
Filename string set accessor.
Definition FileSpec.cpp:352
void Resolve(llvm::SmallVectorImpl< char > &path)
Resolve path to make it canonical.
void EnumerateDirectory(llvm::Twine path, bool find_directories, bool find_files, bool find_other, EnumerateDirectoryCallbackType callback, void *callback_baton)
@ eEnumerateDirectoryResultNext
Enumerate next entry in the current directory.
Definition FileSystem.h:178
static FileSystem & Instance()
static bool ResolveExecutableInBundle(FileSpec &file)
When executable files may live within a directory, where the directory represents an executable bundl...
static Status RunShellCommand(llvm::StringRef command, const FileSpec &working_dir, int *status_ptr, int *signo_ptr, std::string *command_output, const Timeout< std::micro > &timeout, bool run_in_shell=true, bool hide_stderr=false)
Run a shell command.
static bool GetProcessInfo(lldb::pid_t pid, ProcessInstanceInfo &proc_info)
Definition aix/Host.cpp:177
static bool GetBundleDirectory(const FileSpec &file, FileSpec &bundle_directory)
If you have an executable that is in a bundle and want to get back to the bundle directory from the p...
ModuleIterable Modules() const
Definition ModuleList.h:537
FileSpec & GetFileSpec()
Definition ModuleSpec.h:53
FileSpec & GetSymbolFileSpec()
Definition ModuleSpec.h:77
ArchSpec * GetArchitecturePtr()
Definition ModuleSpec.h:81
A class that describes an executable image and its associated object and symbol files.
Definition Module.h:90
virtual SymbolFile * GetSymbolFile(bool can_create=true, Stream *feedback_strm=nullptr)
Get the module's symbol file.
Definition Module.cpp:977
const FileSpec & GetFileSpec() const
Get const accessor for the module file specification.
Definition Module.h:454
A plug-in interface definition class for object file parsers.
Definition ObjectFile.h:45
@ eTypeDynamicLinker
The platform's dynamic linker executable.
Definition ObjectFile.h:58
virtual llvm::VersionTuple GetMinimumOSVersion()
Get the minimum OS version this object file can run on.
Definition ObjectFile.h:640
virtual FileSpec & GetFileSpec()
Get accessor to the object file specification.
Definition ObjectFile.h:281
void SetValidator(ValidatorCallback validator, void *baton=nullptr)
const char * GetCurrentValue() const
StructuredData::ArraySP ExtractCrashInfoAnnotations(Process &process)
Extract the __crash_info annotations from each of the target's modules.
llvm::Expected< StructuredData::DictionarySP > FetchExtendedCrashInformation(Process &process) override
Gather all of crash informations into a structured data dictionary.
~PlatformDarwin() override
Destructor.
static FileSpec GetSDKDirectoryForModules(XcodeSDK::Type sdk_type)
Status ResolveSymbolFile(Target &target, const ModuleSpec &sym_spec, FileSpec &sym_file) override
Find a symbol file given a symbol file module specification.
void CalculateTrapHandlerSymbolNames() override
Ask the Platform subclass to fill in the list of trap handler names.
static std::tuple< llvm::VersionTuple, llvm::StringRef > ParseVersionBuildDir(llvm::StringRef str)
static lldb::PlatformSP CreateInstance(bool force, const ArchSpec *arch)
llvm::VersionTuple GetOSVersion(Process *process=nullptr) override
Get the OS version from a connected platform.
static FileSystem::EnumerateDirectoryResult DirectoryEnumerator(void *baton, llvm::sys::fs::file_type file_type, llvm::StringRef path)
FileSpecList LocateExecutableScriptingResources(Target *target, Module &module, Stream &feedback_stream) override
static FileSpec FindSDKInXcodeForModules(XcodeSDK::Type sdk_type, const FileSpec &sdks_spec)
ConstString GetFullNameForDylib(ConstString basename) override
static void DebuggerInitialize(lldb_private::Debugger &debugger)
static llvm::StringRef GetPluginNameStatic()
static llvm::Triple::OSType GetHostOSType()
StructuredData::DictionarySP ExtractAppSpecificInfo(Process &process)
Extract the Application Specific Information messages from a crash report.
lldb::ProcessSP DebugProcess(ProcessLaunchInfo &launch_info, Debugger &debugger, Target &target, Status &error) override
Subclasses do not need to implement this function as it uses the Platform::LaunchProcess() followed b...
lldb::BreakpointSP SetThreadCreationBreakpoint(Target &target) override
static llvm::StringRef GetDescriptionStatic()
Status LaunchProcess(ProcessLaunchInfo &launch_info) override
Launch a new process on a platform, not necessarily for debugging, it could be just for running the p...
Status GetSharedModule(const ModuleSpec &module_spec, Process *process, lldb::ModuleSP &module_sp, const FileSpecList *module_search_paths_ptr, llvm::SmallVectorImpl< lldb::ModuleSP > *old_modules, bool *did_create_ptr) override
uint32_t GetResumeCountForLaunchInfo(ProcessLaunchInfo &launch_info) override
Status FindBundleBinaryInExecSearchPaths(const ModuleSpec &module_spec, Process *process, lldb::ModuleSP &module_sp, const FileSpecList *module_search_paths_ptr, llvm::SmallVectorImpl< lldb::ModuleSP > *old_modules, bool *did_create_ptr)
llvm::Expected< std::string > ResolveSDKPathFromDebugInfo(Module &module) override
Returns the full path of the most appropriate SDK for the specified 'module'.
size_t GetSoftwareBreakpointTrapOpcode(Target &target, BreakpointSite *bp_site) override
void AddClangModuleCompilationOptionsForSDKType(Target *target, std::vector< std::string > &options, XcodeSDK::Type sdk_type)
Args GetExtraStartupCommands() override
Status PutFile(const FileSpec &source, const FileSpec &destination, uint32_t uid=UINT32_MAX, uint32_t gid=UINT32_MAX) override
FileSpec LocateExecutable(const char *basename) override
Find a support executable that may not live within in the standard locations related to LLDB.
void x86GetSupportedArchitectures(std::vector< ArchSpec > &archs)
llvm::Expected< std::pair< XcodeSDK, bool > > GetSDKPathFromDebugInfo(Module &module) override
Search each CU associated with the specified 'module' for the SDK paths the CUs were compiled against...
bool ModuleIsExcludedForUnconstrainedSearches(Target &target, const lldb::ModuleSP &module_sp) override
void ARMGetSupportedArchitectures(std::vector< ArchSpec > &archs, std::optional< llvm::Triple::OSType > os={})
The architecture selection rules for arm processors These cpu subtypes have distinct names (e....
std::vector< ConstString > m_trap_handlers
Definition Platform.h:1024
virtual size_t GetSoftwareBreakpointTrapOpcode(Target &target, BreakpointSite *bp_site)
virtual lldb::ProcessSP DebugProcess(ProcessLaunchInfo &launch_info, Debugger &debugger, Target &target, Status &error)
Subclasses do not need to implement this function as it uses the Platform::LaunchProcess() followed b...
static void Terminate()
Definition Platform.cpp:138
const ArchSpec & GetSystemArchitecture()
Definition Platform.cpp:816
virtual llvm::VersionTuple GetOSVersion(Process *process=nullptr)
Get the OS version from a connected platform.
Definition Platform.cpp:297
virtual Status LaunchProcess(ProcessLaunchInfo &launch_info)
Launch a new process on a platform, not necessarily for debugging, it could be just for running the p...
Definition Platform.cpp:933
static void Initialize()
Definition Platform.cpp:136
virtual Status GetSharedModule(const ModuleSpec &module_spec, Process *process, lldb::ModuleSP &module_sp, const FileSpecList *module_search_paths_ptr, llvm::SmallVectorImpl< lldb::ModuleSP > *old_modules, bool *did_create_ptr)
Definition Platform.cpp:164
bool IsRemote() const
Definition Platform.h:507
bool IsHost() const
Definition Platform.h:503
virtual llvm::StringRef GetPluginName()=0
static bool RegisterPlugin(llvm::StringRef name, llvm::StringRef description, ABICreateInstance create_callback)
static lldb::OptionValuePropertiesSP GetSettingForPlatformPlugin(Debugger &debugger, llvm::StringRef setting_name)
static bool CreateSettingForPlatformPlugin(Debugger &debugger, const lldb::OptionValuePropertiesSP &properties_sp, llvm::StringRef description, bool is_global_property)
static bool UnregisterPlugin(ABICreateInstance create_callback)
static FileSpec FindSymbolFileInBundle(const FileSpec &dsym_bundle_fspec, const UUID *uuid, const ArchSpec *arch)
Environment & GetEnvironment()
Definition ProcessInfo.h:88
const FileSpec & GetShell() const
static void NoOpMonitorCallback(lldb::pid_t pid, int signal, int status)
A Monitor callback which does not take any action on process events.
void SetMonitorProcessCallback(Host::MonitorChildProcessCallback callback)
A plug-in interface definition class for debugging a process.
Definition Process.h:357
lldb::pid_t GetID() const
Returns the pid of the process or LLDB_INVALID_PROCESS_ID if there is no known pid.
Definition Process.h:556
size_t ReadMemoryFromInferior(lldb::addr_t vm_addr, void *buf, size_t size, Status &error)
Read of memory from a process.
Definition Process.cpp:2165
virtual StructuredData::DictionarySP GetMetadata()
Fetch process defined metadata.
Definition Process.h:2611
size_t ReadCStringFromMemory(lldb::addr_t vm_addr, char *cstr, size_t cstr_max_len, Status &error)
Read a NULL terminated C string from memory.
Definition Process.cpp:2119
StructuredData::DictionarySP GetExtendedCrashInfoDict()
Fetch extended crash information held by the process.
Definition Process.h:2616
Target & GetTarget()
Get the target object pointer for this module.
Definition Process.h:1270
lldb::OptionValuePropertiesSP m_collection_sp
Status Unlink(const FileSpec &file_spec) override
virtual bool IsReservedWord(const char *word)
lldb::SectionSP FindSectionByName(ConstString section_dstr) const
Definition Section.cpp:558
An error handling class.
Definition Status.h:118
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Definition Status.cpp:106
static Status FromErrorString(const char *str)
Definition Status.h:141
bool Success() const
Test for success condition.
Definition Status.cpp:304
const char * GetData() const
llvm::StringRef GetString() const
A stream class that can stream formatted output to a file.
Definition Stream.h:28
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:134
void AddItem(const ObjectSP &item)
ObjectSP GetItemAtIndex(size_t idx) const
void ForEach(std::function< bool(llvm::StringRef key, Object *object)> const &callback) const
std::shared_ptr< Dictionary > DictionarySP
std::shared_ptr< Array > ArraySP
Provides public interface for all SymbolFiles.
Definition SymbolFile.h:51
virtual XcodeSDK ParseXcodeSDK(CompileUnit &comp_unit)
Return the Xcode SDK comp_unit was compiled against.
Definition SymbolFile.h:152
virtual uint32_t GetNumCompileUnits()=0
virtual lldb::CompUnitSP GetCompileUnitAtIndex(uint32_t idx)=0
Debugger & GetDebugger() const
Definition Target.h:1097
lldb::ModuleSP GetExecutableModule()
Gets the module for the main executable.
Definition Target.cpp:1517
lldb::BreakpointSP CreateBreakpoint(const FileSpecList *containingModules, const FileSpec &file, uint32_t line_no, uint32_t column, lldb::addr_t offset, LazyBool check_inlines, LazyBool skip_prologue, bool internal, bool request_hardware, LazyBool move_to_nearest_code)
Definition Target.cpp:481
const ModuleList & GetImages() const
Get accessor for the images for this process.
Definition Target.h:1014
const ArchSpec & GetArchitecture() const
Definition Target.h:1056
An abstraction for Xcode-style SDKs that works like ArchSpec.
Definition XcodeSDK.h:25
Type
Different types of Xcode SDKs.
Definition XcodeSDK.h:31
const FileSpec & GetSysroot() const
Definition XcodeSDK.cpp:145
void Merge(const XcodeSDK &other)
The merge function follows a strict order to maintain monotonicity:
Definition XcodeSDK.cpp:157
static std::string GetCanonicalName(Info info)
Return the canonical SDK name, such as "macosx" for the macOS SDK.
Definition XcodeSDK.cpp:177
bool IsAppleInternalSDK() const
Definition XcodeSDK.cpp:125
static bool SDKSupportsModules(Type type, llvm::VersionTuple version)
Whether LLDB feels confident importing Clang modules from this SDK.
Definition XcodeSDK.cpp:223
#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:332
@ eScriptLanguagePython
std::shared_ptr< lldb_private::BreakpointLocation > BreakpointLocationSP
std::shared_ptr< lldb_private::Platform > PlatformSP
@ eLanguageTypeUnknown
Unknown or invalid language value.
std::shared_ptr< lldb_private::Breakpoint > BreakpointSP
std::shared_ptr< lldb_private::Process > ProcessSP
std::shared_ptr< lldb_private::Section > SectionSP
uint64_t addr_t
Definition lldb-types.h:80
std::shared_ptr< lldb_private::Module > ModuleSP
A parsed SDK directory name.
Definition XcodeSDK.h:48
#define PATH_MAX