12#include <AvailabilityMacros.h>
13#include <TargetConditionals.h>
16#define __XPC_PRIVATE_H__
19#define LaunchUsingXPCRightName "com.apple.lldb.RootDebuggingXPCService"
23#define LauncherXPCServiceAuthKey "auth-key"
24#define LauncherXPCServiceArgPrefxKey "arg"
25#define LauncherXPCServiceEnvPrefxKey "env"
26#define LauncherXPCServiceCPUTypeKey "cpuType"
27#define LauncherXPCServicePosixspawnFlagsKey "posixspawnFlags"
28#define LauncherXPCServiceStdInPathKeyKey "stdInPath"
29#define LauncherXPCServiceStdOutPathKeyKey "stdOutPath"
30#define LauncherXPCServiceStdErrPathKeyKey "stdErrPath"
31#define LauncherXPCServiceChildPIDKey "childPID"
32#define LauncherXPCServiceErrorTypeKey "errorType"
33#define LauncherXPCServiceCodeTypeKey "errorCode"
36#include <bsm/audit_session.h>
39#include "llvm/TargetParser/Host.h"
42#include <crt_externs.h>
52#include <sys/sysctl.h>
74#include "llvm/ADT/ScopeExit.h"
75#include "llvm/Support/Errno.h"
76#include "llvm/Support/FileSystem.h"
78#include "../cfcpp/CFCBundle.h"
79#include "../cfcpp/CFCMutableArray.h"
80#include "../cfcpp/CFCMutableDictionary.h"
81#include "../cfcpp/CFCReleaser.h"
82#include "../cfcpp/CFCString.h"
84#include <objc/objc-auto.h>
87#include <CoreFoundation/CoreFoundation.h>
88#include <Foundation/Foundation.h>
90#ifndef _POSIX_SPAWN_DISABLE_ASLR
91#define _POSIX_SPAWN_DISABLE_ASLR 0x0100
106 if (__builtin_available(macos 10.12, iOS 10, tvOS 10, watchOS 3, *)) {
108 g_os_log = os_log_create(
"com.apple.dt.lldb",
"lldb");
110 os_log(
g_os_log,
"%{public}s", message.str().c_str());
112 llvm::errs() << message;
118#if defined(__APPLE__)
121 if (file.
GetPath(path,
sizeof(path))) {
123 if (bundle.GetPath(path,
sizeof(path))) {
124 bundle_directory.
SetFile(path, FileSpec::Style::native);
130 bundle_directory.
Clear();
135#if defined(__APPLE__)
138 if (file.
GetPath(path,
sizeof(path))) {
142 if (::CFURLGetFileSystemRepresentation(url.get(), YES, (UInt8 *)path,
144 file.
SetFile(path, FileSpec::Style::native);
156static void *AcceptPIDFromInferior(
const char *connect_url) {
161 ::memset(pid_str, 0,
sizeof(pid_str));
163 const size_t pid_str_len = file_conn.
Read(
164 pid_str,
sizeof(pid_str), std::chrono::seconds(0), status, NULL);
165 if (pid_str_len > 0) {
166 int pid = atoi(pid_str);
167 return (
void *)(intptr_t)pid;
173const char *applscript_in_new_tty =
"tell application \"Terminal\"\n"
175 " do script \"/bin/bash -c '%s';exit\"\n"
178const char *applscript_in_existing_tty =
"\
179set the_shell_script to \"/bin/bash -c '%s';exit\"\n\
180tell application \"Terminal\"\n\
181 repeat with the_window in (get windows)\n\
182 repeat with the_tab in tabs of the_window\n\
183 set the_tty to tty in the_tab\n\
184 if the_tty contains \"%s\" then\n\
185 if the_tab is not busy then\n\
186 set selected of the_tab to true\n\
187 set frontmost of the_window to true\n\
188 do script the_shell_script in the_tab\n\
194 do script the_shell_script\n\
198LaunchInNewTerminalWithAppleScript(
const char *exe_path,
201 char unix_socket_name[
PATH_MAX] =
"/tmp/XXXXXX";
202 if (::mktemp(unix_socket_name) == NULL) {
203 error.SetErrorString(
"failed to make temporary path for a unix socket");
208 FileSpec darwin_debug_file_spec = HostInfo::GetSupportExeDir();
209 if (!darwin_debug_file_spec) {
210 error.SetErrorString(
"can't locate the 'darwin-debug' executable");
214 darwin_debug_file_spec.
SetFilename(
"darwin-debug");
217 error.SetErrorStringWithFormat(
218 "the 'darwin-debug' executable doesn't exists at '%s'",
219 darwin_debug_file_spec.
GetPath().c_str());
224 darwin_debug_file_spec.
GetPath(launcher_path,
sizeof(launcher_path));
232 command.
Printf(R
"(\"%s\" --unix-socket=%s)", launcher_path, unix_socket_name);
239 command.
Printf(R
"( --working-dir \"%s\")", working_dir.GetPath().c_str());
243 command.
Printf(R
"( --working-dir \"%s\")", cwd);
246 if (launch_info.
GetFlags().
Test(eLaunchFlagDisableASLR))
257 auto host_entry = host_env.find(KV.first());
258 if (host_entry == host_env.end() || host_entry->second != KV.second)
266 for (
size_t i = 0; argv[i] != NULL; ++i) {
268 command.
Printf(R
"( \"%s\")", exe_path);
270 command.
Printf(R
"( \"%s\")", argv[i]);
273 command.
Printf(R
"( \"%s\")", exe_path);
275 command.PutCString(" ; echo Process exited with status $?");
276 if (launch_info.
GetFlags().
Test(lldb::eLaunchFlagCloseTTYOnExit))
281 applescript_source.
Printf(applscript_in_new_tty,
284 NSAppleScript *applescript = [[NSAppleScript alloc]
285 initWithSource:[NSString stringWithCString:applescript_source.
GetString()
288 encoding:NSUTF8StringEncoding]];
295 char connect_url[128];
296 ::snprintf(connect_url,
sizeof(connect_url),
"unix-accept://%s",
306 unix_socket_name, [&] {
return AcceptPIDFromInferior(connect_url); });
309 return Status(accept_thread.takeError());
311 [applescript executeAndReturnError:nil];
314 lldb_error = accept_thread->Join(&accept_thread_result);
315 if (lldb_error.
Success() && accept_thread_result) {
316 pid = (intptr_t)accept_thread_result;
319 llvm::sys::fs::remove(unix_socket_name);
320 [applescript release];
346 CFCString file_cfstr(file_path, kCFStringEncodingUTF8);
348 NULL, file_cfstr.get(), kCFURLPOSIXPathStyle,
false));
351 "Sending source file: \"%s\" and line: %d to external editor.\n",
355 BabelAESelInfo file_and_line_info = {
357 (int16_t)(line_no - 1),
364 AEKeyDesc file_and_line_desc;
366 error = ::AECreateDesc(typeUTF8Text, &file_and_line_info,
367 sizeof(file_and_line_info),
368 &(file_and_line_desc.descContent));
370 if (
error != noErr) {
375 file_and_line_desc.descKey = keyAEPosition;
377 static std::string g_app_name;
378 static FSRef g_app_fsref;
380 LSApplicationParameters app_params;
381 ::memset(&app_params, 0,
sizeof(app_params));
383 kLSLaunchDefaults | kLSLaunchDontAddToRecents | kLSLaunchDontSwitch;
385 char *external_editor = ::getenv(
"LLDB_EXTERNAL_EDITOR");
387 if (external_editor) {
388 LLDB_LOGF(log,
"Looking for external editor \"%s\".\n", external_editor);
390 if (g_app_name.empty() ||
391 strcmp(g_app_name.c_str(), external_editor) != 0) {
392 CFCString editor_name(external_editor, kCFStringEncodingUTF8);
393 error = ::LSFindApplicationForInfo(kLSUnknownCreator, NULL,
394 editor_name.get(), &g_app_fsref, NULL);
398 if (
error != noErr) {
400 "Could not find External Editor application, error: %ld.\n",
405 app_params.application = &g_app_fsref;
408 ProcessSerialNumber psn;
410 CFArrayCreate(NULL, (
const void **)file_URL.ptr_address(
false), 1, NULL));
411 error = ::LSOpenURLsWithRole(file_array.get(), kLSRolesAll,
412 &file_and_line_desc, &app_params, &psn, 1);
414 AEDisposeDesc(&(file_and_line_desc.descContent));
416 if (
error != noErr) {
417 LLDB_LOGF(log,
"LSOpenURLsWithRole failed, error: %ld.\n",
error);
430 auditinfo_addr_t info;
431 getaudit_addr(&info,
sizeof(info));
432 return info.ai_flags & AU_SESSION_FLAG_HAS_GRAPHIC_ACCESS;
441 int mib[CTL_MAXNAME] = {
444 size_t mib_len = CTL_MAXNAME;
445 if (::sysctlnametomib(
"sysctl.proc_cputype", mib, &mib_len))
452 size_t len =
sizeof(cpu);
453 if (::sysctl(mib, mib_len, &cpu, &len, 0, 0) == 0) {
456 sub = CPU_SUBTYPE_I386_ALL;
458 case CPU_TYPE_X86_64:
459 sub = CPU_SUBTYPE_X86_64_ALL;
462#if defined(CPU_TYPE_ARM64) && defined(CPU_SUBTYPE_ARM64_ALL)
464 sub = CPU_SUBTYPE_ARM64_ALL;
468#if defined(CPU_TYPE_ARM64_32) && defined(CPU_SUBTYPE_ARM64_32_ALL)
470 sub = CPU_SUBTYPE_ARM64_32_ALL;
479 len =
sizeof(cpusubtype);
480 if (::sysctlbyname(
"hw.cpusubtype", &cpusubtype, &len, NULL, 0) == 0)
483 bool host_cpu_is_64bit;
485 size_t is64bit_capable_len =
sizeof(is64bit_capable);
487 sysctlbyname(
"hw.cpu64bit_capable", &is64bit_capable,
488 &is64bit_capable_len, NULL, 0) == 0;
495 if (host_cpu_is_64bit) {
496 sub = CPU_SUBTYPE_ARM_V7;
514 int proc_args_mib[3] = {CTL_KERN, KERN_PROCARGS2,
517 size_t arg_data_size = 0;
518 if (::sysctl(proc_args_mib, 3,
nullptr, &arg_data_size, NULL, 0) ||
520 arg_data_size = 8192;
527 if (::sysctl(proc_args_mib, 3, arg_data.GetBytes(), &arg_data_size, NULL,
534 const llvm::Triple::ArchType triple_arch = triple.getArch();
535 const bool check_for_ios_simulator =
536 (triple_arch == llvm::Triple::x86 ||
537 triple_arch == llvm::Triple::x86_64);
538 const char *cstr = data.
GetCStr(&offset);
542 if (match_info_ptr == NULL ||
549 const uint8_t *p = data.
PeekData(offset, 1);
550 if ((p == NULL) || (*p !=
'\0'))
556 for (
int i = 0; i < static_cast<int>(argc); ++i) {
563 while ((cstr = data.
GetCStr(&offset))) {
567 if (check_for_ios_simulator) {
568 if (strncmp(cstr,
"SIMULATOR_UDID=", strlen(
"SIMULATOR_UDID=")) ==
574 llvm::Triple::MacOSX);
592 mib[2] = KERN_PROC_PID;
594 struct kinfo_proc proc_kinfo;
595 size_t proc_kinfo_size =
sizeof(
struct kinfo_proc);
597 if (::sysctl(mib, 4, &proc_kinfo, &proc_kinfo_size, NULL, 0) == 0) {
598 if (proc_kinfo_size > 0) {
600 process_info.
SetUserID(proc_kinfo.kp_eproc.e_pcred.p_ruid);
601 process_info.
SetGroupID(proc_kinfo.kp_eproc.e_pcred.p_rgid);
603 if (proc_kinfo.kp_eproc.e_ucred.cr_ngroups > 0)
605 proc_kinfo.kp_eproc.e_ucred.cr_groups[0]);
622 std::vector<struct kinfo_proc> kinfos;
624 int mib[3] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL};
626 size_t pid_data_size = 0;
627 if (::sysctl(mib, 3,
nullptr, &pid_data_size,
nullptr, 0) != 0)
631 const size_t estimated_pid_count =
632 (pid_data_size /
sizeof(
struct kinfo_proc)) + 10;
634 kinfos.resize(estimated_pid_count);
635 pid_data_size = kinfos.size() *
sizeof(
struct kinfo_proc);
637 if (::sysctl(mib, 3, &kinfos[0], &pid_data_size,
nullptr, 0) != 0)
640 const size_t actual_pid_count = (pid_data_size /
sizeof(
struct kinfo_proc));
644 const uid_t our_uid = getuid();
645 for (
size_t i = 0; i < actual_pid_count; i++) {
646 const struct kinfo_proc &kinfo = kinfos[i];
648 bool kinfo_user_matches =
false;
650 kinfo_user_matches =
true;
652 kinfo_user_matches = kinfo.kp_eproc.e_pcred.p_ruid == our_uid;
656 kinfo_user_matches =
true;
658 if (!kinfo_user_matches ||
661 kinfo.kp_proc.p_pid == 0 ||
662 kinfo.kp_proc.p_stat == SZOMB ||
663 kinfo.kp_proc.p_flag & P_TRACED ||
664 kinfo.kp_proc.p_flag & P_WEXIT)
670 process_info.
SetUserID(kinfo.kp_eproc.e_pcred.p_ruid);
671 process_info.
SetGroupID(kinfo.kp_eproc.e_pcred.p_rgid);
673 if (kinfo.kp_eproc.e_ucred.cr_ngroups > 0)
687 if (match_info.
Matches(process_info))
688 process_infos.push_back(process_info);
692 return process_infos.size();
697 bool success =
false;
713 process_info.
Clear();
718static void PackageXPCArguments(xpc_object_t message,
const char *prefix,
723 sprintf(buf,
"%sCount", prefix);
724 xpc_dictionary_set_int64(message, buf, count);
725 for (
size_t i = 0; i < count; i++) {
727 sprintf(buf,
"%s%zi", prefix, i);
732static void PackageXPCEnvironment(xpc_object_t message, llvm::StringRef prefix,
734 xpc_dictionary_set_int64(message, (prefix +
"Count").str().c_str(),
737 for (
const auto &KV : env) {
738 xpc_dictionary_set_string(message, (prefix + llvm::Twine(i)).str().c_str(),
749static AuthorizationRef authorizationRef = NULL;
754 if ((launch_info.
GetUserID() == 0) && !authorizationRef) {
755 OSStatus createStatus =
756 AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment,
757 kAuthorizationFlagDefaults, &authorizationRef);
758 if (createStatus != errAuthorizationSuccess) {
760 error.SetErrorString(
"Can't create authorizationRef.");
765 OSStatus rightsStatus =
766 AuthorizationRightGet(LaunchUsingXPCRightName, NULL);
767 if (rightsStatus != errAuthorizationSuccess) {
770 CFSTR(
"Xcode is trying to take control of a root process.");
771 CFStringRef keys[] = {CFSTR(
"en")};
772 CFTypeRef values[] = {prompt};
773 CFDictionaryRef promptDict = CFDictionaryCreate(
774 kCFAllocatorDefault, (
const void **)keys, (
const void **)values, 1,
775 &kCFCopyStringDictionaryKeyCallBacks,
776 &kCFTypeDictionaryValueCallBacks);
778 CFStringRef keys1[] = {CFSTR(
"class"), CFSTR(
"group"), CFSTR(
"comment"),
779 CFSTR(
"default-prompt"), CFSTR(
"shared")};
780 CFTypeRef values1[] = {CFSTR(
"user"), CFSTR(
"admin"),
781 CFSTR(LaunchUsingXPCRightName), promptDict,
783 CFDictionaryRef dict = CFDictionaryCreate(
784 kCFAllocatorDefault, (
const void **)keys1, (
const void **)values1, 5,
785 &kCFCopyStringDictionaryKeyCallBacks,
786 &kCFTypeDictionaryValueCallBacks);
787 rightsStatus = AuthorizationRightSet(
788 authorizationRef, LaunchUsingXPCRightName, dict, NULL, NULL, NULL);
789 CFRelease(promptDict);
793 OSStatus copyRightStatus = errAuthorizationDenied;
794 if (rightsStatus == errAuthorizationSuccess) {
795 AuthorizationItem item1 = {LaunchUsingXPCRightName, 0, NULL, 0};
796 AuthorizationItem items[] = {item1};
797 AuthorizationRights requestedRights = {1, items};
798 AuthorizationFlags authorizationFlags =
799 kAuthorizationFlagInteractionAllowed | kAuthorizationFlagExtendRights;
800 copyRightStatus = AuthorizationCopyRights(
801 authorizationRef, &requestedRights, kAuthorizationEmptyEnvironment,
802 authorizationFlags, NULL);
805 if (copyRightStatus != errAuthorizationSuccess) {
812 error.SetErrorStringWithFormat(
813 "Launching as root needs root authorization.");
816 if (authorizationRef) {
817 AuthorizationFree(authorizationRef, kAuthorizationFlagDefaults);
818 authorizationRef = NULL;
828 short flags = POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK;
831 flags |= POSIX_SPAWN_SETEXEC;
834 flags |= POSIX_SPAWN_START_SUSPENDED;
836 if (launch_info.
GetFlags().
Test(eLaunchFlagDisableASLR))
840 flags |= POSIX_SPAWN_SETPGROUP;
842#ifdef POSIX_SPAWN_CLOEXEC_DEFAULT
843#if defined(__x86_64__) || defined(__i386__)
848 llvm::VersionTuple version = HostInfo::GetOSVersion();
849 if (version > llvm::VersionTuple(10, 7)) {
860 flags |= POSIX_SPAWN_CLOEXEC_DEFAULT;
875 uid_t requested_uid = launch_info.
GetUserID();
876 const char *xpc_service = nil;
877 bool send_auth =
false;
878 AuthorizationExternalForm extForm;
879 if (requested_uid == 0) {
880 if (AuthorizationMakeExternalForm(authorizationRef, &extForm) ==
881 errAuthorizationSuccess) {
885 error.SetErrorStringWithFormat(
"Launching root via XPC needs to "
886 "externalize authorization reference.");
890 xpc_service = LaunchUsingXPCRightName;
893 error.SetErrorStringWithFormat(
894 "Launching via XPC is only currently available for root.");
899 xpc_connection_t conn = xpc_connection_create(xpc_service, NULL);
901 xpc_connection_set_event_handler(conn, ^(xpc_object_t event) {
902 xpc_type_t type = xpc_get_type(event);
904 if (type == XPC_TYPE_ERROR) {
905 if (event == XPC_ERROR_CONNECTION_INTERRUPTED) {
912 }
else if (event == XPC_ERROR_CONNECTION_INVALID) {
929 xpc_connection_set_finalizer_f(conn, xpc_finalizer_t(xpc_release));
930 xpc_connection_resume(conn);
931 xpc_object_t message = xpc_dictionary_create(nil, nil, 0);
934 xpc_dictionary_set_data(message, LauncherXPCServiceAuthKey, extForm.bytes,
935 sizeof(AuthorizationExternalForm));
938 PackageXPCArguments(message, LauncherXPCServiceArgPrefxKey,
940 PackageXPCEnvironment(message, LauncherXPCServiceEnvPrefxKey,
944 xpc_dictionary_set_int64(message, LauncherXPCServiceCPUTypeKey,
946 xpc_dictionary_set_int64(message, LauncherXPCServicePosixspawnFlagsKey,
949 if (file_action && !file_action->
GetPath().empty()) {
950 xpc_dictionary_set_string(message, LauncherXPCServiceStdInPathKeyKey,
951 file_action->
GetPath().str().c_str());
954 if (file_action && !file_action->
GetPath().empty()) {
955 xpc_dictionary_set_string(message, LauncherXPCServiceStdOutPathKeyKey,
956 file_action->
GetPath().str().c_str());
959 if (file_action && !file_action->
GetPath().empty()) {
960 xpc_dictionary_set_string(message, LauncherXPCServiceStdErrPathKeyKey,
961 file_action->
GetPath().str().c_str());
965 xpc_connection_send_message_with_reply_sync(conn, message);
966 xpc_type_t returnType = xpc_get_type(reply);
967 if (returnType == XPC_TYPE_DICTIONARY) {
968 pid = xpc_dictionary_get_int64(reply, LauncherXPCServiceChildPIDKey);
971 xpc_dictionary_get_int64(reply, LauncherXPCServiceErrorTypeKey);
973 xpc_dictionary_get_int64(reply, LauncherXPCServiceCodeTypeKey);
976 error.SetErrorStringWithFormat(
977 "Problems with launching via XPC. Error type : %i, code : %i",
978 errorType, errorCode);
981 if (authorizationRef) {
982 AuthorizationFree(authorizationRef, kAuthorizationFlagDefaults);
983 authorizationRef = NULL;
986 }
else if (returnType == XPC_TYPE_ERROR) {
988 error.SetErrorStringWithFormat(
989 "Problems with launching via XPC. XPC error : %s",
990 xpc_dictionary_get_string(reply, XPC_ERROR_KEY_DESCRIPTION));
1006 posix_spawn_file_actions_t *file_actions =
1007 static_cast<posix_spawn_file_actions_t *
>(_file_actions);
1015 if (info->
GetFD() == -1)
1016 error.SetErrorString(
1017 "invalid fd for posix_spawn_file_actions_addclose(...)");
1020 ::posix_spawn_file_actions_addclose(file_actions, info->
GetFD()),
1024 "error: {0}, posix_spawn_file_actions_addclose "
1025 "(action={1}, fd={2})",
1031 if (info->
GetFD() == -1)
1032 error.SetErrorString(
1033 "invalid fd for posix_spawn_file_actions_adddup2(...)");
1035 error.SetErrorString(
1036 "invalid duplicate fd for posix_spawn_file_actions_adddup2(...)");
1039 ::posix_spawn_file_actions_adddup2(file_actions, info->
GetFD(),
1044 "error: {0}, posix_spawn_file_actions_adddup2 "
1045 "(action={1}, fd={2}, dup_fd={3})",
1051 if (info->
GetFD() == -1)
1052 error.SetErrorString(
1053 "invalid fd in posix_spawn_file_actions_addopen(...)");
1059 if (oflag & O_CREAT)
1062 error.SetError(::posix_spawn_file_actions_addopen(
1063 file_actions, info->
GetFD(),
1064 info->
GetPath().str().c_str(), oflag, mode),
1068 "error: {0}, posix_spawn_file_actions_addopen (action={1}, "
1069 "fd={2}, path='{3}', oflag={4}, mode={5})",
1075 return error.Success();
1084 posix_spawnattr_t attr;
1088 LLDB_LOG(log,
"error: {0}, ::posix_spawnattr_init ( &attr )",
error);
1094 llvm::make_scope_exit([&]() { posix_spawnattr_destroy(&attr); });
1096 sigset_t no_signals;
1097 sigset_t all_signals;
1098 sigemptyset(&no_signals);
1099 sigfillset(&all_signals);
1100 ::posix_spawnattr_setsigmask(&attr, &no_signals);
1101 ::posix_spawnattr_setsigdefault(&attr, &all_signals);
1108 "error: {0}, ::posix_spawnattr_setflags ( &attr, flags={1:x} )",
1113 bool is_graphical =
true;
1116 SecuritySessionId session_id;
1117 SessionAttributeBits session_attributes;
1119 SessionGetInfo(callerSecuritySession, &session_id, &session_attributes);
1120 if (status == errSessionSuccess)
1121 is_graphical = session_attributes & sessionHasGraphicAccess;
1127 if (is_graphical && launch_info.
GetFlags().
Test(eLaunchFlagDebug) &&
1128 !launch_info.
GetFlags().
Test(eLaunchFlagInheritTCCFromParent)) {
1131 LLDB_LOG(log,
"error: {0}, setup_posix_spawn_responsible_flag(&attr)",
1145 const bool set_cpu_type =
1148 const bool set_cpu_subtype =
1154 typedef int (*posix_spawnattr_setarchpref_np_t)(
1156 posix_spawnattr_setarchpref_np_t posix_spawnattr_setarchpref_np_fn =
1157 (posix_spawnattr_setarchpref_np_t)dlsym(
1158 RTLD_DEFAULT,
"posix_spawnattr_setarchpref_np");
1159 if (set_cpu_subtype && posix_spawnattr_setarchpref_np_fn) {
1160 error.SetError((*posix_spawnattr_setarchpref_np_fn)(
1161 &attr, 1, &cpu_type, &cpu_subtype, &ocount),
1165 "error: {0}, ::posix_spawnattr_setarchpref_np ( &attr, 1, "
1166 "cpu_type = {1:x}, cpu_subtype = {1:x}, count => {2} )",
1167 error, cpu_type, cpu_subtype, ocount);
1169 if (
error.Fail() || ocount != 1)
1173 ::posix_spawnattr_setbinpref_np(&attr, 1, &cpu_type, &ocount),
1177 "error: {0}, ::posix_spawnattr_setbinpref_np ( &attr, 1, "
1178 "cpu_type = {1:x}, count => {2} )",
1179 error, cpu_type, ocount);
1180 if (
error.Fail() || ocount != 1)
1186 const char *tmp_argv[2];
1187 char *
const *argv =
const_cast<char *
const *
>(
1195 tmp_argv[0] = exe_path;
1197 argv =
const_cast<char *
const *
>(tmp_argv);
1203 std::string working_dir_path = working_dir.
GetPath();
1205 if (errno == ENOENT) {
1206 error.SetErrorStringWithFormat(
"No such file or directory: %s",
1207 working_dir_path.c_str());
1208 }
else if (errno == ENOTDIR) {
1209 error.SetErrorStringWithFormat(
"Path doesn't name a directory: %s",
1210 working_dir_path.c_str());
1212 error.SetErrorStringWithFormat(
"An unknown error occurred when "
1213 "changing directory for process "
1222 if (num_file_actions > 0) {
1223 posix_spawn_file_actions_t file_actions;
1224 error.SetError(::posix_spawn_file_actions_init(&file_actions),
1228 "error: {0}, ::posix_spawn_file_actions_init ( &file_actions )",
1234 auto cleanup_fileact = llvm::make_scope_exit(
1235 [&]() { posix_spawn_file_actions_destroy(&file_actions); });
1237 for (
size_t i = 0; i < num_file_actions; ++i) {
1240 if (launch_file_action) {
1248 ::posix_spawnp(&result_pid, exe_path, &file_actions, &attr, argv, envp),
1253 "error: {0}, ::posix_spawnp(pid => {1}, path = '{2}', "
1254 "file_actions = {3}, "
1255 "attr = {4}, argv = {5}, envp = {6} )",
1256 error, result_pid, exe_path, &file_actions, &attr, argv,
1259 for (
int ii = 0; argv[ii]; ++ii)
1260 LLDB_LOG(log,
"argv[{0}] = '{1}'", ii, argv[ii]);
1266 ::posix_spawnp(&result_pid, exe_path, NULL, &attr, argv, envp),
1271 "error: {0}, ::posix_spawnp ( pid => {1}, path = '{2}', "
1272 "file_actions = NULL, attr = {3}, argv = {4}, envp = {5} )",
1273 error, result_pid, exe_path, &attr, argv, envp.
get());
1275 for (
int ii = 0; argv[ii]; ++ii)
1276 LLDB_LOG(log,
"argv[{0}] = '{1}'", ii, argv[ii]);
1291 bool result =
false;
1294 bool launchingAsRoot = launch_info.
GetUserID() == 0;
1295 bool currentUserIsRoot = HostInfo::GetEffectiveUserID() == 0;
1297 if (launchingAsRoot && !currentUserIsRoot) {
1312 if (!fs.
Exists(exe_spec))
1315 if (!fs.
Exists(exe_spec))
1318 if (!fs.
Exists(exe_spec)) {
1319 error.SetErrorStringWithFormatv(
"executable doesn't exist: '{0}'",
1324 if (launch_info.
GetFlags().
Test(eLaunchFlagLaunchInTTY)) {
1326 return LaunchInNewTerminalWithAppleScript(exe_spec.GetPath().c_str(),
1329 error.SetErrorString(
"launching a process in a new terminal is not "
1330 "supported on iOS devices");
1337 auto exe_path = exe_spec.GetPath();
1354 if (
error.Success())
1355 error.SetErrorString(
"process launch failed for unknown reasons");
1362 if (launch_info.
GetFlags().
Test(eLaunchFlagShellExpandArguments)) {
1363 FileSpec expand_tool_spec = HostInfo::GetSupportExeDir();
1364 if (!expand_tool_spec) {
1365 error.SetErrorString(
1366 "could not get support executable directory for lldb-argdumper tool");
1371 error.SetErrorStringWithFormat(
1372 "could not find the lldb-argdumper tool: %s",
1373 expand_tool_spec.
GetPath().c_str());
1378 expand_tool_spec_stream.
Printf(
"\"%s\"",
1379 expand_tool_spec.
GetPath().c_str());
1381 Args expand_command(expand_tool_spec_stream.
GetData());
1382 expand_command.AppendArguments(launch_info.
GetArguments());
1388 char *wd = getcwd(
nullptr, 0);
1389 if (wd ==
nullptr) {
1390 error.SetErrorStringWithFormat(
1391 "cwd does not exist; cannot launch with shell argument expansion");
1399 bool run_in_shell =
true;
1400 bool hide_stderr =
true;
1403 std::chrono::seconds(10), run_in_shell, hide_stderr);
1409 error.SetErrorStringWithFormat(
"lldb-argdumper exited with error %d",
1416 error.SetErrorString(
"invalid JSON");
1420 auto dict_sp = data_sp->GetAsDictionary();
1422 error.SetErrorString(
"invalid JSON");
1426 auto args_sp = dict_sp->GetObjectForDotSeparatedPath(
"arguments");
1428 error.SetErrorString(
"invalid JSON");
1432 auto args_array_sp = args_sp->GetAsArray();
1433 if (!args_array_sp) {
1434 error.SetErrorString(
"invalid JSON");
1440 for (
size_t i = 0; i < args_array_sp->GetSize(); i++) {
1441 auto item_sp = args_array_sp->GetItemAtIndex(i);
1444 auto str_sp = item_sp->GetAsString();
1457 unsigned long mask = DISPATCH_PROC_EXIT;
1461 dispatch_source_t source = ::dispatch_source_create(
1462 DISPATCH_SOURCE_TYPE_PROC, pid, mask,
1463 ::dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0));
1466 "Host::StartMonitoringChildProcess(callback, pid=%i) source = %p\n",
1467 static_cast<int>(pid),
static_cast<void *
>(source));
1471 ::dispatch_source_set_cancel_handler(source, ^{
1472 dispatch_release(source);
1474 ::dispatch_source_set_event_handler(source, ^{
1478 wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, pid, &status, 0);
1479 if (wait_pid >= 0) {
1481 int exit_status = 0;
1482 const char *status_cstr = NULL;
1483 if (WIFEXITED(status)) {
1484 exit_status = WEXITSTATUS(status);
1485 status_cstr =
"EXITED";
1486 }
else if (WIFSIGNALED(status)) {
1487 signal = WTERMSIG(status);
1488 status_cstr =
"SIGNALED";
1491 llvm_unreachable(
"Unknown status");
1495 "::waitpid (pid = %llu, &status, 0) => pid = %i, status "
1496 "= 0x%8.8x (%s), signal = %i, exit_status = %i",
1497 pid, wait_pid, status, status_cstr, signal, exit_status);
1500 callback_copy(pid, signal, exit_status);
1502 ::dispatch_source_cancel(source);
1506 ::dispatch_resume(source);
static llvm::raw_ostream & error(Stream &strm)
#define CPU_SUBTYPE_X86_64_H
#define CPU_TYPE_ARM64_32
static Status LaunchProcessPosixSpawn(const char *exe_path, const ProcessLaunchInfo &launch_info, lldb::pid_t &pid)
static Status LaunchProcessXPC(const char *exe_path, ProcessLaunchInfo &launch_info, lldb::pid_t &pid)
static short GetPosixspawnFlags(const ProcessLaunchInfo &launch_info)
#define _POSIX_SPAWN_DISABLE_ASLR
int __pthread_chdir(const char *path)
static bool GetMacOSXProcessUserAndGroup(ProcessInstanceInfo &process_info)
static std::once_flag g_os_log_once
static bool GetMacOSXProcessCPUType(ProcessInstanceInfo &process_info)
int __pthread_fchdir(int fildes)
static bool ShouldLaunchUsingXPC(ProcessLaunchInfo &launch_info)
static bool AddPosixSpawnFileAction(void *_file_actions, const FileAction *info, Log *log, Status &error)
static bool GetMacOSXProcessArgs(const ProcessInstanceInfoMatch *match_info_ptr, ProcessInstanceInfo &process_info)
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
#define LLDB_LOGF(log,...)
static int setup_posix_spawn_responsible_flag(posix_spawnattr_t *attr)
An architecture specification class.
bool IsValid() const
Tests if this ArchSpec is valid.
void Clear()
Clears the object state.
llvm::Triple & GetTriple()
Architecture triple accessor.
bool SetArchitecture(ArchitectureType arch_type, uint32_t cpu, uint32_t sub, uint32_t os=0)
Change the architecture object type, CPU type and OS type.
uint32_t GetMachOCPUSubType() const
uint32_t GetMachOCPUType() const
const char * GetArchitectureName() const
Returns a static string representing the current architecture.
A command line argument class.
size_t GetArgumentCount() const
Gets the number of arguments left in this command object.
void AppendArgument(llvm::StringRef arg_str, char quote_char='\0')
Appends a new argument to the end of the list argument list.
const char * GetArgumentAtIndex(size_t idx) const
Gets the NULL terminated C string argument pointer for the argument at index idx.
const char ** GetConstArgumentVector() const
Gets the argument vector.
void Clear()
Clear the arguments.
lldb::ConnectionStatus Connect(llvm::StringRef url, Status *error_ptr) override
Connect using the connect string url.
size_t Read(void *dst, size_t dst_len, const Timeout< std::micro > &timeout, lldb::ConnectionStatus &status, Status *error_ptr) override
The read function that attempts to read from the connection.
const char * GetCString() const
Get the string value as a C string.
A subclass of DataBuffer that stores a data buffer on the heap.
lldb::offset_t GetByteSize() const override
char *const * get() const
static std::string compose(const value_type &KeyValue)
std::pair< iterator, bool > insert(llvm::StringRef KeyEqValue)
llvm::StringRef GetPath() const
int GetActionArgument() const
void SetFile(llvm::StringRef path, Style style)
Change the file specified with a new path.
void AppendPathComponent(llvm::StringRef component)
const ConstString & GetFilename() const
Filename string const get accessor.
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
void Clear()
Clears the object state.
void SetFilename(ConstString filename)
Filename string set accessor.
void Resolve(llvm::SmallVectorImpl< char > &path)
Resolve path to make it canonical.
bool ResolveExecutableLocation(FileSpec &file_spec)
Call into the Host to see if it can help find the file.
bool Exists(const FileSpec &file_spec) const
Returns whether the given file exists.
static FileSystem & Instance()
bool Test(ValueType bit) const
Test a single flag bit.
static Status LaunchProcess(ProcessLaunchInfo &launch_info)
Launch the process specified in launch_info.
static bool OpenFileInExternalEditor(const FileSpec &file_spec, uint32_t line_no)
static bool ResolveExecutableInBundle(FileSpec &file)
When executable files may live within a directory, where the directory represents an executable bundl...
static Status ShellExpandArguments(ProcessLaunchInfo &launch_info)
Perform expansion of the command-line for this launch info This can potentially involve wildcard expa...
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 Environment GetEnvironment()
static void SystemLog(llvm::StringRef message)
Emit the given message to the operating system log.
static uint32_t FindProcessesImpl(const ProcessInstanceInfoMatch &match_info, ProcessInstanceInfoList &proc_infos)
static bool GetProcessInfo(lldb::pid_t pid, ProcessInstanceInfo &proc_info)
std::function< void(lldb::pid_t pid, int signal, int status)> MonitorChildProcessCallback
static llvm::Expected< HostThread > StartMonitoringChildProcess(const MonitorChildProcessCallback &callback, lldb::pid_t pid)
Start monitoring a child process.
static bool IsInteractiveGraphicSession()
Check if we're running in an interactive graphical session.
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...
void SetGroupID(uint32_t gid)
bool ProcessIDIsValid() const
const char * GetName() const
lldb::pid_t GetProcessID() const
void SetProcessID(lldb::pid_t pid)
FileSpec & GetExecutableFile()
uint32_t GetUserID() const
Environment & GetEnvironment()
void SetUserID(uint32_t uid)
ArchSpec & GetArchitecture()
NameMatch GetNameMatchType() const
bool Matches(const ProcessInstanceInfo &proc_info) const
bool GetMatchAllUsers() const
ProcessInstanceInfo & GetProcessInfo()
bool ProcessIDsMatch(const ProcessInstanceInfo &proc_info) const
Return true iff the process ID and parent process IDs in this object match the ones in proc_info.
bool UserIDsMatch(const ProcessInstanceInfo &proc_info) const
Return true iff the (both effective and real) user and group IDs in this object match the ones in pro...
void SetEffectiveGroupID(uint32_t gid)
void SetParentProcessID(lldb::pid_t pid)
void SetEffectiveUserID(uint32_t uid)
const FileSpec & GetShell() const
bool MonitorProcess() const
const FileAction * GetFileActionAtIndex(size_t idx) const
const FileAction * GetFileActionForFD(int fd) const
bool GetLaunchInSeparateProcessGroup() const
void SetWorkingDirectory(const FileSpec &working_dir)
const FileSpec & GetWorkingDirectory() const
size_t GetNumFileActions() const
bool Fail() const
Test for error condition.
bool Success() const
Test for success condition.
const char * GetData() const
llvm::StringRef GetString() const
void Format(const char *format, Args &&... args)
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
static ObjectSP ParseJSON(const std::string &json_text)
static llvm::Expected< HostThread > LaunchThread(llvm::StringRef name, std::function< lldb::thread_result_t()> thread_function, size_t min_stack_byte_size=0)
#define LLDB_INVALID_CPUTYPE
#define UNUSED_IF_ASSERT_DISABLED(x)
#define LLDB_INVALID_PROCESS_ID
lldb::ByteOrder InlHostByteOrder()
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.
bool NameMatches(llvm::StringRef name, NameMatch match_type, llvm::StringRef match)
std::vector< ProcessInstanceInfo > ProcessInstanceInfoList
ConnectionStatus
Connection Status Types.
@ eConnectionStatusSuccess
Success.
@ eErrorTypeGeneric
Generic errors that can be any value.
@ eErrorTypePOSIX
POSIX error codes.