/
Host.cpp
2472 lines (2186 loc) · 77 KB
/
Host.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
//===-- Host.cpp ------------------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "lldb/lldb-python.h"
// C includes
#include <errno.h>
#include <limits.h>
#include <stdlib.h>
#include <sys/types.h>
#ifdef _WIN32
#include "lldb/Host/windows/windows.h"
#include <winsock2.h>
#include <ws2tcpip.h>
#else
#include <unistd.h>
#include <dlfcn.h>
#include <grp.h>
#include <netdb.h>
#include <pwd.h>
#include <sys/stat.h>
#endif
#if !defined (__GNU__) && !defined (_WIN32)
// Does not exist under GNU/HURD or Windows
#include <sys/sysctl.h>
#endif
#if defined (__APPLE__)
#include <mach/mach_port.h>
#include <mach/mach_init.h>
#include <mach-o/dyld.h>
#include <AvailabilityMacros.h>
#endif
#if defined (__linux__) || defined (__FreeBSD__) || defined (__FreeBSD_kernel__) || defined (__APPLE__) || defined(__NetBSD__)
#include <spawn.h>
#include <sys/wait.h>
#include <sys/syscall.h>
#endif
#if defined (__FreeBSD__)
#include <pthread_np.h>
#endif
#include "lldb/Host/Host.h"
#include "lldb/Core/ArchSpec.h"
#include "lldb/Core/ConstString.h"
#include "lldb/Core/Debugger.h"
#include "lldb/Core/Error.h"
#include "lldb/Core/Log.h"
#include "lldb/Core/Module.h"
#include "lldb/Core/StreamString.h"
#include "lldb/Core/ThreadSafeSTLMap.h"
#include "lldb/Host/Config.h"
#include "lldb/Host/Endian.h"
#include "lldb/Host/FileSpec.h"
#include "lldb/Host/Mutex.h"
#include "lldb/Target/Process.h"
#include "lldb/Target/TargetList.h"
#include "lldb/Utility/CleanUp.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/raw_ostream.h"
#if defined (__APPLE__)
#ifndef _POSIX_SPAWN_DISABLE_ASLR
#define _POSIX_SPAWN_DISABLE_ASLR 0x0100
#endif
extern "C"
{
int __pthread_chdir(const char *path);
int __pthread_fchdir (int fildes);
}
#endif
using namespace lldb;
using namespace lldb_private;
#if !defined (__APPLE__) && !defined (_WIN32)
struct MonitorInfo
{
lldb::pid_t pid; // The process ID to monitor
Host::MonitorChildProcessCallback callback; // The callback function to call when "pid" exits or signals
void *callback_baton; // The callback baton for the callback function
bool monitor_signals; // If true, call the callback when "pid" gets signaled.
};
static thread_result_t
MonitorChildProcessThreadFunction (void *arg);
lldb::thread_t
Host::StartMonitoringChildProcess
(
Host::MonitorChildProcessCallback callback,
void *callback_baton,
lldb::pid_t pid,
bool monitor_signals
)
{
lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
MonitorInfo * info_ptr = new MonitorInfo();
info_ptr->pid = pid;
info_ptr->callback = callback;
info_ptr->callback_baton = callback_baton;
info_ptr->monitor_signals = monitor_signals;
char thread_name[256];
::snprintf (thread_name, sizeof(thread_name), "<lldb.host.wait4(pid=%" PRIu64 ")>", pid);
thread = ThreadCreate (thread_name,
MonitorChildProcessThreadFunction,
info_ptr,
NULL);
return thread;
}
//------------------------------------------------------------------
// Scoped class that will disable thread canceling when it is
// constructed, and exception safely restore the previous value it
// when it goes out of scope.
//------------------------------------------------------------------
class ScopedPThreadCancelDisabler
{
public:
ScopedPThreadCancelDisabler()
{
// Disable the ability for this thread to be cancelled
int err = ::pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &m_old_state);
if (err != 0)
m_old_state = -1;
}
~ScopedPThreadCancelDisabler()
{
// Restore the ability for this thread to be cancelled to what it
// previously was.
if (m_old_state != -1)
::pthread_setcancelstate (m_old_state, 0);
}
private:
int m_old_state; // Save the old cancelability state.
};
static thread_result_t
MonitorChildProcessThreadFunction (void *arg)
{
Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
const char *function = __FUNCTION__;
if (log)
log->Printf ("%s (arg = %p) thread starting...", function, arg);
MonitorInfo *info = (MonitorInfo *)arg;
const Host::MonitorChildProcessCallback callback = info->callback;
void * const callback_baton = info->callback_baton;
const bool monitor_signals = info->monitor_signals;
assert (info->pid <= UINT32_MAX);
const ::pid_t pid = monitor_signals ? -1 * getpgid(info->pid) : info->pid;
delete info;
int status = -1;
#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
#define __WALL 0
#endif
const int options = __WALL;
while (1)
{
log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
if (log)
log->Printf("%s ::wait_pid (pid = %" PRIi32 ", &status, options = %i)...", function, pid, options);
// Wait for all child processes
::pthread_testcancel ();
// Get signals from all children with same process group of pid
const ::pid_t wait_pid = ::waitpid (pid, &status, options);
::pthread_testcancel ();
if (wait_pid == -1)
{
if (errno == EINTR)
continue;
else
{
if (log)
log->Printf ("%s (arg = %p) thread exiting because waitpid failed (%s)...", __FUNCTION__, arg, strerror(errno));
break;
}
}
else if (wait_pid > 0)
{
bool exited = false;
int signal = 0;
int exit_status = 0;
const char *status_cstr = NULL;
if (WIFSTOPPED(status))
{
signal = WSTOPSIG(status);
status_cstr = "STOPPED";
}
else if (WIFEXITED(status))
{
exit_status = WEXITSTATUS(status);
status_cstr = "EXITED";
exited = true;
}
else if (WIFSIGNALED(status))
{
signal = WTERMSIG(status);
status_cstr = "SIGNALED";
if (wait_pid == abs(pid)) {
exited = true;
exit_status = -1;
}
}
else
{
status_cstr = "(\?\?\?)";
}
// Scope for pthread_cancel_disabler
{
ScopedPThreadCancelDisabler pthread_cancel_disabler;
log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
if (log)
log->Printf ("%s ::waitpid (pid = %" PRIi32 ", &status, options = %i) => pid = %" PRIi32 ", status = 0x%8.8x (%s), signal = %i, exit_state = %i",
function,
wait_pid,
options,
pid,
status,
status_cstr,
signal,
exit_status);
if (exited || (signal != 0 && monitor_signals))
{
bool callback_return = false;
if (callback)
callback_return = callback (callback_baton, wait_pid, exited, signal, exit_status);
// If our process exited, then this thread should exit
if (exited && wait_pid == abs(pid))
{
if (log)
log->Printf ("%s (arg = %p) thread exiting because pid received exit signal...", __FUNCTION__, arg);
break;
}
// If the callback returns true, it means this process should
// exit
if (callback_return)
{
if (log)
log->Printf ("%s (arg = %p) thread exiting because callback returned true...", __FUNCTION__, arg);
break;
}
}
}
}
}
log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
if (log)
log->Printf ("%s (arg = %p) thread exiting...", __FUNCTION__, arg);
return NULL;
}
#endif // #if !defined (__APPLE__) && !defined (_WIN32)
#if !defined (__APPLE__)
void
Host::SystemLog (SystemLogType type, const char *format, va_list args)
{
vfprintf (stderr, format, args);
}
#endif
void
Host::SystemLog (SystemLogType type, const char *format, ...)
{
va_list args;
va_start (args, format);
SystemLog (type, format, args);
va_end (args);
}
const ArchSpec &
Host::GetArchitecture (SystemDefaultArchitecture arch_kind)
{
static bool g_supports_32 = false;
static bool g_supports_64 = false;
static ArchSpec g_host_arch_32;
static ArchSpec g_host_arch_64;
#if defined (__APPLE__)
// Apple is different in that it can support both 32 and 64 bit executables
// in the same operating system running concurrently. Here we detect the
// correct host architectures for both 32 and 64 bit including if 64 bit
// executables are supported on the system.
if (g_supports_32 == false && g_supports_64 == false)
{
// All apple systems support 32 bit execution.
g_supports_32 = true;
uint32_t cputype, cpusubtype;
uint32_t is_64_bit_capable = false;
size_t len = sizeof(cputype);
ArchSpec host_arch;
// These will tell us about the kernel architecture, which even on a 64
// bit machine can be 32 bit...
if (::sysctlbyname("hw.cputype", &cputype, &len, NULL, 0) == 0)
{
len = sizeof (cpusubtype);
if (::sysctlbyname("hw.cpusubtype", &cpusubtype, &len, NULL, 0) != 0)
cpusubtype = CPU_TYPE_ANY;
len = sizeof (is_64_bit_capable);
if (::sysctlbyname("hw.cpu64bit_capable", &is_64_bit_capable, &len, NULL, 0) == 0)
{
if (is_64_bit_capable)
g_supports_64 = true;
}
if (is_64_bit_capable)
{
#if defined (__i386__) || defined (__x86_64__)
if (cpusubtype == CPU_SUBTYPE_486)
cpusubtype = CPU_SUBTYPE_I386_ALL;
#endif
if (cputype & CPU_ARCH_ABI64)
{
// We have a 64 bit kernel on a 64 bit system
g_host_arch_32.SetArchitecture (eArchTypeMachO, ~(CPU_ARCH_MASK) & cputype, cpusubtype);
g_host_arch_64.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
}
else
{
// We have a 32 bit kernel on a 64 bit system
g_host_arch_32.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
cputype |= CPU_ARCH_ABI64;
g_host_arch_64.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
}
}
else
{
g_host_arch_32.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
g_host_arch_64.Clear();
}
}
}
#else // #if defined (__APPLE__)
if (g_supports_32 == false && g_supports_64 == false)
{
llvm::Triple triple(llvm::sys::getDefaultTargetTriple());
g_host_arch_32.Clear();
g_host_arch_64.Clear();
// If the OS is Linux, "unknown" in the vendor slot isn't what we want
// for the default triple. It's probably an artifact of config.guess.
if (triple.getOS() == llvm::Triple::Linux && triple.getVendor() == llvm::Triple::UnknownVendor)
triple.setVendorName ("");
const char* distribution_id = GetDistributionId ().AsCString();
switch (triple.getArch())
{
default:
g_host_arch_32.SetTriple(triple);
g_host_arch_32.SetDistributionId (distribution_id);
g_supports_32 = true;
break;
case llvm::Triple::x86_64:
g_host_arch_64.SetTriple(triple);
g_host_arch_64.SetDistributionId (distribution_id);
g_supports_64 = true;
g_host_arch_32.SetTriple(triple.get32BitArchVariant());
g_host_arch_32.SetDistributionId (distribution_id);
g_supports_32 = true;
break;
case llvm::Triple::mips64:
case llvm::Triple::sparcv9:
case llvm::Triple::ppc64:
g_host_arch_64.SetTriple(triple);
g_host_arch_64.SetDistributionId (distribution_id);
g_supports_64 = true;
break;
}
g_supports_32 = g_host_arch_32.IsValid();
g_supports_64 = g_host_arch_64.IsValid();
}
#endif // #else for #if defined (__APPLE__)
if (arch_kind == eSystemDefaultArchitecture32)
return g_host_arch_32;
else if (arch_kind == eSystemDefaultArchitecture64)
return g_host_arch_64;
if (g_supports_64)
return g_host_arch_64;
return g_host_arch_32;
}
const ConstString &
Host::GetVendorString()
{
static ConstString g_vendor;
if (!g_vendor)
{
const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
const llvm::StringRef &str_ref = host_arch.GetTriple().getVendorName();
g_vendor.SetCStringWithLength(str_ref.data(), str_ref.size());
}
return g_vendor;
}
const ConstString &
Host::GetOSString()
{
static ConstString g_os_string;
if (!g_os_string)
{
const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
const llvm::StringRef &str_ref = host_arch.GetTriple().getOSName();
g_os_string.SetCStringWithLength(str_ref.data(), str_ref.size());
}
return g_os_string;
}
const ConstString &
Host::GetTargetTriple()
{
static ConstString g_host_triple;
if (!(g_host_triple))
{
const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
g_host_triple.SetCString(host_arch.GetTriple().getTriple().c_str());
}
return g_host_triple;
}
// See linux/Host.cpp for Linux-based implementations of this.
// Add your platform-specific implementation to the appropriate host file.
#if !defined(__linux__)
const ConstString &
Host::GetDistributionId ()
{
static ConstString s_distribution_id;
return s_distribution_id;
}
#endif // #if !defined(__linux__)
lldb::pid_t
Host::GetCurrentProcessID()
{
return ::getpid();
}
#ifndef _WIN32
lldb::tid_t
Host::GetCurrentThreadID()
{
#if defined (__APPLE__)
// Calling "mach_thread_self()" bumps the reference count on the thread
// port, so we need to deallocate it. mach_task_self() doesn't bump the ref
// count.
thread_port_t thread_self = mach_thread_self();
mach_port_deallocate(mach_task_self(), thread_self);
return thread_self;
#elif defined(__FreeBSD__)
return lldb::tid_t(pthread_getthreadid_np());
#elif defined(__linux__)
return lldb::tid_t(syscall(SYS_gettid));
#else
return lldb::tid_t(pthread_self());
#endif
}
lldb::thread_t
Host::GetCurrentThread ()
{
return lldb::thread_t(pthread_self());
}
const char *
Host::GetSignalAsCString (int signo)
{
switch (signo)
{
case SIGHUP: return "SIGHUP"; // 1 hangup
case SIGINT: return "SIGINT"; // 2 interrupt
case SIGQUIT: return "SIGQUIT"; // 3 quit
case SIGILL: return "SIGILL"; // 4 illegal instruction (not reset when caught)
case SIGTRAP: return "SIGTRAP"; // 5 trace trap (not reset when caught)
case SIGABRT: return "SIGABRT"; // 6 abort()
#if defined(SIGPOLL)
#if !defined(SIGIO) || (SIGPOLL != SIGIO)
// Under some GNU/Linux, SIGPOLL and SIGIO are the same. Causing the build to
// fail with 'multiple define cases with same value'
case SIGPOLL: return "SIGPOLL"; // 7 pollable event ([XSR] generated, not supported)
#endif
#endif
#if defined(SIGEMT)
case SIGEMT: return "SIGEMT"; // 7 EMT instruction
#endif
case SIGFPE: return "SIGFPE"; // 8 floating point exception
case SIGKILL: return "SIGKILL"; // 9 kill (cannot be caught or ignored)
case SIGBUS: return "SIGBUS"; // 10 bus error
case SIGSEGV: return "SIGSEGV"; // 11 segmentation violation
case SIGSYS: return "SIGSYS"; // 12 bad argument to system call
case SIGPIPE: return "SIGPIPE"; // 13 write on a pipe with no one to read it
case SIGALRM: return "SIGALRM"; // 14 alarm clock
case SIGTERM: return "SIGTERM"; // 15 software termination signal from kill
case SIGURG: return "SIGURG"; // 16 urgent condition on IO channel
case SIGSTOP: return "SIGSTOP"; // 17 sendable stop signal not from tty
case SIGTSTP: return "SIGTSTP"; // 18 stop signal from tty
case SIGCONT: return "SIGCONT"; // 19 continue a stopped process
case SIGCHLD: return "SIGCHLD"; // 20 to parent on child stop or exit
case SIGTTIN: return "SIGTTIN"; // 21 to readers pgrp upon background tty read
case SIGTTOU: return "SIGTTOU"; // 22 like TTIN for output if (tp->t_local<OSTOP)
#if defined(SIGIO)
case SIGIO: return "SIGIO"; // 23 input/output possible signal
#endif
case SIGXCPU: return "SIGXCPU"; // 24 exceeded CPU time limit
case SIGXFSZ: return "SIGXFSZ"; // 25 exceeded file size limit
case SIGVTALRM: return "SIGVTALRM"; // 26 virtual time alarm
case SIGPROF: return "SIGPROF"; // 27 profiling time alarm
#if defined(SIGWINCH)
case SIGWINCH: return "SIGWINCH"; // 28 window size changes
#endif
#if defined(SIGINFO)
case SIGINFO: return "SIGINFO"; // 29 information request
#endif
case SIGUSR1: return "SIGUSR1"; // 30 user defined signal 1
case SIGUSR2: return "SIGUSR2"; // 31 user defined signal 2
default:
break;
}
return NULL;
}
#endif
void
Host::WillTerminate ()
{
}
#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__) // see macosx/Host.mm
void
Host::ThreadCreated (const char *thread_name)
{
}
void
Host::Backtrace (Stream &strm, uint32_t max_frames)
{
// TODO: Is there a way to backtrace the current process on other systems?
}
size_t
Host::GetEnvironment (StringList &env)
{
// TODO: Is there a way to the host environment for this process on other systems?
return 0;
}
#endif // #if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__)
struct HostThreadCreateInfo
{
std::string thread_name;
thread_func_t thread_fptr;
thread_arg_t thread_arg;
HostThreadCreateInfo (const char *name, thread_func_t fptr, thread_arg_t arg) :
thread_name (name ? name : ""),
thread_fptr (fptr),
thread_arg (arg)
{
}
};
static thread_result_t
#ifdef _WIN32
__stdcall
#endif
ThreadCreateTrampoline (thread_arg_t arg)
{
HostThreadCreateInfo *info = (HostThreadCreateInfo *)arg;
Host::ThreadCreated (info->thread_name.c_str());
thread_func_t thread_fptr = info->thread_fptr;
thread_arg_t thread_arg = info->thread_arg;
Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
if (log)
log->Printf("thread created");
delete info;
return thread_fptr (thread_arg);
}
lldb::thread_t
Host::ThreadCreate
(
const char *thread_name,
thread_func_t thread_fptr,
thread_arg_t thread_arg,
Error *error
)
{
lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
// Host::ThreadCreateTrampoline will delete this pointer for us.
HostThreadCreateInfo *info_ptr = new HostThreadCreateInfo (thread_name, thread_fptr, thread_arg);
#ifdef _WIN32
thread = ::_beginthreadex(0, 0, ThreadCreateTrampoline, info_ptr, 0, NULL);
int err = thread <= 0 ? GetLastError() : 0;
#else
int err = ::pthread_create (&thread, NULL, ThreadCreateTrampoline, info_ptr);
#endif
if (err == 0)
{
if (error)
error->Clear();
return thread;
}
if (error)
error->SetError (err, eErrorTypePOSIX);
return LLDB_INVALID_HOST_THREAD;
}
#ifndef _WIN32
bool
Host::ThreadCancel (lldb::thread_t thread, Error *error)
{
int err = ::pthread_cancel (thread);
if (error)
error->SetError(err, eErrorTypePOSIX);
return err == 0;
}
bool
Host::ThreadDetach (lldb::thread_t thread, Error *error)
{
int err = ::pthread_detach (thread);
if (error)
error->SetError(err, eErrorTypePOSIX);
return err == 0;
}
bool
Host::ThreadJoin (lldb::thread_t thread, thread_result_t *thread_result_ptr, Error *error)
{
int err = ::pthread_join (thread, thread_result_ptr);
if (error)
error->SetError(err, eErrorTypePOSIX);
return err == 0;
}
lldb::thread_key_t
Host::ThreadLocalStorageCreate(ThreadLocalStorageCleanupCallback callback)
{
pthread_key_t key;
::pthread_key_create (&key, callback);
return key;
}
void*
Host::ThreadLocalStorageGet(lldb::thread_key_t key)
{
return ::pthread_getspecific (key);
}
void
Host::ThreadLocalStorageSet(lldb::thread_key_t key, void *value)
{
::pthread_setspecific (key, value);
}
bool
Host::SetThreadName (lldb::pid_t pid, lldb::tid_t tid, const char *name)
{
#if defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
lldb::pid_t curr_pid = Host::GetCurrentProcessID();
lldb::tid_t curr_tid = Host::GetCurrentThreadID();
if (pid == LLDB_INVALID_PROCESS_ID)
pid = curr_pid;
if (tid == LLDB_INVALID_THREAD_ID)
tid = curr_tid;
// Set the pthread name if possible
if (pid == curr_pid && tid == curr_tid)
{
if (::pthread_setname_np (name) == 0)
return true;
}
return false;
#elif defined (__FreeBSD__)
lldb::pid_t curr_pid = Host::GetCurrentProcessID();
lldb::tid_t curr_tid = Host::GetCurrentThreadID();
if (pid == LLDB_INVALID_PROCESS_ID)
pid = curr_pid;
if (tid == LLDB_INVALID_THREAD_ID)
tid = curr_tid;
// Set the pthread name if possible
if (pid == curr_pid && tid == curr_tid)
{
::pthread_set_name_np (::pthread_self(), name);
return true;
}
return false;
#elif defined (__linux__) || defined (__GLIBC__)
void *fn = dlsym (RTLD_DEFAULT, "pthread_setname_np");
if (fn)
{
lldb::pid_t curr_pid = Host::GetCurrentProcessID();
lldb::tid_t curr_tid = Host::GetCurrentThreadID();
if (pid == LLDB_INVALID_PROCESS_ID)
pid = curr_pid;
if (tid == LLDB_INVALID_THREAD_ID)
tid = curr_tid;
if (pid == curr_pid && tid == curr_tid)
{
int (*pthread_setname_np_func)(pthread_t thread, const char *name);
*reinterpret_cast<void **> (&pthread_setname_np_func) = fn;
if (pthread_setname_np_func (::pthread_self(), name) == 0)
return true;
}
}
return false;
#else
return false;
#endif
}
bool
Host::SetShortThreadName (lldb::pid_t pid, lldb::tid_t tid,
const char *thread_name, size_t len)
{
std::unique_ptr<char[]> namebuf(new char[len+1]);
// Thread names are coming in like '<lldb.comm.debugger.edit>' and
// '<lldb.comm.debugger.editline>'. So just chopping the end of the string
// off leads to a lot of similar named threads. Go through the thread name
// and search for the last dot and use that.
const char *lastdot = ::strrchr (thread_name, '.');
if (lastdot && lastdot != thread_name)
thread_name = lastdot + 1;
::strncpy (namebuf.get(), thread_name, len);
namebuf[len] = 0;
int namebuflen = strlen(namebuf.get());
if (namebuflen > 0)
{
if (namebuf[namebuflen - 1] == '(' || namebuf[namebuflen - 1] == '>')
{
// Trim off trailing '(' and '>' characters for a bit more cleanup.
namebuflen--;
namebuf[namebuflen] = 0;
}
return Host::SetThreadName (pid, tid, namebuf.get());
}
return false;
}
#endif
FileSpec
Host::GetProgramFileSpec ()
{
static FileSpec g_program_filespec;
if (!g_program_filespec)
{
#if defined (__APPLE__)
char program_fullpath[PATH_MAX];
// If DST is NULL, then return the number of bytes needed.
uint32_t len = sizeof(program_fullpath);
int err = _NSGetExecutablePath (program_fullpath, &len);
if (err == 0)
g_program_filespec.SetFile (program_fullpath, false);
else if (err == -1)
{
char *large_program_fullpath = (char *)::malloc (len + 1);
err = _NSGetExecutablePath (large_program_fullpath, &len);
if (err == 0)
g_program_filespec.SetFile (large_program_fullpath, false);
::free (large_program_fullpath);
}
#elif defined (__linux__)
char exe_path[PATH_MAX];
ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path) - 1);
if (len > 0) {
exe_path[len] = 0;
g_program_filespec.SetFile(exe_path, false);
}
#elif defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
int exe_path_mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, getpid() };
size_t exe_path_size;
if (sysctl(exe_path_mib, 4, NULL, &exe_path_size, NULL, 0) == 0)
{
char *exe_path = new char[exe_path_size];
if (sysctl(exe_path_mib, 4, exe_path, &exe_path_size, NULL, 0) == 0)
g_program_filespec.SetFile(exe_path, false);
delete[] exe_path;
}
#endif
}
return g_program_filespec;
}
#if !defined (__APPLE__) // see Host.mm
bool
Host::GetBundleDirectory (const FileSpec &file, FileSpec &bundle)
{
bundle.Clear();
return false;
}
bool
Host::ResolveExecutableInBundle (FileSpec &file)
{
return false;
}
#endif
#ifndef _WIN32
// Opaque info that tracks a dynamic library that was loaded
struct DynamicLibraryInfo
{
DynamicLibraryInfo (const FileSpec &fs, int o, void *h) :
file_spec (fs),
open_options (o),
handle (h)
{
}
const FileSpec file_spec;
uint32_t open_options;
void * handle;
};
void *
Host::DynamicLibraryOpen (const FileSpec &file_spec, uint32_t options, Error &error)
{
char path[PATH_MAX];
if (file_spec.GetPath(path, sizeof(path)))
{
int mode = 0;
if (options & eDynamicLibraryOpenOptionLazy)
mode |= RTLD_LAZY;
else
mode |= RTLD_NOW;
if (options & eDynamicLibraryOpenOptionLocal)
mode |= RTLD_LOCAL;
else
mode |= RTLD_GLOBAL;
#ifdef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
if (options & eDynamicLibraryOpenOptionLimitGetSymbol)
mode |= RTLD_FIRST;
#endif
void * opaque = ::dlopen (path, mode);
if (opaque)
{
error.Clear();
return new DynamicLibraryInfo (file_spec, options, opaque);
}
else
{
error.SetErrorString(::dlerror());
}
}
else
{
error.SetErrorString("failed to extract path");
}
return NULL;
}
Error
Host::DynamicLibraryClose (void *opaque)
{
Error error;
if (opaque == NULL)
{
error.SetErrorString ("invalid dynamic library handle");
}
else
{
DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
if (::dlclose (dylib_info->handle) != 0)
{
error.SetErrorString(::dlerror());
}
dylib_info->open_options = 0;
dylib_info->handle = 0;
delete dylib_info;
}
return error;
}
void *
Host::DynamicLibraryGetSymbol (void *opaque, const char *symbol_name, Error &error)
{
if (opaque == NULL)
{
error.SetErrorString ("invalid dynamic library handle");
}
else
{
DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
void *symbol_addr = ::dlsym (dylib_info->handle, symbol_name);
if (symbol_addr)
{
#ifndef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
// This host doesn't support limiting searches to this shared library
// so we need to verify that the match came from this shared library
// if it was requested in the Host::DynamicLibraryOpen() function.
if (dylib_info->open_options & eDynamicLibraryOpenOptionLimitGetSymbol)
{
FileSpec match_dylib_spec (Host::GetModuleFileSpecForHostAddress (symbol_addr));
if (match_dylib_spec != dylib_info->file_spec)
{
char dylib_path[PATH_MAX];
if (dylib_info->file_spec.GetPath (dylib_path, sizeof(dylib_path)))
error.SetErrorStringWithFormat ("symbol not found in \"%s\"", dylib_path);
else
error.SetErrorString ("symbol not found");
return NULL;
}
}
#endif
error.Clear();
return symbol_addr;
}
else
{
error.SetErrorString(::dlerror());
}
}
return NULL;
}
FileSpec
Host::GetModuleFileSpecForHostAddress (const void *host_addr)