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");
113 os_log(
g_os_log,
"%{public}s", message.str().c_str());
116 os_log_error(
g_os_log,
"%{public}s", message.str().c_str());
120 llvm::errs() << message;
126#if defined(__APPLE__)
129 if (file.
GetPath(path,
sizeof(path))) {
131 if (bundle.GetPath(path,
sizeof(path))) {
132 bundle_directory.
SetFile(path, FileSpec::Style::native);
138 bundle_directory.
Clear();
143#if defined(__APPLE__)
146 if (file.
GetPath(path,
sizeof(path))) {
150 if (::CFURLGetFileSystemRepresentation(url.get(), YES, (UInt8 *)path,
152 file.
SetFile(path, FileSpec::Style::native);
164static void *AcceptPIDFromInferior(
const char *connect_url) {
169 ::memset(pid_str, 0,
sizeof(pid_str));
171 const size_t pid_str_len = file_conn.
Read(
172 pid_str,
sizeof(pid_str), std::chrono::seconds(0), status, NULL);
173 if (pid_str_len > 0) {
174 int pid = atoi(pid_str);
175 return (
void *)(intptr_t)pid;
181const char *applscript_in_new_tty =
"tell application \"Terminal\"\n"
183 " do script \"/bin/bash -c '%s';exit\"\n"
186const char *applscript_in_existing_tty =
"\
187set the_shell_script to \"/bin/bash -c '%s';exit\"\n\
188tell application \"Terminal\"\n\
189 repeat with the_window in (get windows)\n\
190 repeat with the_tab in tabs of the_window\n\
191 set the_tty to tty in the_tab\n\
192 if the_tty contains \"%s\" then\n\
193 if the_tab is not busy then\n\
194 set selected of the_tab to true\n\
195 set frontmost of the_window to true\n\
196 do script the_shell_script in the_tab\n\
202 do script the_shell_script\n\
206LaunchInNewTerminalWithAppleScript(
const char *exe_path,
209 char unix_socket_name[
PATH_MAX] =
"/tmp/XXXXXX";
210 if (::mktemp(unix_socket_name) == NULL) {
211 error.SetErrorString(
"failed to make temporary path for a unix socket");
216 FileSpec darwin_debug_file_spec = HostInfo::GetSupportExeDir();
217 if (!darwin_debug_file_spec) {
218 error.SetErrorString(
"can't locate the 'darwin-debug' executable");
222 darwin_debug_file_spec.
SetFilename(
"darwin-debug");
225 error.SetErrorStringWithFormat(
226 "the 'darwin-debug' executable doesn't exists at '%s'",
227 darwin_debug_file_spec.
GetPath().c_str());
232 darwin_debug_file_spec.
GetPath(launcher_path,
sizeof(launcher_path));
240 command.
Printf(R
"(\"%s\" --unix-socket=%s)", launcher_path, unix_socket_name);
247 command.
Printf(R
"( --working-dir \"%s\")", working_dir.GetPath().c_str());
251 command.
Printf(R
"( --working-dir \"%s\")", cwd);
254 if (launch_info.
GetFlags().
Test(eLaunchFlagDisableASLR))
265 auto host_entry = host_env.find(KV.first());
266 if (host_entry == host_env.end() || host_entry->second != KV.second)
274 for (
size_t i = 0; argv[i] != NULL; ++i) {
276 command.
Printf(R
"( \"%s\")", exe_path);
278 command.
Printf(R
"( \"%s\")", argv[i]);
281 command.
Printf(R
"( \"%s\")", exe_path);
283 command.PutCString(" ; echo Process exited with status $?");
284 if (launch_info.
GetFlags().
Test(lldb::eLaunchFlagCloseTTYOnExit))
289 applescript_source.
Printf(applscript_in_new_tty,
292 NSAppleScript *applescript = [[NSAppleScript alloc]
293 initWithSource:[NSString stringWithCString:applescript_source.
GetString()
296 encoding:NSUTF8StringEncoding]];
303 char connect_url[128];
304 ::snprintf(connect_url,
sizeof(connect_url),
"unix-accept://%s",
314 unix_socket_name, [&] {
return AcceptPIDFromInferior(connect_url); });
317 return Status(accept_thread.takeError());
319 [applescript executeAndReturnError:nil];
322 lldb_error = accept_thread->Join(&accept_thread_result);
323 if (lldb_error.
Success() && accept_thread_result) {
324 pid = (intptr_t)accept_thread_result;
327 llvm::sys::fs::remove(unix_socket_name);
328 [applescript release];
340 return llvm::errorCodeToError(
341 std::error_code(ENOTSUP, std::system_category()));
345 const std::string file_path = file_spec.
GetPath();
347 LLDB_LOG(log,
"Sending {0}:{1} to external editor",
348 file_path.empty() ?
"<invalid>" : file_path, line_no);
350 if (file_path.empty())
351 return llvm::createStringError(llvm::inconvertibleErrorCode(),
352 "no file specified");
354 CFCString file_cfstr(file_path.c_str(), kCFStringEncodingUTF8);
358 kCFURLPOSIXPathStyle,
362 return llvm::createStringError(
363 llvm::inconvertibleErrorCode(),
364 llvm::formatv(
"could not create CFURL from path \"{0}\"", file_path));
377 BabelAESelInfo file_and_line_info = {
379 (int16_t)(line_no - 1),
386 AEKeyDesc file_and_line_desc;
387 file_and_line_desc.descKey = keyAEPosition;
388 long error = ::AECreateDesc(typeUTF8Text,
390 sizeof(file_and_line_info),
391 &(file_and_line_desc.descContent));
394 return llvm::createStringError(
395 llvm::inconvertibleErrorCode(),
396 llvm::formatv(
"creating Apple Event descriptor failed: error {0}",
400 auto on_exit = llvm::make_scope_exit(
401 [&]() { AEDisposeDesc(&(file_and_line_desc.descContent)); });
403 if (editor.empty()) {
404 if (
const char *lldb_external_editor = ::getenv(
"LLDB_EXTERNAL_EDITOR"))
405 editor = lldb_external_editor;
408 std::optional<FSRef> app_fsref;
409 if (!editor.empty()) {
410 LLDB_LOG(log,
"Looking for external editor: {0}", editor);
413 CFCString editor_name(editor.data(), kCFStringEncodingUTF8);
414 long app_error = ::LSFindApplicationForInfo(
415 kLSUnknownCreator, NULL,
416 editor_name.get(), &(*app_fsref),
418 if (app_error != noErr)
419 return llvm::createStringError(
420 llvm::inconvertibleErrorCode(),
421 llvm::formatv(
"could not find external editor \"{0}\": "
422 "LSFindApplicationForInfo returned error {1}",
427 LSApplicationParameters app_params;
428 ::memset(&app_params, 0,
sizeof(app_params));
430 kLSLaunchDefaults | kLSLaunchDontAddToRecents | kLSLaunchDontSwitch;
432 app_params.application = &(*app_fsref);
434 ProcessSerialNumber psn;
435 std::array<CFURLRef, 1> file_array = {file_URL.
get()};
437 CFArrayCreate(NULL, (
const void **)&file_array,
439 error = ::LSOpenURLsWithRole(
440 cf_array.get(), kLSRolesEditor,
442 &app_params, &psn, 1);
445 return llvm::createStringError(
446 llvm::inconvertibleErrorCode(),
447 llvm::formatv(
"LSOpenURLsWithRole failed: error {0}",
error));
449 return llvm::Error::success();
457 auditinfo_addr_t info;
458 getaudit_addr(&info,
sizeof(info));
459 return info.ai_flags & AU_SESSION_FLAG_HAS_GRAPHIC_ACCESS;
468 int mib[CTL_MAXNAME] = {
471 size_t mib_len = CTL_MAXNAME;
472 if (::sysctlnametomib(
"sysctl.proc_cputype", mib, &mib_len))
479 size_t len =
sizeof(cpu);
480 if (::sysctl(mib, mib_len, &cpu, &len, 0, 0) == 0) {
483 sub = CPU_SUBTYPE_I386_ALL;
485 case CPU_TYPE_X86_64:
486 sub = CPU_SUBTYPE_X86_64_ALL;
489#if defined(CPU_TYPE_ARM64) && defined(CPU_SUBTYPE_ARM64_ALL)
491 sub = CPU_SUBTYPE_ARM64_ALL;
495#if defined(CPU_TYPE_ARM64_32) && defined(CPU_SUBTYPE_ARM64_32_ALL)
497 sub = CPU_SUBTYPE_ARM64_32_ALL;
505 uint32_t cpusubtype = 0;
506 len =
sizeof(cpusubtype);
507 if (::sysctlbyname(
"hw.cpusubtype", &cpusubtype, &len, NULL, 0) == 0)
510 bool host_cpu_is_64bit;
511 uint32_t is64bit_capable;
512 size_t is64bit_capable_len =
sizeof(is64bit_capable);
514 sysctlbyname(
"hw.cpu64bit_capable", &is64bit_capable,
515 &is64bit_capable_len, NULL, 0) == 0;
522 if (host_cpu_is_64bit) {
523 sub = CPU_SUBTYPE_ARM_V7;
541 int proc_args_mib[3] = {CTL_KERN, KERN_PROCARGS2,
544 size_t arg_data_size = 0;
545 if (::sysctl(proc_args_mib, 3,
nullptr, &arg_data_size, NULL, 0) ||
547 arg_data_size = 8192;
554 if (::sysctl(proc_args_mib, 3, arg_data.
GetBytes(), &arg_data_size, NULL,
559 uint32_t argc = data.
GetU32(&offset);
561 const llvm::Triple::ArchType triple_arch = triple.getArch();
562 const bool check_for_ios_simulator =
563 (triple_arch == llvm::Triple::x86 ||
564 triple_arch == llvm::Triple::x86_64);
565 const char *cstr = data.
GetCStr(&offset);
569 if (match_info_ptr == NULL ||
576 const uint8_t *p = data.
PeekData(offset, 1);
577 if ((p == NULL) || (*p !=
'\0'))
583 for (
int i = 0; i < static_cast<int>(argc); ++i) {
590 while ((cstr = data.
GetCStr(&offset))) {
594 if (check_for_ios_simulator) {
595 if (strncmp(cstr,
"SIMULATOR_UDID=", strlen(
"SIMULATOR_UDID=")) ==
601 llvm::Triple::MacOSX);
619 mib[2] = KERN_PROC_PID;
621 struct kinfo_proc proc_kinfo;
622 size_t proc_kinfo_size =
sizeof(
struct kinfo_proc);
624 if (::sysctl(mib, 4, &proc_kinfo, &proc_kinfo_size, NULL, 0) == 0) {
625 if (proc_kinfo_size > 0) {
627 process_info.
SetUserID(proc_kinfo.kp_eproc.e_pcred.p_ruid);
628 process_info.
SetGroupID(proc_kinfo.kp_eproc.e_pcred.p_rgid);
630 if (proc_kinfo.kp_eproc.e_ucred.cr_ngroups > 0)
632 proc_kinfo.kp_eproc.e_ucred.cr_groups[0]);
649 std::vector<struct kinfo_proc> kinfos;
651 int mib[3] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL};
653 size_t pid_data_size = 0;
654 if (::sysctl(mib, 3,
nullptr, &pid_data_size,
nullptr, 0) != 0)
658 const size_t estimated_pid_count =
659 (pid_data_size /
sizeof(
struct kinfo_proc)) + 10;
661 kinfos.resize(estimated_pid_count);
662 pid_data_size = kinfos.size() *
sizeof(
struct kinfo_proc);
664 if (::sysctl(mib, 3, &kinfos[0], &pid_data_size,
nullptr, 0) != 0)
667 const size_t actual_pid_count = (pid_data_size /
sizeof(
struct kinfo_proc));
671 const uid_t our_uid = getuid();
672 for (
size_t i = 0; i < actual_pid_count; i++) {
673 const struct kinfo_proc &kinfo = kinfos[i];
675 bool kinfo_user_matches =
false;
677 kinfo_user_matches =
true;
679 kinfo_user_matches = kinfo.kp_eproc.e_pcred.p_ruid == our_uid;
683 kinfo_user_matches =
true;
685 if (!kinfo_user_matches ||
688 kinfo.kp_proc.p_pid == 0 ||
689 kinfo.kp_proc.p_stat == SZOMB ||
690 kinfo.kp_proc.p_flag & P_TRACED ||
691 kinfo.kp_proc.p_flag & P_WEXIT)
697 process_info.
SetUserID(kinfo.kp_eproc.e_pcred.p_ruid);
698 process_info.
SetGroupID(kinfo.kp_eproc.e_pcred.p_rgid);
700 if (kinfo.kp_eproc.e_ucred.cr_ngroups > 0)
714 if (match_info.
Matches(process_info))
715 process_infos.push_back(process_info);
719 return process_infos.size();
724 bool success =
false;
740 process_info.
Clear();
745static void PackageXPCArguments(xpc_object_t message,
const char *prefix,
749 memset(buf, 0,
sizeof(buf));
750 snprintf(buf,
sizeof(buf),
"%sCount", prefix);
751 xpc_dictionary_set_int64(message, buf, count);
752 for (
size_t i = 0; i < count; i++) {
753 memset(buf, 0,
sizeof(buf));
754 snprintf(buf,
sizeof(buf),
"%s%zi", prefix, i);
759static void PackageXPCEnvironment(xpc_object_t message, llvm::StringRef prefix,
761 xpc_dictionary_set_int64(message, (prefix +
"Count").str().c_str(),
764 for (
const auto &KV : env) {
765 xpc_dictionary_set_string(message, (prefix + llvm::Twine(i)).str().c_str(),
776static AuthorizationRef authorizationRef = NULL;
781 if ((launch_info.
GetUserID() == 0) && !authorizationRef) {
782 OSStatus createStatus =
783 AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment,
784 kAuthorizationFlagDefaults, &authorizationRef);
785 if (createStatus != errAuthorizationSuccess) {
787 error.SetErrorString(
"Can't create authorizationRef.");
792 OSStatus rightsStatus =
793 AuthorizationRightGet(LaunchUsingXPCRightName, NULL);
794 if (rightsStatus != errAuthorizationSuccess) {
797 CFSTR(
"Xcode is trying to take control of a root process.");
799 CFTypeRef values[] = {prompt};
800 CFDictionaryRef promptDict = CFDictionaryCreate(
801 kCFAllocatorDefault, (
const void **)keys, (
const void **)values, 1,
802 &kCFCopyStringDictionaryKeyCallBacks,
803 &kCFTypeDictionaryValueCallBacks);
805 CFStringRef keys1[] = {CFSTR(
"class"), CFSTR(
"group"), CFSTR(
"comment"),
806 CFSTR(
"default-prompt"), CFSTR(
"shared")};
807 CFTypeRef values1[] = {CFSTR(
"user"), CFSTR(
"admin"),
808 CFSTR(LaunchUsingXPCRightName), promptDict,
810 CFDictionaryRef dict = CFDictionaryCreate(
811 kCFAllocatorDefault, (
const void **)keys1, (
const void **)values1, 5,
812 &kCFCopyStringDictionaryKeyCallBacks,
813 &kCFTypeDictionaryValueCallBacks);
814 rightsStatus = AuthorizationRightSet(
815 authorizationRef, LaunchUsingXPCRightName, dict, NULL, NULL, NULL);
816 CFRelease(promptDict);
820 OSStatus copyRightStatus = errAuthorizationDenied;
821 if (rightsStatus == errAuthorizationSuccess) {
822 AuthorizationItem item1 = {LaunchUsingXPCRightName, 0, NULL, 0};
823 AuthorizationItem items[] = {item1};
824 AuthorizationRights requestedRights = {1, items};
825 AuthorizationFlags authorizationFlags =
826 kAuthorizationFlagInteractionAllowed | kAuthorizationFlagExtendRights;
827 copyRightStatus = AuthorizationCopyRights(
828 authorizationRef, &requestedRights, kAuthorizationEmptyEnvironment,
829 authorizationFlags, NULL);
832 if (copyRightStatus != errAuthorizationSuccess) {
839 error.SetErrorStringWithFormat(
840 "Launching as root needs root authorization.");
843 if (authorizationRef) {
844 AuthorizationFree(authorizationRef, kAuthorizationFlagDefaults);
845 authorizationRef = NULL;
855 short flags = POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK;
858 flags |= POSIX_SPAWN_SETEXEC;
861 flags |= POSIX_SPAWN_START_SUSPENDED;
863 if (launch_info.
GetFlags().
Test(eLaunchFlagDisableASLR))
867 flags |= POSIX_SPAWN_SETPGROUP;
869#ifdef POSIX_SPAWN_CLOEXEC_DEFAULT
870#if defined(__x86_64__) || defined(__i386__)
875 llvm::VersionTuple version = HostInfo::GetOSVersion();
876 if (version > llvm::VersionTuple(10, 7)) {
887 flags |= POSIX_SPAWN_CLOEXEC_DEFAULT;
902 uid_t requested_uid = launch_info.
GetUserID();
903 const char *xpc_service = nil;
904 bool send_auth =
false;
905 AuthorizationExternalForm extForm;
906 if (requested_uid == 0) {
907 if (AuthorizationMakeExternalForm(authorizationRef, &extForm) ==
908 errAuthorizationSuccess) {
912 error.SetErrorStringWithFormat(
"Launching root via XPC needs to "
913 "externalize authorization reference.");
917 xpc_service = LaunchUsingXPCRightName;
920 error.SetErrorStringWithFormat(
921 "Launching via XPC is only currently available for root.");
926 xpc_connection_t conn = xpc_connection_create(xpc_service, NULL);
928 xpc_connection_set_event_handler(conn, ^(xpc_object_t event) {
929 xpc_type_t type = xpc_get_type(event);
931 if (type == XPC_TYPE_ERROR) {
932 if (event == XPC_ERROR_CONNECTION_INTERRUPTED) {
939 }
else if (event == XPC_ERROR_CONNECTION_INVALID) {
956 xpc_connection_set_finalizer_f(conn, xpc_finalizer_t(xpc_release));
957 xpc_connection_resume(conn);
958 xpc_object_t message = xpc_dictionary_create(nil, nil, 0);
961 xpc_dictionary_set_data(message, LauncherXPCServiceAuthKey, extForm.bytes,
962 sizeof(AuthorizationExternalForm));
965 PackageXPCArguments(message, LauncherXPCServiceArgPrefxKey,
967 PackageXPCEnvironment(message, LauncherXPCServiceEnvPrefxKey,
971 xpc_dictionary_set_int64(message, LauncherXPCServiceCPUTypeKey,
973 xpc_dictionary_set_int64(message, LauncherXPCServicePosixspawnFlagsKey,
976 if (file_action && !file_action->
GetPath().empty()) {
977 xpc_dictionary_set_string(message, LauncherXPCServiceStdInPathKeyKey,
978 file_action->
GetPath().str().c_str());
981 if (file_action && !file_action->
GetPath().empty()) {
982 xpc_dictionary_set_string(message, LauncherXPCServiceStdOutPathKeyKey,
983 file_action->
GetPath().str().c_str());
986 if (file_action && !file_action->
GetPath().empty()) {
987 xpc_dictionary_set_string(message, LauncherXPCServiceStdErrPathKeyKey,
988 file_action->
GetPath().str().c_str());
992 xpc_connection_send_message_with_reply_sync(conn, message);
993 xpc_type_t returnType = xpc_get_type(reply);
994 if (returnType == XPC_TYPE_DICTIONARY) {
995 pid = xpc_dictionary_get_int64(reply, LauncherXPCServiceChildPIDKey);
998 xpc_dictionary_get_int64(reply, LauncherXPCServiceErrorTypeKey);
1000 xpc_dictionary_get_int64(reply, LauncherXPCServiceCodeTypeKey);
1003 error.SetErrorStringWithFormat(
1004 "Problems with launching via XPC. Error type : %i, code : %i",
1005 errorType, errorCode);
1008 if (authorizationRef) {
1009 AuthorizationFree(authorizationRef, kAuthorizationFlagDefaults);
1010 authorizationRef = NULL;
1013 }
else if (returnType == XPC_TYPE_ERROR) {
1015 error.SetErrorStringWithFormat(
1016 "Problems with launching via XPC. XPC error : %s",
1017 xpc_dictionary_get_string(reply, XPC_ERROR_KEY_DESCRIPTION));
1033 posix_spawn_file_actions_t *file_actions =
1034 static_cast<posix_spawn_file_actions_t *
>(_file_actions);
1042 if (info->
GetFD() == -1)
1043 error.SetErrorString(
1044 "invalid fd for posix_spawn_file_actions_addclose(...)");
1047 ::posix_spawn_file_actions_addclose(file_actions, info->
GetFD()),
1051 "error: {0}, posix_spawn_file_actions_addclose "
1052 "(action={1}, fd={2})",
1058 if (info->
GetFD() == -1)
1059 error.SetErrorString(
1060 "invalid fd for posix_spawn_file_actions_adddup2(...)");
1062 error.SetErrorString(
1063 "invalid duplicate fd for posix_spawn_file_actions_adddup2(...)");
1066 ::posix_spawn_file_actions_adddup2(file_actions, info->
GetFD(),
1071 "error: {0}, posix_spawn_file_actions_adddup2 "
1072 "(action={1}, fd={2}, dup_fd={3})",
1078 if (info->
GetFD() == -1)
1079 error.SetErrorString(
1080 "invalid fd in posix_spawn_file_actions_addopen(...)");
1086 if (oflag & O_CREAT)
1089 error.SetError(::posix_spawn_file_actions_addopen(
1090 file_actions, info->
GetFD(),
1091 info->
GetPath().str().c_str(), oflag, mode),
1095 "error: {0}, posix_spawn_file_actions_addopen (action={1}, "
1096 "fd={2}, path='{3}', oflag={4}, mode={5})",
1102 return error.Success();
1111 posix_spawnattr_t attr;
1115 LLDB_LOG(log,
"error: {0}, ::posix_spawnattr_init ( &attr )",
error);
1121 llvm::make_scope_exit([&]() { posix_spawnattr_destroy(&attr); });
1123 sigset_t no_signals;
1124 sigset_t all_signals;
1125 sigemptyset(&no_signals);
1126 sigfillset(&all_signals);
1127 ::posix_spawnattr_setsigmask(&attr, &no_signals);
1128 ::posix_spawnattr_setsigdefault(&attr, &all_signals);
1135 "error: {0}, ::posix_spawnattr_setflags ( &attr, flags={1:x} )",
1140 bool is_graphical =
true;
1143 SecuritySessionId session_id;
1144 SessionAttributeBits session_attributes;
1146 SessionGetInfo(callerSecuritySession, &session_id, &session_attributes);
1147 if (status == errSessionSuccess)
1148 is_graphical = session_attributes & sessionHasGraphicAccess;
1154 if (is_graphical && launch_info.
GetFlags().
Test(eLaunchFlagDebug) &&
1155 !launch_info.
GetFlags().
Test(eLaunchFlagInheritTCCFromParent)) {
1158 LLDB_LOG(log,
"error: {0}, setup_posix_spawn_responsible_flag(&attr)",
1172 const bool set_cpu_type =
1175 const bool set_cpu_subtype =
1181 typedef int (*posix_spawnattr_setarchpref_np_t)(
1183 posix_spawnattr_setarchpref_np_t posix_spawnattr_setarchpref_np_fn =
1184 (posix_spawnattr_setarchpref_np_t)dlsym(
1185 RTLD_DEFAULT,
"posix_spawnattr_setarchpref_np");
1186 if (set_cpu_subtype && posix_spawnattr_setarchpref_np_fn) {
1187 error.SetError((*posix_spawnattr_setarchpref_np_fn)(
1188 &attr, 1, &cpu_type, &cpu_subtype, &ocount),
1192 "error: {0}, ::posix_spawnattr_setarchpref_np ( &attr, 1, "
1193 "cpu_type = {1:x}, cpu_subtype = {1:x}, count => {2} )",
1194 error, cpu_type, cpu_subtype, ocount);
1196 if (
error.Fail() || ocount != 1)
1200 ::posix_spawnattr_setbinpref_np(&attr, 1, &cpu_type, &ocount),
1204 "error: {0}, ::posix_spawnattr_setbinpref_np ( &attr, 1, "
1205 "cpu_type = {1:x}, count => {2} )",
1206 error, cpu_type, ocount);
1207 if (
error.Fail() || ocount != 1)
1213 const char *tmp_argv[2];
1214 char *
const *argv =
const_cast<char *
const *
>(
1222 tmp_argv[0] = exe_path;
1224 argv =
const_cast<char *
const *
>(tmp_argv);
1230 std::string working_dir_path = working_dir.
GetPath();
1232 if (errno == ENOENT) {
1233 error.SetErrorStringWithFormat(
"No such file or directory: %s",
1234 working_dir_path.c_str());
1235 }
else if (errno == ENOTDIR) {
1236 error.SetErrorStringWithFormat(
"Path doesn't name a directory: %s",
1237 working_dir_path.c_str());
1239 error.SetErrorStringWithFormat(
"An unknown error occurred when "
1240 "changing directory for process "
1249 if (num_file_actions > 0) {
1250 posix_spawn_file_actions_t file_actions;
1251 error.SetError(::posix_spawn_file_actions_init(&file_actions),
1255 "error: {0}, ::posix_spawn_file_actions_init ( &file_actions )",
1261 auto cleanup_fileact = llvm::make_scope_exit(
1262 [&]() { posix_spawn_file_actions_destroy(&file_actions); });
1264 for (
size_t i = 0; i < num_file_actions; ++i) {
1267 if (launch_file_action) {
1275 ::posix_spawnp(&result_pid, exe_path, &file_actions, &attr, argv, envp),
1280 "error: {0}, ::posix_spawnp(pid => {1}, path = '{2}', "
1281 "file_actions = {3}, "
1282 "attr = {4}, argv = {5}, envp = {6} )",
1283 error, result_pid, exe_path, &file_actions, &attr, argv,
1286 for (
int ii = 0; argv[ii]; ++ii)
1287 LLDB_LOG(log,
"argv[{0}] = '{1}'", ii, argv[ii]);
1293 ::posix_spawnp(&result_pid, exe_path, NULL, &attr, argv, envp),
1298 "error: {0}, ::posix_spawnp ( pid => {1}, path = '{2}', "
1299 "file_actions = NULL, attr = {3}, argv = {4}, envp = {5} )",
1300 error, result_pid, exe_path, &attr, argv, envp.
get());
1302 for (
int ii = 0; argv[ii]; ++ii)
1303 LLDB_LOG(log,
"argv[{0}] = '{1}'", ii, argv[ii]);
1318 bool result =
false;
1321 bool launchingAsRoot = launch_info.
GetUserID() == 0;
1322 bool currentUserIsRoot = HostInfo::GetEffectiveUserID() == 0;
1324 if (launchingAsRoot && !currentUserIsRoot) {
1339 if (!fs.
Exists(exe_spec))
1342 if (!fs.
Exists(exe_spec))
1345 if (!fs.
Exists(exe_spec)) {
1346 error.SetErrorStringWithFormatv(
"executable doesn't exist: '{0}'",
1351 if (launch_info.
GetFlags().
Test(eLaunchFlagLaunchInTTY)) {
1353 return LaunchInNewTerminalWithAppleScript(exe_spec.GetPath().c_str(),
1356 error.SetErrorString(
"launching a process in a new terminal is not "
1357 "supported on iOS devices");
1364 auto exe_path = exe_spec.GetPath();
1381 if (
error.Success())
1382 error.SetErrorString(
"process launch failed for unknown reasons");
1389 if (launch_info.
GetFlags().
Test(eLaunchFlagShellExpandArguments)) {
1392 std::string env_argdumper_path = host_env.lookup(
"LLDB_ARGDUMPER_PATH");
1393 if (!env_argdumper_path.empty()) {
1394 expand_tool_spec.
SetFile(env_argdumper_path, FileSpec::Style::native);
1397 "lldb-argdumper exe path set from environment variable: %s",
1398 env_argdumper_path.c_str());
1401 if (!argdumper_exists) {
1402 expand_tool_spec = HostInfo::GetSupportExeDir();
1403 if (!expand_tool_spec) {
1404 error.SetErrorString(
"could not get support executable directory for "
1405 "lldb-argdumper tool");
1410 error.SetErrorStringWithFormat(
1411 "could not find the lldb-argdumper tool: %s",
1412 expand_tool_spec.
GetPath().c_str());
1418 expand_tool_spec_stream.
Printf(
"\"%s\"",
1419 expand_tool_spec.
GetPath().c_str());
1421 Args expand_command(expand_tool_spec_stream.
GetData());
1422 expand_command.AppendArguments(launch_info.
GetArguments());
1428 char *wd = getcwd(
nullptr, 0);
1429 if (wd ==
nullptr) {
1430 error.SetErrorStringWithFormat(
1431 "cwd does not exist; cannot launch with shell argument expansion");
1439 bool run_in_shell =
true;
1440 bool hide_stderr =
true;
1443 std::chrono::seconds(10), run_in_shell, hide_stderr);
1449 error.SetErrorStringWithFormat(
"lldb-argdumper exited with error %d",
1456 error.SetErrorString(
"invalid JSON");
1460 auto dict_sp = data_sp->GetAsDictionary();
1462 error.SetErrorString(
"invalid JSON");
1466 auto args_sp = dict_sp->GetObjectForDotSeparatedPath(
"arguments");
1468 error.SetErrorString(
"invalid JSON");
1472 auto args_array_sp = args_sp->GetAsArray();
1473 if (!args_array_sp) {
1474 error.SetErrorString(
"invalid JSON");
1480 for (
size_t i = 0; i < args_array_sp->GetSize(); i++) {
1481 auto item_sp = args_array_sp->GetItemAtIndex(i);
1484 auto str_sp = item_sp->GetAsString();
1497 unsigned long mask = DISPATCH_PROC_EXIT;
1501 dispatch_source_t source = ::dispatch_source_create(
1502 DISPATCH_SOURCE_TYPE_PROC, pid, mask,
1503 ::dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0));
1506 "Host::StartMonitoringChildProcess(callback, pid=%i) source = %p\n",
1507 static_cast<int>(pid),
static_cast<void *
>(source));
1511 ::dispatch_source_set_cancel_handler(source, ^{
1512 dispatch_release(source);
1514 ::dispatch_source_set_event_handler(source, ^{
1518 wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, pid, &status, 0);
1519 if (wait_pid >= 0) {
1521 int exit_status = 0;
1522 const char *status_cstr = NULL;
1523 if (WIFEXITED(status)) {
1524 exit_status = WEXITSTATUS(status);
1525 status_cstr =
"EXITED";
1526 }
else if (WIFSIGNALED(status)) {
1527 signal = WTERMSIG(status);
1528 status_cstr =
"SIGNALED";
1531 llvm_unreachable(
"Unknown status");
1535 "::waitpid (pid = %llu, &status, 0) => pid = %i, status "
1536 "= 0x%8.8x (%s), signal = %i, exit_status = %i",
1537 pid, wait_pid, status, status_cstr, signal, exit_status);
1540 callback_copy(pid, signal, exit_status);
1542 ::dispatch_source_cancel(source);
1546 ::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
Get the number of bytes in the data buffer.
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 ResolveExecutableInBundle(FileSpec &file)
When executable files may live within a directory, where the directory represents an executable bundl...
static void SystemLog(lldb::Severity severity, llvm::StringRef message)
Emit the given message to the operating system log.
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 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...
static llvm::Error OpenFileInExternalEditor(llvm::StringRef editor, const FileSpec &file_spec, uint32_t line_no)
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(llvm::StringRef 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)
uint8_t * GetBytes()
Get a pointer to the data.
#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
Severity
Used for expressing severity in logs and diagnostics.
ConnectionStatus
Connection Status Types.
@ eConnectionStatusSuccess
Success.
@ eErrorTypeGeneric
Generic errors that can be any value.
@ eErrorTypePOSIX
POSIX error codes.