-
Notifications
You must be signed in to change notification settings - Fork 10.8k
/
PlatformDarwin.cpp
1377 lines (1219 loc) · 52 KB
/
PlatformDarwin.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===-- PlatformDarwin.cpp ------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "PlatformDarwin.h"
#include <cstring>
#include <algorithm>
#include <memory>
#include <mutex>
#include "lldb/Breakpoint/BreakpointLocation.h"
#include "lldb/Breakpoint/BreakpointSite.h"
#include "lldb/Core/Debugger.h"
#include "lldb/Core/Module.h"
#include "lldb/Core/ModuleSpec.h"
#include "lldb/Core/Section.h"
#include "lldb/Host/Host.h"
#include "lldb/Host/HostInfo.h"
#include "lldb/Host/XML.h"
#include "lldb/Interpreter/CommandInterpreter.h"
#include "lldb/Symbol/LocateSymbolFile.h"
#include "lldb/Symbol/ObjectFile.h"
#include "lldb/Symbol/SymbolFile.h"
#include "lldb/Symbol/SymbolVendor.h"
#include "lldb/Target/Platform.h"
#include "lldb/Target/Process.h"
#include "lldb/Target/Target.h"
#include "lldb/Utility/Log.h"
#include "lldb/Utility/ProcessInfo.h"
#include "lldb/Utility/Status.h"
#include "lldb/Utility/Timer.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Threading.h"
#include "llvm/Support/VersionTuple.h"
#if defined(__APPLE__)
#include <TargetConditionals.h>
#endif
using namespace lldb;
using namespace lldb_private;
/// Default Constructor
PlatformDarwin::PlatformDarwin(bool is_host) : PlatformPOSIX(is_host) {}
/// Destructor.
///
/// The destructor is virtual since this class is designed to be
/// inherited from by the plug-in instance.
PlatformDarwin::~PlatformDarwin() = default;
lldb_private::Status
PlatformDarwin::PutFile(const lldb_private::FileSpec &source,
const lldb_private::FileSpec &destination, uint32_t uid,
uint32_t gid) {
// Unconditionally unlink the destination. If it is an executable,
// simply opening it and truncating its contents would invalidate
// its cached code signature.
Unlink(destination);
return PlatformPOSIX::PutFile(source, destination, uid, gid);
}
FileSpecList PlatformDarwin::LocateExecutableScriptingResources(
Target *target, Module &module, Stream *feedback_stream) {
FileSpecList file_list;
if (target &&
target->GetDebugger().GetScriptLanguage() == eScriptLanguagePython) {
// NB some extensions might be meaningful and should not be stripped -
// "this.binary.file"
// should not lose ".file" but GetFileNameStrippingExtension() will do
// precisely that. Ideally, we should have a per-platform list of
// extensions (".exe", ".app", ".dSYM", ".framework") which should be
// stripped while leaving "this.binary.file" as-is.
FileSpec module_spec = module.GetFileSpec();
if (module_spec) {
if (SymbolFile *symfile = module.GetSymbolFile()) {
ObjectFile *objfile = symfile->GetObjectFile();
if (objfile) {
FileSpec symfile_spec(objfile->GetFileSpec());
if (symfile_spec &&
strcasestr(symfile_spec.GetPath().c_str(),
".dSYM/Contents/Resources/DWARF") != nullptr &&
FileSystem::Instance().Exists(symfile_spec)) {
while (module_spec.GetFilename()) {
std::string module_basename(
module_spec.GetFilename().GetCString());
std::string original_module_basename(module_basename);
bool was_keyword = false;
// FIXME: for Python, we cannot allow certain characters in
// module
// filenames we import. Theoretically, different scripting
// languages may have different sets of forbidden tokens in
// filenames, and that should be dealt with by each
// ScriptInterpreter. For now, we just replace dots with
// underscores, but if we ever support anything other than
// Python we will need to rework this
std::replace(module_basename.begin(), module_basename.end(), '.',
'_');
std::replace(module_basename.begin(), module_basename.end(), ' ',
'_');
std::replace(module_basename.begin(), module_basename.end(), '-',
'_');
ScriptInterpreter *script_interpreter =
target->GetDebugger().GetScriptInterpreter();
if (script_interpreter &&
script_interpreter->IsReservedWord(module_basename.c_str())) {
module_basename.insert(module_basename.begin(), '_');
was_keyword = true;
}
StreamString path_string;
StreamString original_path_string;
// for OSX we are going to be in
// .dSYM/Contents/Resources/DWARF/<basename> let us go to
// .dSYM/Contents/Resources/Python/<basename>.py and see if the
// file exists
path_string.Printf("%s/../Python/%s.py",
symfile_spec.GetDirectory().GetCString(),
module_basename.c_str());
original_path_string.Printf(
"%s/../Python/%s.py",
symfile_spec.GetDirectory().GetCString(),
original_module_basename.c_str());
FileSpec script_fspec(path_string.GetString());
FileSystem::Instance().Resolve(script_fspec);
FileSpec orig_script_fspec(original_path_string.GetString());
FileSystem::Instance().Resolve(orig_script_fspec);
// if we did some replacements of reserved characters, and a
// file with the untampered name exists, then warn the user
// that the file as-is shall not be loaded
if (feedback_stream) {
if (module_basename != original_module_basename &&
FileSystem::Instance().Exists(orig_script_fspec)) {
const char *reason_for_complaint =
was_keyword ? "conflicts with a keyword"
: "contains reserved characters";
if (FileSystem::Instance().Exists(script_fspec))
feedback_stream->Printf(
"warning: the symbol file '%s' contains a debug "
"script. However, its name"
" '%s' %s and as such cannot be loaded. LLDB will"
" load '%s' instead. Consider removing the file with "
"the malformed name to"
" eliminate this warning.\n",
symfile_spec.GetPath().c_str(),
original_path_string.GetData(), reason_for_complaint,
path_string.GetData());
else
feedback_stream->Printf(
"warning: the symbol file '%s' contains a debug "
"script. However, its name"
" %s and as such cannot be loaded. If you intend"
" to have this script loaded, please rename '%s' to "
"'%s' and retry.\n",
symfile_spec.GetPath().c_str(), reason_for_complaint,
original_path_string.GetData(), path_string.GetData());
}
}
if (FileSystem::Instance().Exists(script_fspec)) {
file_list.Append(script_fspec);
break;
}
// If we didn't find the python file, then keep stripping the
// extensions and try again
ConstString filename_no_extension(
module_spec.GetFileNameStrippingExtension());
if (module_spec.GetFilename() == filename_no_extension)
break;
module_spec.GetFilename() = filename_no_extension;
}
}
}
}
}
}
return file_list;
}
Status PlatformDarwin::ResolveSymbolFile(Target &target,
const ModuleSpec &sym_spec,
FileSpec &sym_file) {
sym_file = sym_spec.GetSymbolFileSpec();
if (FileSystem::Instance().IsDirectory(sym_file)) {
sym_file = Symbols::FindSymbolFileInBundle(sym_file, sym_spec.GetUUIDPtr(),
sym_spec.GetArchitecturePtr());
}
return {};
}
static lldb_private::Status
MakeCacheFolderForFile(const FileSpec &module_cache_spec) {
FileSpec module_cache_folder =
module_cache_spec.CopyByRemovingLastPathComponent();
return llvm::sys::fs::create_directory(module_cache_folder.GetPath());
}
static lldb_private::Status
BringInRemoteFile(Platform *platform,
const lldb_private::ModuleSpec &module_spec,
const FileSpec &module_cache_spec) {
MakeCacheFolderForFile(module_cache_spec);
Status err = platform->GetFile(module_spec.GetFileSpec(), module_cache_spec);
return err;
}
lldb_private::Status PlatformDarwin::GetSharedModuleWithLocalCache(
const lldb_private::ModuleSpec &module_spec, lldb::ModuleSP &module_sp,
const lldb_private::FileSpecList *module_search_paths_ptr,
llvm::SmallVectorImpl<lldb::ModuleSP> *old_modules, bool *did_create_ptr) {
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM));
LLDB_LOGF(log,
"[%s] Trying to find module %s/%s - platform path %s/%s symbol "
"path %s/%s",
(IsHost() ? "host" : "remote"),
module_spec.GetFileSpec().GetDirectory().AsCString(),
module_spec.GetFileSpec().GetFilename().AsCString(),
module_spec.GetPlatformFileSpec().GetDirectory().AsCString(),
module_spec.GetPlatformFileSpec().GetFilename().AsCString(),
module_spec.GetSymbolFileSpec().GetDirectory().AsCString(),
module_spec.GetSymbolFileSpec().GetFilename().AsCString());
Status err;
if (IsHost()) {
// When debugging on the host, we are most likely using the same shared
// cache as our inferior. The dylibs from the shared cache might not
// exist on the filesystem, so let's use the images in our own memory
// to create the modules.
// Check if the requested image is in our shared cache.
SharedCacheImageInfo image_info =
HostInfo::GetSharedCacheImageInfo(module_spec.GetFileSpec().GetPath());
// If we found it and it has the correct UUID, let's proceed with
// creating a module from the memory contents.
if (image_info.uuid &&
(!module_spec.GetUUID() || module_spec.GetUUID() == image_info.uuid)) {
ModuleSpec shared_cache_spec(module_spec.GetFileSpec(), image_info.uuid,
image_info.data_sp);
err = ModuleList::GetSharedModule(shared_cache_spec, module_sp,
module_search_paths_ptr, old_modules,
did_create_ptr);
if (module_sp)
return err;
}
}
err = ModuleList::GetSharedModule(module_spec, module_sp,
module_search_paths_ptr, old_modules,
did_create_ptr);
if (module_sp)
return err;
if (!IsHost()) {
std::string cache_path(GetLocalCacheDirectory());
// Only search for a locally cached file if we have a valid cache path
if (!cache_path.empty()) {
std::string module_path(module_spec.GetFileSpec().GetPath());
cache_path.append(module_path);
FileSpec module_cache_spec(cache_path);
// if rsync is supported, always bring in the file - rsync will be very
// efficient when files are the same on the local and remote end of the
// connection
if (this->GetSupportsRSync()) {
err = BringInRemoteFile(this, module_spec, module_cache_spec);
if (err.Fail())
return err;
if (FileSystem::Instance().Exists(module_cache_spec)) {
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM));
LLDB_LOGF(log, "[%s] module %s/%s was rsynced and is now there",
(IsHost() ? "host" : "remote"),
module_spec.GetFileSpec().GetDirectory().AsCString(),
module_spec.GetFileSpec().GetFilename().AsCString());
ModuleSpec local_spec(module_cache_spec,
module_spec.GetArchitecture());
module_sp = std::make_shared<Module>(local_spec);
module_sp->SetPlatformFileSpec(module_spec.GetFileSpec());
return Status();
}
}
// try to find the module in the cache
if (FileSystem::Instance().Exists(module_cache_spec)) {
// get the local and remote MD5 and compare
if (m_remote_platform_sp) {
// when going over the *slow* GDB remote transfer mechanism we first
// check the hashes of the files - and only do the actual transfer if
// they differ
uint64_t high_local, high_remote, low_local, low_remote;
auto MD5 = llvm::sys::fs::md5_contents(module_cache_spec.GetPath());
if (!MD5)
return Status(MD5.getError());
std::tie(high_local, low_local) = MD5->words();
m_remote_platform_sp->CalculateMD5(module_spec.GetFileSpec(),
low_remote, high_remote);
if (low_local != low_remote || high_local != high_remote) {
// bring in the remote file
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM));
LLDB_LOGF(log,
"[%s] module %s/%s needs to be replaced from remote copy",
(IsHost() ? "host" : "remote"),
module_spec.GetFileSpec().GetDirectory().AsCString(),
module_spec.GetFileSpec().GetFilename().AsCString());
Status err =
BringInRemoteFile(this, module_spec, module_cache_spec);
if (err.Fail())
return err;
}
}
ModuleSpec local_spec(module_cache_spec, module_spec.GetArchitecture());
module_sp = std::make_shared<Module>(local_spec);
module_sp->SetPlatformFileSpec(module_spec.GetFileSpec());
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM));
LLDB_LOGF(log, "[%s] module %s/%s was found in the cache",
(IsHost() ? "host" : "remote"),
module_spec.GetFileSpec().GetDirectory().AsCString(),
module_spec.GetFileSpec().GetFilename().AsCString());
return Status();
}
// bring in the remote module file
LLDB_LOGF(log, "[%s] module %s/%s needs to come in remotely",
(IsHost() ? "host" : "remote"),
module_spec.GetFileSpec().GetDirectory().AsCString(),
module_spec.GetFileSpec().GetFilename().AsCString());
Status err = BringInRemoteFile(this, module_spec, module_cache_spec);
if (err.Fail())
return err;
if (FileSystem::Instance().Exists(module_cache_spec)) {
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM));
LLDB_LOGF(log, "[%s] module %s/%s is now cached and fine",
(IsHost() ? "host" : "remote"),
module_spec.GetFileSpec().GetDirectory().AsCString(),
module_spec.GetFileSpec().GetFilename().AsCString());
ModuleSpec local_spec(module_cache_spec, module_spec.GetArchitecture());
module_sp = std::make_shared<Module>(local_spec);
module_sp->SetPlatformFileSpec(module_spec.GetFileSpec());
return Status();
} else
return Status("unable to obtain valid module file");
} else
return Status("no cache path");
} else
return Status("unable to resolve module");
}
Status PlatformDarwin::GetSharedModule(
const ModuleSpec &module_spec, Process *process, ModuleSP &module_sp,
const FileSpecList *module_search_paths_ptr,
llvm::SmallVectorImpl<ModuleSP> *old_modules, bool *did_create_ptr) {
Status error;
module_sp.reset();
if (IsRemote()) {
// If we have a remote platform always, let it try and locate the shared
// module first.
if (m_remote_platform_sp) {
error = m_remote_platform_sp->GetSharedModule(
module_spec, process, module_sp, module_search_paths_ptr, old_modules,
did_create_ptr);
}
}
if (!module_sp) {
// Fall back to the local platform and find the file locally
error = Platform::GetSharedModule(module_spec, process, module_sp,
module_search_paths_ptr, old_modules,
did_create_ptr);
const FileSpec &platform_file = module_spec.GetFileSpec();
if (!module_sp && module_search_paths_ptr && platform_file) {
// We can try to pull off part of the file path up to the bundle
// directory level and try any module search paths...
FileSpec bundle_directory;
if (Host::GetBundleDirectory(platform_file, bundle_directory)) {
if (platform_file == bundle_directory) {
ModuleSpec new_module_spec(module_spec);
new_module_spec.GetFileSpec() = bundle_directory;
if (Host::ResolveExecutableInBundle(new_module_spec.GetFileSpec())) {
Status new_error(Platform::GetSharedModule(
new_module_spec, process, module_sp, nullptr, old_modules,
did_create_ptr));
if (module_sp)
return new_error;
}
} else {
char platform_path[PATH_MAX];
char bundle_dir[PATH_MAX];
platform_file.GetPath(platform_path, sizeof(platform_path));
const size_t bundle_directory_len =
bundle_directory.GetPath(bundle_dir, sizeof(bundle_dir));
char new_path[PATH_MAX];
size_t num_module_search_paths = module_search_paths_ptr->GetSize();
for (size_t i = 0; i < num_module_search_paths; ++i) {
const size_t search_path_len =
module_search_paths_ptr->GetFileSpecAtIndex(i).GetPath(
new_path, sizeof(new_path));
if (search_path_len < sizeof(new_path)) {
snprintf(new_path + search_path_len,
sizeof(new_path) - search_path_len, "/%s",
platform_path + bundle_directory_len);
FileSpec new_file_spec(new_path);
if (FileSystem::Instance().Exists(new_file_spec)) {
ModuleSpec new_module_spec(module_spec);
new_module_spec.GetFileSpec() = new_file_spec;
Status new_error(Platform::GetSharedModule(
new_module_spec, process, module_sp, nullptr, old_modules,
did_create_ptr));
if (module_sp) {
module_sp->SetPlatformFileSpec(new_file_spec);
return new_error;
}
}
}
}
}
}
}
}
if (module_sp)
module_sp->SetPlatformFileSpec(module_spec.GetFileSpec());
return error;
}
size_t
PlatformDarwin::GetSoftwareBreakpointTrapOpcode(Target &target,
BreakpointSite *bp_site) {
const uint8_t *trap_opcode = nullptr;
uint32_t trap_opcode_size = 0;
bool bp_is_thumb = false;
llvm::Triple::ArchType machine = target.GetArchitecture().GetMachine();
switch (machine) {
case llvm::Triple::aarch64_32:
case llvm::Triple::aarch64: {
// 'brk #0' or 0xd4200000 in BE byte order
static const uint8_t g_arm64_breakpoint_opcode[] = {0x00, 0x00, 0x20, 0xD4};
trap_opcode = g_arm64_breakpoint_opcode;
trap_opcode_size = sizeof(g_arm64_breakpoint_opcode);
} break;
case llvm::Triple::thumb:
bp_is_thumb = true;
LLVM_FALLTHROUGH;
case llvm::Triple::arm: {
static const uint8_t g_arm_breakpoint_opcode[] = {0xFE, 0xDE, 0xFF, 0xE7};
static const uint8_t g_thumb_breakpooint_opcode[] = {0xFE, 0xDE};
// Auto detect arm/thumb if it wasn't explicitly specified
if (!bp_is_thumb) {
lldb::BreakpointLocationSP bp_loc_sp(bp_site->GetOwnerAtIndex(0));
if (bp_loc_sp)
bp_is_thumb = bp_loc_sp->GetAddress().GetAddressClass() ==
AddressClass::eCodeAlternateISA;
}
if (bp_is_thumb) {
trap_opcode = g_thumb_breakpooint_opcode;
trap_opcode_size = sizeof(g_thumb_breakpooint_opcode);
break;
}
trap_opcode = g_arm_breakpoint_opcode;
trap_opcode_size = sizeof(g_arm_breakpoint_opcode);
} break;
case llvm::Triple::ppc:
case llvm::Triple::ppc64: {
static const uint8_t g_ppc_breakpoint_opcode[] = {0x7F, 0xC0, 0x00, 0x08};
trap_opcode = g_ppc_breakpoint_opcode;
trap_opcode_size = sizeof(g_ppc_breakpoint_opcode);
} break;
default:
return Platform::GetSoftwareBreakpointTrapOpcode(target, bp_site);
}
if (trap_opcode && trap_opcode_size) {
if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size))
return trap_opcode_size;
}
return 0;
}
bool PlatformDarwin::ModuleIsExcludedForUnconstrainedSearches(
lldb_private::Target &target, const lldb::ModuleSP &module_sp) {
if (!module_sp)
return false;
ObjectFile *obj_file = module_sp->GetObjectFile();
if (!obj_file)
return false;
ObjectFile::Type obj_type = obj_file->GetType();
return obj_type == ObjectFile::eTypeDynamicLinker;
}
bool PlatformDarwin::x86GetSupportedArchitectureAtIndex(uint32_t idx,
ArchSpec &arch) {
ArchSpec host_arch = HostInfo::GetArchitecture(HostInfo::eArchKindDefault);
if (host_arch.GetCore() == ArchSpec::eCore_x86_64_x86_64h) {
switch (idx) {
case 0:
arch = host_arch;
return true;
case 1:
arch.SetTriple("x86_64-apple-macosx");
return true;
case 2:
arch = HostInfo::GetArchitecture(HostInfo::eArchKind32);
return true;
default:
return false;
}
} else {
if (idx == 0) {
arch = HostInfo::GetArchitecture(HostInfo::eArchKindDefault);
return arch.IsValid();
} else if (idx == 1) {
ArchSpec platform_arch(
HostInfo::GetArchitecture(HostInfo::eArchKindDefault));
ArchSpec platform_arch64(
HostInfo::GetArchitecture(HostInfo::eArchKind64));
if (platform_arch.IsExactMatch(platform_arch64)) {
// This macosx platform supports both 32 and 64 bit. Since we already
// returned the 64 bit arch for idx == 0, return the 32 bit arch for
// idx == 1
arch = HostInfo::GetArchitecture(HostInfo::eArchKind32);
return arch.IsValid();
}
}
}
return false;
}
static llvm::ArrayRef<const char *> GetCompatibleArchs(ArchSpec::Core core) {
switch (core) {
default:
LLVM_FALLTHROUGH;
case ArchSpec::eCore_arm_arm64e: {
static const char *g_arm64e_compatible_archs[] = {
"arm64e", "arm64", "armv7", "armv7f", "armv7k", "armv7s",
"armv7m", "armv7em", "armv6m", "armv6", "armv5", "armv4",
"arm", "thumbv7", "thumbv7f", "thumbv7k", "thumbv7s", "thumbv7m",
"thumbv7em", "thumbv6m", "thumbv6", "thumbv5", "thumbv4t", "thumb",
};
return {g_arm64e_compatible_archs};
}
case ArchSpec::eCore_arm_arm64: {
static const char *g_arm64_compatible_archs[] = {
"arm64", "armv7", "armv7f", "armv7k", "armv7s", "armv7m",
"armv7em", "armv6m", "armv6", "armv5", "armv4", "arm",
"thumbv7", "thumbv7f", "thumbv7k", "thumbv7s", "thumbv7m", "thumbv7em",
"thumbv6m", "thumbv6", "thumbv5", "thumbv4t", "thumb",
};
return {g_arm64_compatible_archs};
}
case ArchSpec::eCore_arm_armv7: {
static const char *g_armv7_compatible_archs[] = {
"armv7", "armv6m", "armv6", "armv5", "armv4", "arm",
"thumbv7", "thumbv6m", "thumbv6", "thumbv5", "thumbv4t", "thumb",
};
return {g_armv7_compatible_archs};
}
case ArchSpec::eCore_arm_armv7f: {
static const char *g_armv7f_compatible_archs[] = {
"armv7f", "armv7", "armv6m", "armv6", "armv5",
"armv4", "arm", "thumbv7f", "thumbv7", "thumbv6m",
"thumbv6", "thumbv5", "thumbv4t", "thumb",
};
return {g_armv7f_compatible_archs};
}
case ArchSpec::eCore_arm_armv7k: {
static const char *g_armv7k_compatible_archs[] = {
"armv7k", "armv7", "armv6m", "armv6", "armv5",
"armv4", "arm", "thumbv7k", "thumbv7", "thumbv6m",
"thumbv6", "thumbv5", "thumbv4t", "thumb",
};
return {g_armv7k_compatible_archs};
}
case ArchSpec::eCore_arm_armv7s: {
static const char *g_armv7s_compatible_archs[] = {
"armv7s", "armv7", "armv6m", "armv6", "armv5",
"armv4", "arm", "thumbv7s", "thumbv7", "thumbv6m",
"thumbv6", "thumbv5", "thumbv4t", "thumb",
};
return {g_armv7s_compatible_archs};
}
case ArchSpec::eCore_arm_armv7m: {
static const char *g_armv7m_compatible_archs[] = {
"armv7m", "armv7", "armv6m", "armv6", "armv5",
"armv4", "arm", "thumbv7m", "thumbv7", "thumbv6m",
"thumbv6", "thumbv5", "thumbv4t", "thumb",
};
return {g_armv7m_compatible_archs};
}
case ArchSpec::eCore_arm_armv7em: {
static const char *g_armv7em_compatible_archs[] = {
"armv7em", "armv7", "armv6m", "armv6", "armv5",
"armv4", "arm", "thumbv7em", "thumbv7", "thumbv6m",
"thumbv6", "thumbv5", "thumbv4t", "thumb",
};
return {g_armv7em_compatible_archs};
}
case ArchSpec::eCore_arm_armv6m: {
static const char *g_armv6m_compatible_archs[] = {
"armv6m", "armv6", "armv5", "armv4", "arm",
"thumbv6m", "thumbv6", "thumbv5", "thumbv4t", "thumb",
};
return {g_armv6m_compatible_archs};
}
case ArchSpec::eCore_arm_armv6: {
static const char *g_armv6_compatible_archs[] = {
"armv6", "armv5", "armv4", "arm",
"thumbv6", "thumbv5", "thumbv4t", "thumb",
};
return {g_armv6_compatible_archs};
}
case ArchSpec::eCore_arm_armv5: {
static const char *g_armv5_compatible_archs[] = {
"armv5", "armv4", "arm", "thumbv5", "thumbv4t", "thumb",
};
return {g_armv5_compatible_archs};
}
case ArchSpec::eCore_arm_armv4: {
static const char *g_armv4_compatible_archs[] = {
"armv4",
"arm",
"thumbv4t",
"thumb",
};
return {g_armv4_compatible_archs};
}
}
return {};
}
const char *PlatformDarwin::GetCompatibleArch(ArchSpec::Core core, size_t idx) {
llvm::ArrayRef<const char *> compatible_archs = GetCompatibleArchs(core);
if (!compatible_archs.data())
return nullptr;
if (idx < compatible_archs.size())
return compatible_archs[idx];
return nullptr;
}
/// The architecture selection rules for arm processors These cpu subtypes have
/// distinct names (e.g. armv7f) but armv7 binaries run fine on an armv7f
/// processor.
bool PlatformDarwin::ARMGetSupportedArchitectureAtIndex(uint32_t idx,
ArchSpec &arch) {
const ArchSpec system_arch = GetSystemArchitecture();
const ArchSpec::Core system_core = system_arch.GetCore();
if (const char *compatible_arch = GetCompatibleArch(system_core, idx)) {
llvm::Triple triple;
triple.setArchName(compatible_arch);
triple.setVendor(llvm::Triple::VendorType::Apple);
arch.SetTriple(triple);
return true;
}
arch.Clear();
return false;
}
static FileSpec GetXcodeSelectPath() {
static FileSpec g_xcode_select_filespec;
if (!g_xcode_select_filespec) {
FileSpec xcode_select_cmd("/usr/bin/xcode-select");
if (FileSystem::Instance().Exists(xcode_select_cmd)) {
int exit_status = -1;
int signo = -1;
std::string command_output;
Status status =
Host::RunShellCommand("/usr/bin/xcode-select --print-path",
FileSpec(), // current working directory
&exit_status, &signo, &command_output,
std::chrono::seconds(2), // short timeout
false); // don't run in a shell
if (status.Success() && exit_status == 0 && !command_output.empty()) {
size_t first_non_newline = command_output.find_last_not_of("\r\n");
if (first_non_newline != std::string::npos) {
command_output.erase(first_non_newline + 1);
}
g_xcode_select_filespec = FileSpec(command_output);
}
}
}
return g_xcode_select_filespec;
}
BreakpointSP PlatformDarwin::SetThreadCreationBreakpoint(Target &target) {
BreakpointSP bp_sp;
static const char *g_bp_names[] = {
"start_wqthread", "_pthread_wqthread", "_pthread_start",
};
static const char *g_bp_modules[] = {"libsystem_c.dylib",
"libSystem.B.dylib"};
FileSpecList bp_modules;
for (size_t i = 0; i < llvm::array_lengthof(g_bp_modules); i++) {
const char *bp_module = g_bp_modules[i];
bp_modules.EmplaceBack(bp_module);
}
bool internal = true;
bool hardware = false;
LazyBool skip_prologue = eLazyBoolNo;
bp_sp = target.CreateBreakpoint(&bp_modules, nullptr, g_bp_names,
llvm::array_lengthof(g_bp_names),
eFunctionNameTypeFull, eLanguageTypeUnknown,
0, skip_prologue, internal, hardware);
bp_sp->SetBreakpointKind("thread-creation");
return bp_sp;
}
uint32_t
PlatformDarwin::GetResumeCountForLaunchInfo(ProcessLaunchInfo &launch_info) {
const FileSpec &shell = launch_info.GetShell();
if (!shell)
return 1;
std::string shell_string = shell.GetPath();
const char *shell_name = strrchr(shell_string.c_str(), '/');
if (shell_name == nullptr)
shell_name = shell_string.c_str();
else
shell_name++;
if (strcmp(shell_name, "sh") == 0) {
// /bin/sh re-exec's itself as /bin/bash requiring another resume. But it
// only does this if the COMMAND_MODE environment variable is set to
// "legacy".
if (launch_info.GetEnvironment().lookup("COMMAND_MODE") == "legacy")
return 2;
return 1;
} else if (strcmp(shell_name, "csh") == 0 ||
strcmp(shell_name, "tcsh") == 0 ||
strcmp(shell_name, "zsh") == 0) {
// csh and tcsh always seem to re-exec themselves.
return 2;
} else
return 1;
}
lldb::ProcessSP PlatformDarwin::DebugProcess(ProcessLaunchInfo &launch_info,
Debugger &debugger, Target &target,
Status &error) {
ProcessSP process_sp;
if (IsHost()) {
// We are going to hand this process off to debugserver which will be in
// charge of setting the exit status. However, we still need to reap it
// from lldb. So, make sure we use a exit callback which does not set exit
// status.
const bool monitor_signals = false;
launch_info.SetMonitorProcessCallback(
&ProcessLaunchInfo::NoOpMonitorCallback, monitor_signals);
process_sp = Platform::DebugProcess(launch_info, debugger, target, error);
} else {
if (m_remote_platform_sp)
process_sp = m_remote_platform_sp->DebugProcess(launch_info, debugger,
target, error);
else
error.SetErrorString("the platform is not currently connected");
}
return process_sp;
}
void PlatformDarwin::CalculateTrapHandlerSymbolNames() {
m_trap_handlers.push_back(ConstString("_sigtramp"));
}
static FileSpec GetCommandLineToolsLibraryPath() {
static FileSpec g_command_line_tools_filespec;
if (!g_command_line_tools_filespec) {
FileSpec command_line_tools_path(GetXcodeSelectPath());
command_line_tools_path.AppendPathComponent("Library");
if (FileSystem::Instance().Exists(command_line_tools_path)) {
g_command_line_tools_filespec = command_line_tools_path;
}
}
return g_command_line_tools_filespec;
}
FileSystem::EnumerateDirectoryResult PlatformDarwin::DirectoryEnumerator(
void *baton, llvm::sys::fs::file_type file_type, llvm::StringRef path) {
SDKEnumeratorInfo *enumerator_info = static_cast<SDKEnumeratorInfo *>(baton);
FileSpec spec(path);
if (XcodeSDK::SDKSupportsModules(enumerator_info->sdk_type, spec)) {
enumerator_info->found_path = spec;
return FileSystem::EnumerateDirectoryResult::eEnumerateDirectoryResultNext;
}
return FileSystem::EnumerateDirectoryResult::eEnumerateDirectoryResultNext;
}
FileSpec PlatformDarwin::FindSDKInXcodeForModules(XcodeSDK::Type sdk_type,
const FileSpec &sdks_spec) {
// Look inside Xcode for the required installed iOS SDK version
if (!FileSystem::Instance().IsDirectory(sdks_spec)) {
return FileSpec();
}
const bool find_directories = true;
const bool find_files = false;
const bool find_other = true; // include symlinks
SDKEnumeratorInfo enumerator_info;
enumerator_info.sdk_type = sdk_type;
FileSystem::Instance().EnumerateDirectory(
sdks_spec.GetPath(), find_directories, find_files, find_other,
DirectoryEnumerator, &enumerator_info);
if (FileSystem::Instance().IsDirectory(enumerator_info.found_path))
return enumerator_info.found_path;
else
return FileSpec();
}
FileSpec PlatformDarwin::GetSDKDirectoryForModules(XcodeSDK::Type sdk_type) {
FileSpec sdks_spec = HostInfo::GetXcodeContentsDirectory();
sdks_spec.AppendPathComponent("Developer");
sdks_spec.AppendPathComponent("Platforms");
switch (sdk_type) {
case XcodeSDK::Type::MacOSX:
sdks_spec.AppendPathComponent("MacOSX.platform");
break;
case XcodeSDK::Type::iPhoneSimulator:
sdks_spec.AppendPathComponent("iPhoneSimulator.platform");
break;
case XcodeSDK::Type::iPhoneOS:
sdks_spec.AppendPathComponent("iPhoneOS.platform");
break;
case XcodeSDK::Type::WatchSimulator:
sdks_spec.AppendPathComponent("WatchSimulator.platform");
break;
case XcodeSDK::Type::AppleTVSimulator:
sdks_spec.AppendPathComponent("AppleTVSimulator.platform");
break;
default:
llvm_unreachable("unsupported sdk");
}
sdks_spec.AppendPathComponent("Developer");
sdks_spec.AppendPathComponent("SDKs");
if (sdk_type == XcodeSDK::Type::MacOSX) {
llvm::VersionTuple version = HostInfo::GetOSVersion();
if (!version.empty()) {
if (XcodeSDK::SDKSupportsModules(XcodeSDK::Type::MacOSX, version)) {
// If the Xcode SDKs are not available then try to use the
// Command Line Tools one which is only for MacOSX.
if (!FileSystem::Instance().Exists(sdks_spec)) {
sdks_spec = GetCommandLineToolsLibraryPath();
sdks_spec.AppendPathComponent("SDKs");
}
// We slightly prefer the exact SDK for this machine. See if it is
// there.
FileSpec native_sdk_spec = sdks_spec;
StreamString native_sdk_name;
native_sdk_name.Printf("MacOSX%u.%u.sdk", version.getMajor(),
version.getMinor().getValueOr(0));
native_sdk_spec.AppendPathComponent(native_sdk_name.GetString());
if (FileSystem::Instance().Exists(native_sdk_spec)) {
return native_sdk_spec;
}
}
}
}
return FindSDKInXcodeForModules(sdk_type, sdks_spec);
}
std::tuple<llvm::VersionTuple, llvm::StringRef>
PlatformDarwin::ParseVersionBuildDir(llvm::StringRef dir) {
llvm::StringRef build;
llvm::StringRef version_str;
llvm::StringRef build_str;
std::tie(version_str, build_str) = dir.split(' ');
llvm::VersionTuple version;
if (!version.tryParse(version_str) ||
build_str.empty()) {
if (build_str.consume_front("(")) {
size_t pos = build_str.find(')');
build = build_str.slice(0, pos);
}
}
return std::make_tuple(version, build);
}
llvm::Expected<StructuredData::DictionarySP>
PlatformDarwin::FetchExtendedCrashInformation(Process &process) {
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
StructuredData::ArraySP annotations = ExtractCrashInfoAnnotations(process);
if (!annotations || !annotations->GetSize()) {
LLDB_LOG(log, "Couldn't extract crash information annotations");
return nullptr;
}
StructuredData::DictionarySP extended_crash_info =
std::make_shared<StructuredData::Dictionary>();
extended_crash_info->AddItem("crash-info annotations", annotations);
return extended_crash_info;
}
StructuredData::ArraySP
PlatformDarwin::ExtractCrashInfoAnnotations(Process &process) {
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
ConstString section_name("__crash_info");
Target &target = process.GetTarget();
StructuredData::ArraySP array_sp = std::make_shared<StructuredData::Array>();
for (ModuleSP module : target.GetImages().Modules()) {
SectionList *sections = module->GetSectionList();
std::string module_name = module->GetSpecificationDescription();
// The DYDL module is skipped since it's always loaded when running the
// binary.
if (module_name == "/usr/lib/dyld")
continue;
if (!sections) {
LLDB_LOG(log, "Module {0} doesn't have any section!", module_name);
continue;
}
SectionSP crash_info = sections->FindSectionByName(section_name);
if (!crash_info) {
LLDB_LOG(log, "Module {0} doesn't have section {1}!", module_name,
section_name);
continue;
}
addr_t load_addr = crash_info->GetLoadBaseAddress(&target);
if (load_addr == LLDB_INVALID_ADDRESS) {
LLDB_LOG(log, "Module {0} has an invalid '{1}' section load address: {2}",
module_name, section_name, load_addr);
continue;
}
Status error;
CrashInfoAnnotations annotations;
size_t expected_size = sizeof(CrashInfoAnnotations);
size_t bytes_read = process.ReadMemoryFromInferior(load_addr, &annotations,
expected_size, error);
if (expected_size != bytes_read || error.Fail()) {
LLDB_LOG(log, "Failed to read {0} section from memory in module {1}: {2}",
section_name, module_name, error);
continue;
}
// initial support added for version 5