LLDB mainline
Host.mm
Go to the documentation of this file.
1//===-- Host.mm -------------------------------------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "lldb/Host/Host.h"
11
12#include <AvailabilityMacros.h>
13#include <TargetConditionals.h>
14
15#if TARGET_OS_OSX
16#define __XPC_PRIVATE_H__
17#include <xpc/xpc.h>
18
19#define LaunchUsingXPCRightName "com.apple.lldb.RootDebuggingXPCService"
20
21// These XPC messaging keys are used for communication between Host.mm and the
22// XPC service.
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"
34
35#include <bsm/audit.h>
36#include <bsm/audit_session.h>
37#endif
38
39#include "llvm/TargetParser/Host.h"
40
41#include <asl.h>
42#include <crt_externs.h>
43#include <cstdio>
44#include <cstdlib>
45#include <dlfcn.h>
46#include <grp.h>
47#include <libproc.h>
48#include <pwd.h>
49#include <spawn.h>
50#include <sys/proc.h>
51#include <sys/stat.h>
52#include <sys/sysctl.h>
53#include <sys/types.h>
54#include <unistd.h>
55
58#include "lldb/Host/HostInfo.h"
65#include "lldb/Utility/Endian.h"
67#include "lldb/Utility/Log.h"
72#include "lldb/lldb-defines.h"
73
74#include "llvm/ADT/ScopeExit.h"
75#include "llvm/Support/Errno.h"
76#include "llvm/Support/FileSystem.h"
77
78#include "../cfcpp/CFCBundle.h"
82#include "../cfcpp/CFCString.h"
83
84#include <objc/objc-auto.h>
85#include <os/log.h>
86
87#include <CoreFoundation/CoreFoundation.h>
88#include <Foundation/Foundation.h>
89
90#ifndef _POSIX_SPAWN_DISABLE_ASLR
91#define _POSIX_SPAWN_DISABLE_ASLR 0x0100
92#endif
93
94extern "C" {
95int __pthread_chdir(const char *path);
96int __pthread_fchdir(int fildes);
97}
98
99using namespace lldb;
100using namespace lldb_private;
101
102static os_log_t g_os_log;
103static std::once_flag g_os_log_once;
104
105void Host::SystemLog(Severity severity, llvm::StringRef message) {
106 if (__builtin_available(macos 10.12, iOS 10, tvOS 10, watchOS 3, *)) {
107 std::call_once(g_os_log_once, []() {
108 g_os_log = os_log_create("com.apple.dt.lldb", "lldb");
109 });
110 switch (severity) {
113 os_log(g_os_log, "%{public}s", message.str().c_str());
114 break;
116 os_log_error(g_os_log, "%{public}s", message.str().c_str());
117 break;
118 }
119 } else {
120 llvm::errs() << message;
121 }
122}
123
124bool Host::GetBundleDirectory(const FileSpec &file,
125 FileSpec &bundle_directory) {
126#if defined(__APPLE__)
127 if (FileSystem::Instance().IsDirectory(file)) {
128 char path[PATH_MAX];
129 if (file.GetPath(path, sizeof(path))) {
130 CFCBundle bundle(path);
131 if (bundle.GetPath(path, sizeof(path))) {
132 bundle_directory.SetFile(path, FileSpec::Style::native);
133 return true;
134 }
135 }
136 }
137#endif
138 bundle_directory.Clear();
139 return false;
140}
141
143#if defined(__APPLE__)
144 if (FileSystem::Instance().IsDirectory(file)) {
145 char path[PATH_MAX];
146 if (file.GetPath(path, sizeof(path))) {
147 CFCBundle bundle(path);
148 CFCReleaser<CFURLRef> url(bundle.CopyExecutableURL());
149 if (url.get()) {
150 if (::CFURLGetFileSystemRepresentation(url.get(), YES, (UInt8 *)path,
151 sizeof(path))) {
152 file.SetFile(path, FileSpec::Style::native);
153 return true;
154 }
155 }
156 }
157 }
158#endif
159 return false;
160}
161
162#if TARGET_OS_OSX
163
164static void *AcceptPIDFromInferior(const char *connect_url) {
165 ConnectionFileDescriptor file_conn;
167 if (file_conn.Connect(connect_url, &error) == eConnectionStatusSuccess) {
168 char pid_str[256];
169 ::memset(pid_str, 0, sizeof(pid_str));
170 ConnectionStatus status;
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;
176 }
177 }
178 return NULL;
179}
180
181const char *applscript_in_new_tty = "tell application \"Terminal\"\n"
182 " activate\n"
183 " do script \"/bin/bash -c '%s';exit\"\n"
184 "end tell\n";
185
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\
197 return\n\
198 end if\n\
199 end if\n\
200 end repeat\n\
201 end repeat\n\
202 do script the_shell_script\n\
203end tell\n";
204
205static Status
206LaunchInNewTerminalWithAppleScript(const char *exe_path,
207 ProcessLaunchInfo &launch_info) {
209 char unix_socket_name[PATH_MAX] = "/tmp/XXXXXX";
210 if (::mktemp(unix_socket_name) == NULL) {
212 "failed to make temporary path for a unix socket");
213 return error;
214 }
215
216 StreamString command;
217 FileSpec darwin_debug_file_spec = HostInfo::GetSupportExeDir();
218 if (!darwin_debug_file_spec) {
219 error =
220 Status::FromErrorString("can't locate the 'darwin-debug' executable");
221 return error;
222 }
223
224 darwin_debug_file_spec.SetFilename("darwin-debug");
225
226 if (!FileSystem::Instance().Exists(darwin_debug_file_spec)) {
228 "the 'darwin-debug' executable doesn't exists at '%s'",
229 darwin_debug_file_spec.GetPath().c_str());
230 return error;
231 }
232
233 char launcher_path[PATH_MAX];
234 darwin_debug_file_spec.GetPath(launcher_path, sizeof(launcher_path));
235
236 const ArchSpec &arch_spec = launch_info.GetArchitecture();
237 // Only set the architecture if it is valid and if it isn't Haswell (x86_64h).
238 if (arch_spec.IsValid() &&
240 command.Printf("arch -arch %s ", arch_spec.GetArchitectureName());
241
242 command.Printf(R"(\"%s\" --unix-socket=%s)", launcher_path, unix_socket_name);
243
244 if (arch_spec.IsValid())
245 command.Printf(" --arch=%s", arch_spec.GetArchitectureName());
246
247 FileSpec working_dir{launch_info.GetWorkingDirectory()};
248 if (working_dir)
249 command.Printf(R"( --working-dir \"%s\")", working_dir.GetPath().c_str());
250 else {
251 char cwd[PATH_MAX];
252 if (getcwd(cwd, PATH_MAX))
253 command.Printf(R"( --working-dir \"%s\")", cwd);
254 }
255
256 if (launch_info.GetFlags().Test(eLaunchFlagDisableASLR))
257 command.PutCString(" --disable-aslr");
258
259 // We are launching on this host in a terminal. So compare the environment on
260 // the host to what is supplied in the launch_info. Any items that aren't in
261 // the host environment need to be sent to darwin-debug. If we send all
262 // environment entries, we might blow the max command line length, so we only
263 // send user modified entries.
265
266 for (const auto &KV : launch_info.GetEnvironment()) {
267 auto host_entry = host_env.find(KV.first());
268 if (host_entry == host_env.end() || host_entry->second != KV.second)
269 command.Format(R"( --env=\"{0}\")", Environment::compose(KV));
270 }
271
272 command.PutCString(" -- ");
273
274 const char **argv = launch_info.GetArguments().GetConstArgumentVector();
275 if (argv) {
276 for (size_t i = 0; argv[i] != NULL; ++i) {
277 if (i == 0)
278 command.Printf(R"( \"%s\")", exe_path);
279 else
280 command.Printf(R"( \"%s\")", argv[i]);
281 }
282 } else {
283 command.Printf(R"( \"%s\")", exe_path);
284 }
285 command.PutCString(" ; echo Process exited with status $?");
286 if (launch_info.GetFlags().Test(lldb::eLaunchFlagCloseTTYOnExit))
287 command.PutCString(" ; exit");
288
289 StreamString applescript_source;
290
291 applescript_source.Printf(applscript_in_new_tty,
292 command.GetString().str().c_str());
293
294 NSAppleScript *applescript = [[NSAppleScript alloc]
295 initWithSource:[NSString stringWithCString:applescript_source.GetString()
296 .str()
297 .c_str()
298 encoding:NSUTF8StringEncoding]];
299
301
302 Status lldb_error;
303 // Sleep and wait a bit for debugserver to start to listen...
304 ConnectionFileDescriptor file_conn;
305 char connect_url[128];
306 ::snprintf(connect_url, sizeof(connect_url), "unix-accept://%s",
307 unix_socket_name);
308
309 // Spawn a new thread to accept incoming connection on the connect_url
310 // so we can grab the pid from the inferior. We have to do this because we
311 // are sending an AppleScript that will launch a process in Terminal.app,
312 // in a shell and the shell will fork/exec a couple of times before we get
313 // to the process that we wanted to launch. So when our process actually
314 // gets launched, we will handshake with it and get the process ID for it.
315 llvm::Expected<HostThread> accept_thread = ThreadLauncher::LaunchThread(
316 unix_socket_name, [&] { return AcceptPIDFromInferior(connect_url); });
317
318 if (!accept_thread)
319 return Status::FromError(accept_thread.takeError());
320
321 [applescript executeAndReturnError:nil];
322
323 thread_result_t accept_thread_result = NULL;
324 lldb_error = accept_thread->Join(&accept_thread_result);
325 if (lldb_error.Success() && accept_thread_result) {
326 pid = (intptr_t)accept_thread_result;
327 }
328
329 llvm::sys::fs::remove(unix_socket_name);
330 [applescript release];
331 if (pid != LLDB_INVALID_PROCESS_ID)
332 launch_info.SetProcessID(pid);
333 return error;
334}
335
336#endif // TARGET_OS_OSX
337
338llvm::Error Host::OpenFileInExternalEditor(llvm::StringRef editor,
339 const FileSpec &file_spec,
340 uint32_t line_no) {
341#if !TARGET_OS_OSX
342 return llvm::errorCodeToError(
343 std::error_code(ENOTSUP, std::system_category()));
344#else // !TARGET_OS_OSX
345 Log *log = GetLog(LLDBLog::Host);
346
347 const std::string file_path = file_spec.GetPath();
348
349 LLDB_LOG(log, "Sending {0}:{1} to external editor",
350 file_path.empty() ? "<invalid>" : file_path, line_no);
351
352 if (file_path.empty())
353 return llvm::createStringError(llvm::inconvertibleErrorCode(),
354 "no file specified");
355
356 CFCString file_cfstr(file_path.c_str(), kCFStringEncodingUTF8);
357 CFCReleaser<CFURLRef> file_URL = ::CFURLCreateWithFileSystemPath(
358 /*allocator=*/NULL,
359 /*filePath*/ file_cfstr.get(),
360 /*pathStyle=*/kCFURLPOSIXPathStyle,
361 /*isDirectory=*/false);
362
363 if (!file_URL.get())
364 return llvm::createStringError(
365 llvm::inconvertibleErrorCode(),
366 llvm::formatv("could not create CFURL from path \"{0}\"", file_path));
367
368 // Create a new Apple Event descriptor.
369 typedef struct {
370 int16_t reserved0; // must be zero
371 int16_t fLineNumber;
372 int32_t fSelStart;
373 int32_t fSelEnd;
374 uint32_t reserved1; // must be zero
375 uint32_t reserved2; // must be zero
376 } BabelAESelInfo;
377
378 // We attach this to an 'odoc' event to specify a particular selection.
379 BabelAESelInfo file_and_line_info = {
380 0, // reserved0
381 (int16_t)(line_no - 1), // fLineNumber (zero based line number)
382 1, // fSelStart
383 1024, // fSelEnd
384 0, // reserved1
385 0 // reserved2
386 };
387
388 AEKeyDesc file_and_line_desc;
389 file_and_line_desc.descKey = keyAEPosition;
390 long error = ::AECreateDesc(/*typeCode=*/typeUTF8Text,
391 /*dataPtr=*/&file_and_line_info,
392 /*dataSize=*/sizeof(file_and_line_info),
393 /*result=*/&(file_and_line_desc.descContent));
394
395 if (error != noErr)
396 return llvm::createStringError(
397 llvm::inconvertibleErrorCode(),
398 llvm::formatv("creating Apple Event descriptor failed: error {0}",
399 error));
400
401 // Deallocate the descriptor on exit.
402 llvm::scope_exit on_exit(
403 [&]() { AEDisposeDesc(&(file_and_line_desc.descContent)); });
404
405 if (editor.empty()) {
406 if (const char *lldb_external_editor = ::getenv("LLDB_EXTERNAL_EDITOR"))
407 editor = lldb_external_editor;
408 }
409
410 std::optional<FSRef> app_fsref;
411 if (!editor.empty()) {
412 LLDB_LOG(log, "Looking for external editor: {0}", editor);
413
414 app_fsref.emplace();
415 CFCString editor_name(editor.data(), kCFStringEncodingUTF8);
416 long app_error = ::LSFindApplicationForInfo(
417 /*inCreator=*/kLSUnknownCreator, /*inBundleID=*/NULL,
418 /*inName=*/editor_name.get(), /*outAppRef=*/&(*app_fsref),
419 /*outAppURL=*/NULL);
420 if (app_error != noErr)
421 return llvm::createStringError(
422 llvm::inconvertibleErrorCode(),
423 llvm::formatv("could not find external editor \"{0}\": "
424 "LSFindApplicationForInfo returned error {1}",
425 editor, app_error));
426 }
427
428 // Build app launch parameters.
429 LSApplicationParameters app_params;
430 ::memset(&app_params, 0, sizeof(app_params));
431 app_params.flags =
432 kLSLaunchDefaults | kLSLaunchDontAddToRecents | kLSLaunchDontSwitch;
433 if (app_fsref)
434 app_params.application = &(*app_fsref);
435
436 ProcessSerialNumber psn;
437 std::array<CFURLRef, 1> file_array = {file_URL.get()};
438 CFCReleaser<CFArrayRef> cf_array(
439 CFArrayCreate(/*allocator=*/NULL, /*values=*/(const void **)&file_array,
440 /*numValues*/ 1, /*callBacks=*/NULL));
441 error = ::LSOpenURLsWithRole(
442 /*inURLs=*/cf_array.get(), /*inRole=*/kLSRolesEditor,
443 /*inAEParam=*/&file_and_line_desc,
444 /*inAppParams=*/&app_params, /*outPSNs=*/&psn, /*inMaxPSNCount=*/1);
445
446 if (error != noErr)
447 return llvm::createStringError(
448 llvm::inconvertibleErrorCode(),
449 llvm::formatv("LSOpenURLsWithRole failed: error {0}", error));
450
451 return llvm::Error::success();
452#endif // TARGET_OS_OSX
453}
454
455llvm::Error Host::OpenURL(llvm::StringRef url) {
456#if !TARGET_OS_OSX
457 return llvm::errorCodeToError(
458 std::error_code(ENOTSUP, std::system_category()));
459#else // !TARGET_OS_OSX
460 if (url.empty())
461 return llvm::createStringError("cannot open empty URL");
462
463 LLDB_LOG(GetLog(LLDBLog::Host), "Opening URL: {0}", url);
464
465 CFCString url_cfstr(url.data(), kCFStringEncodingUTF8);
466 CFCReleaser<CFURLRef> cfurl = ::CFURLCreateWithString(
467 /*allocator=*/NULL,
468 /*URLString*/ url_cfstr.get(),
469 /*baseURL=*/NULL);
470
471 if (!cfurl.get())
472 return llvm::createStringError(
473 llvm::formatv("could not create CFURL from URL \"{0}\"", url));
474
475 OSStatus error = ::LSOpenCFURLRef(
476 /*inURL=*/cfurl.get(),
477 /*outLaunchedURL=*/NULL);
478
479 if (error != noErr)
480 return llvm::createStringError(
481 llvm::formatv("LSOpenCFURLRef failed: error {0:x}", error));
482
483 return llvm::Error::success();
484#endif // TARGET_OS_OSX
485}
486
488#if !TARGET_OS_OSX
489 return false;
490#else
491 auditinfo_addr_t info;
492 getaudit_addr(&info, sizeof(info));
493 return info.ai_flags & AU_SESSION_FLAG_HAS_GRAPHIC_ACCESS;
494#endif
495}
496
497Environment Host::GetEnvironment() { return Environment(*_NSGetEnviron()); }
498
500 if (process_info.ProcessIDIsValid()) {
501 // Make a new mib to stay thread safe
502 int mib[CTL_MAXNAME] = {
503 0,
504 };
505 size_t mib_len = CTL_MAXNAME;
506 if (::sysctlnametomib("sysctl.proc_cputype", mib, &mib_len))
507 return false;
508
509 mib[mib_len] = process_info.GetProcessID();
510 mib_len++;
511
512 cpu_type_t cpu, sub = 0;
513 size_t len = sizeof(cpu);
514 if (::sysctl(mib, mib_len, &cpu, &len, 0, 0) == 0) {
515 switch (cpu) {
516 case CPU_TYPE_I386:
517 sub = CPU_SUBTYPE_I386_ALL;
518 break;
519 case CPU_TYPE_X86_64:
520 sub = CPU_SUBTYPE_X86_64_ALL;
521 break;
522
523#if defined(CPU_TYPE_ARM64) && defined(CPU_SUBTYPE_ARM64_ALL)
524 case CPU_TYPE_ARM64:
525 sub = CPU_SUBTYPE_ARM64_ALL;
526 break;
527#endif
528
529#if defined(CPU_TYPE_ARM64_32) && defined(CPU_SUBTYPE_ARM64_32_ALL)
531 sub = CPU_SUBTYPE_ARM64_32_ALL;
532 break;
533#endif
534
535 case CPU_TYPE_ARM: {
536 // Note that we fetched the cpu type from the PROCESS but we can't get a
537 // cpusubtype of the
538 // process -- we can only get the host's cpu subtype.
539 uint32_t cpusubtype = 0;
540 len = sizeof(cpusubtype);
541 if (::sysctlbyname("hw.cpusubtype", &cpusubtype, &len, NULL, 0) == 0)
542 sub = cpusubtype;
543
544 bool host_cpu_is_64bit;
545 uint32_t is64bit_capable;
546 size_t is64bit_capable_len = sizeof(is64bit_capable);
547 host_cpu_is_64bit =
548 sysctlbyname("hw.cpu64bit_capable", &is64bit_capable,
549 &is64bit_capable_len, NULL, 0) == 0;
550
551 // if the host is an armv8 device, its cpusubtype will be in
552 // CPU_SUBTYPE_ARM64 numbering
553 // and we need to rewrite it to a reasonable CPU_SUBTYPE_ARM value
554 // instead.
555
556 if (host_cpu_is_64bit) {
557 sub = CPU_SUBTYPE_ARM_V7;
558 }
559 } break;
560
561 default:
562 break;
563 }
564 process_info.GetArchitecture().SetArchitecture(eArchTypeMachO, cpu, sub);
565 return true;
566 }
567 }
568 process_info.GetArchitecture().Clear();
569 return false;
570}
571
572static bool GetMacOSXProcessArgs(const ProcessInstanceInfoMatch *match_info_ptr,
573 ProcessInstanceInfo &process_info) {
574 if (process_info.ProcessIDIsValid()) {
575 int proc_args_mib[3] = {CTL_KERN, KERN_PROCARGS2,
576 (int)process_info.GetProcessID()};
577
578 size_t arg_data_size = 0;
579 if (::sysctl(proc_args_mib, 3, nullptr, &arg_data_size, NULL, 0) ||
580 arg_data_size == 0)
581 arg_data_size = 8192;
582
583 // Add a few bytes to the calculated length, I know we need to add at least
584 // one byte
585 // to this number otherwise we get junk back, so add 128 just in case...
586 DataBufferHeap arg_data(arg_data_size + 128, 0);
587 arg_data_size = arg_data.GetByteSize();
588 if (::sysctl(proc_args_mib, 3, arg_data.GetBytes(), &arg_data_size, NULL,
589 0) == 0) {
590 DataExtractor data(arg_data.GetBytes(), arg_data_size,
591 endian::InlHostByteOrder(), sizeof(void *));
592 lldb::offset_t offset = 0;
593 uint32_t argc = data.GetU32(&offset);
594 llvm::Triple &triple = process_info.GetArchitecture().GetTriple();
595 const llvm::Triple::ArchType triple_arch = triple.getArch();
596 const bool check_for_ios_simulator =
597 (triple_arch == llvm::Triple::x86 ||
598 triple_arch == llvm::Triple::x86_64 ||
599 triple_arch == llvm::Triple::aarch64);
600
601 const char *cstr = data.GetCStr(&offset);
602 if (cstr) {
603 process_info.GetExecutableFile().SetFile(cstr, FileSpec::Style::native);
604
605 if (match_info_ptr == NULL ||
607 process_info.GetExecutableFile().GetFilename().GetCString(),
608 match_info_ptr->GetNameMatchType(),
609 match_info_ptr->GetProcessInfo().GetName())) {
610 // Skip NULLs
611 while (true) {
612 const uint8_t *p = data.PeekData(offset, 1);
613 if ((p == NULL) || (*p != '\0'))
614 break;
615 ++offset;
616 }
617
618 // Skip argv[0] as we already have the file name from the executable path.
619 if (argc > 0)
620 process_info.SetArg0(data.GetCStr(&offset));
621
622 // Now extract the rest of the arguments.
623 Args &proc_args = process_info.GetArguments();
624 for (int i = 1; i < static_cast<int>(argc); ++i) {
625 cstr = data.GetCStr(&offset);
626 if (cstr)
627 proc_args.AppendArgument(llvm::StringRef(cstr));
628 }
629
630 Environment &proc_env = process_info.GetEnvironment();
631 bool is_simulator = false;
632 llvm::StringRef env_var;
633 while (!(env_var = data.GetCStr(&offset)).empty()) {
634 if (check_for_ios_simulator &&
635 env_var.starts_with("SIMULATOR_UDID="))
636 is_simulator = true;
637 proc_env.insert(env_var);
638 }
639 llvm::Triple &triple = process_info.GetArchitecture().GetTriple();
640 if (is_simulator) {
641 triple.setOS(llvm::Triple::IOS);
642 triple.setEnvironment(llvm::Triple::Simulator);
643 } else {
644 triple.setOS(llvm::Triple::MacOSX);
645 }
646 return true;
647 }
648 }
649 }
650 }
651 return false;
652}
653
655 if (process_info.ProcessIDIsValid()) {
656 int mib[4];
657 mib[0] = CTL_KERN;
658 mib[1] = KERN_PROC;
659 mib[2] = KERN_PROC_PID;
660 mib[3] = process_info.GetProcessID();
661 struct kinfo_proc proc_kinfo;
662 size_t proc_kinfo_size = sizeof(struct kinfo_proc);
663
664 if (::sysctl(mib, 4, &proc_kinfo, &proc_kinfo_size, NULL, 0) == 0) {
665 if (proc_kinfo_size > 0) {
666 process_info.SetParentProcessID(proc_kinfo.kp_eproc.e_ppid);
667 process_info.SetUserID(proc_kinfo.kp_eproc.e_pcred.p_ruid);
668 process_info.SetGroupID(proc_kinfo.kp_eproc.e_pcred.p_rgid);
669 process_info.SetEffectiveUserID(proc_kinfo.kp_eproc.e_ucred.cr_uid);
670 if (proc_kinfo.kp_eproc.e_ucred.cr_ngroups > 0)
671 process_info.SetEffectiveGroupID(
672 proc_kinfo.kp_eproc.e_ucred.cr_groups[0]);
673 else
674 process_info.SetEffectiveGroupID(UINT32_MAX);
675 return true;
676 }
677 }
678 }
680 process_info.SetUserID(UINT32_MAX);
681 process_info.SetGroupID(UINT32_MAX);
682 process_info.SetEffectiveUserID(UINT32_MAX);
683 process_info.SetEffectiveGroupID(UINT32_MAX);
684 return false;
685}
686
687uint32_t Host::FindProcessesImpl(const ProcessInstanceInfoMatch &match_info,
688 ProcessInstanceInfoList &process_infos) {
689 std::vector<struct kinfo_proc> kinfos;
690
691 int mib[3] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL};
692
693 size_t pid_data_size = 0;
694 if (::sysctl(mib, 3, nullptr, &pid_data_size, nullptr, 0) != 0)
695 return 0;
696
697 // Add a few extra in case a few more show up
698 const size_t estimated_pid_count =
699 (pid_data_size / sizeof(struct kinfo_proc)) + 10;
700
701 kinfos.resize(estimated_pid_count);
702 pid_data_size = kinfos.size() * sizeof(struct kinfo_proc);
703
704 if (::sysctl(mib, 3, &kinfos[0], &pid_data_size, nullptr, 0) != 0)
705 return 0;
706
707 const size_t actual_pid_count = (pid_data_size / sizeof(struct kinfo_proc));
708
709 bool all_users = match_info.GetMatchAllUsers();
710 const lldb::pid_t our_pid = getpid();
711 const uid_t our_uid = getuid();
712 for (size_t i = 0; i < actual_pid_count; i++) {
713 const struct kinfo_proc &kinfo = kinfos[i];
714
715 bool kinfo_user_matches = false;
716 if (all_users)
717 kinfo_user_matches = true;
718 else
719 kinfo_user_matches = kinfo.kp_eproc.e_pcred.p_ruid == our_uid;
720
721 // Special case, if lldb is being run as root we can attach to anything.
722 if (our_uid == 0)
723 kinfo_user_matches = true;
724
725 if (!kinfo_user_matches || // Make sure the user is acceptable
726 static_cast<lldb::pid_t>(kinfo.kp_proc.p_pid) ==
727 our_pid || // Skip this process
728 kinfo.kp_proc.p_pid == 0 || // Skip kernel (kernel pid is zero)
729 kinfo.kp_proc.p_stat == SZOMB || // Zombies are bad, they like brains...
730 kinfo.kp_proc.p_flag & P_TRACED || // Being debugged?
731 kinfo.kp_proc.p_flag & P_WEXIT)
732 continue;
733
734 ProcessInstanceInfo process_info;
735 process_info.SetProcessID(kinfo.kp_proc.p_pid);
736 process_info.SetParentProcessID(kinfo.kp_eproc.e_ppid);
737 process_info.SetUserID(kinfo.kp_eproc.e_pcred.p_ruid);
738 process_info.SetGroupID(kinfo.kp_eproc.e_pcred.p_rgid);
739 process_info.SetEffectiveUserID(kinfo.kp_eproc.e_ucred.cr_uid);
740 if (kinfo.kp_eproc.e_ucred.cr_ngroups > 0)
741 process_info.SetEffectiveGroupID(kinfo.kp_eproc.e_ucred.cr_groups[0]);
742 else
743 process_info.SetEffectiveGroupID(UINT32_MAX);
744
745 // Make sure our info matches before we go fetch the name and cpu type
746 if (!match_info.UserIDsMatch(process_info) ||
747 !match_info.ProcessIDsMatch(process_info))
748 continue;
749
750 // Get CPU type first so we can know to look for iOS simulator if we have
751 // a compatible type.
752 if (GetMacOSXProcessCPUType(process_info)) {
753 if (GetMacOSXProcessArgs(&match_info, process_info)) {
754 if (match_info.Matches(process_info))
755 process_infos.push_back(process_info);
756 }
757 }
758 }
759 return process_infos.size();
760}
761
763 process_info.SetProcessID(pid);
764 bool success = false;
765
766 // Get CPU type first so we can know to look for iOS simulator is we have x86
767 // or x86_64
768 if (GetMacOSXProcessCPUType(process_info))
769 success = true;
770
771 if (GetMacOSXProcessArgs(NULL, process_info))
772 success = true;
773
774 if (GetMacOSXProcessUserAndGroup(process_info))
775 success = true;
776
777 if (success)
778 return true;
779
780 process_info.Clear();
781 return false;
782}
783
784#if TARGET_OS_OSX
785static void PackageXPCArguments(xpc_object_t message, const char *prefix,
786 const Args &args) {
787 size_t count = args.GetArgumentCount();
788 char buf[50]; // long enough for 'argXXX'
789 memset(buf, 0, sizeof(buf));
790 snprintf(buf, sizeof(buf), "%sCount", prefix);
791 xpc_dictionary_set_int64(message, buf, count);
792 for (size_t i = 0; i < count; i++) {
793 memset(buf, 0, sizeof(buf));
794 snprintf(buf, sizeof(buf), "%s%zi", prefix, i);
795 xpc_dictionary_set_string(message, buf, args.GetArgumentAtIndex(i));
796 }
797}
798
799static void PackageXPCEnvironment(xpc_object_t message, llvm::StringRef prefix,
800 const Environment &env) {
801 xpc_dictionary_set_int64(message, (prefix + "Count").str().c_str(),
802 env.size());
803 size_t i = 0;
804 for (const auto &KV : env) {
805 xpc_dictionary_set_string(message, (prefix + llvm::Twine(i)).str().c_str(),
806 Environment::compose(KV).c_str());
807 }
808}
809
810/*
811 A valid authorizationRef means that
812 - there is the LaunchUsingXPCRightName rights in the /etc/authorization
813 - we have successfully copied the rights to be send over the XPC wire
814 Once obtained, it will be valid for as long as the process lives.
815 */
816static AuthorizationRef authorizationRef = NULL;
817static Status getXPCAuthorization(ProcessLaunchInfo &launch_info) {
820
821 if ((launch_info.GetUserID() == 0) && !authorizationRef) {
822 OSStatus createStatus =
823 AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment,
824 kAuthorizationFlagDefaults, &authorizationRef);
825 if (createStatus != errAuthorizationSuccess) {
827 error = Status::FromErrorString("Can't create authorizationRef.");
828 LLDB_LOG(log, "error: {0}", error);
829 return error;
830 }
831
832 OSStatus rightsStatus =
833 AuthorizationRightGet(LaunchUsingXPCRightName, NULL);
834 if (rightsStatus != errAuthorizationSuccess) {
835 // No rights in the security database, Create it with the right prompt.
836 CFStringRef prompt =
837 CFSTR("Xcode is trying to take control of a root process.");
838 CFStringRef keys[] = {CFSTR("en")};
839 CFTypeRef values[] = {prompt};
840 CFDictionaryRef promptDict = CFDictionaryCreate(
841 kCFAllocatorDefault, (const void **)keys, (const void **)values, 1,
842 &kCFCopyStringDictionaryKeyCallBacks,
843 &kCFTypeDictionaryValueCallBacks);
844
845 CFStringRef keys1[] = {CFSTR("class"), CFSTR("group"), CFSTR("comment"),
846 CFSTR("default-prompt"), CFSTR("shared")};
847 CFTypeRef values1[] = {CFSTR("user"), CFSTR("admin"),
848 CFSTR(LaunchUsingXPCRightName), promptDict,
849 kCFBooleanFalse};
850 CFDictionaryRef dict = CFDictionaryCreate(
851 kCFAllocatorDefault, (const void **)keys1, (const void **)values1, 5,
852 &kCFCopyStringDictionaryKeyCallBacks,
853 &kCFTypeDictionaryValueCallBacks);
854 rightsStatus = AuthorizationRightSet(
855 authorizationRef, LaunchUsingXPCRightName, dict, NULL, NULL, NULL);
856 CFRelease(promptDict);
857 CFRelease(dict);
858 }
859
860 OSStatus copyRightStatus = errAuthorizationDenied;
861 if (rightsStatus == errAuthorizationSuccess) {
862 AuthorizationItem item1 = {LaunchUsingXPCRightName, 0, NULL, 0};
863 AuthorizationItem items[] = {item1};
864 AuthorizationRights requestedRights = {1, items};
865 AuthorizationFlags authorizationFlags =
866 kAuthorizationFlagInteractionAllowed | kAuthorizationFlagExtendRights;
867 copyRightStatus = AuthorizationCopyRights(
868 authorizationRef, &requestedRights, kAuthorizationEmptyEnvironment,
869 authorizationFlags, NULL);
870 }
871
872 if (copyRightStatus != errAuthorizationSuccess) {
873 // Eventually when the commandline supports running as root and the user
874 // is not
875 // logged in to the current audit session, we will need the trick in gdb
876 // where
877 // we ask the user to type in the root passwd in the terminal.
880 "Launching as root needs root authorization.");
881 LLDB_LOG(log, "error: {0}", error);
882
883 if (authorizationRef) {
884 AuthorizationFree(authorizationRef, kAuthorizationFlagDefaults);
885 authorizationRef = NULL;
886 }
887 }
888 }
889
890 return error;
891}
892#endif
893
894static short GetPosixspawnFlags(const ProcessLaunchInfo &launch_info) {
895 short flags = POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK;
896
897 if (launch_info.GetFlags().Test(eLaunchFlagExec))
898 flags |= POSIX_SPAWN_SETEXEC; // Darwin specific posix_spawn flag
899
900 if (launch_info.GetFlags().Test(eLaunchFlagDebug))
901 flags |= POSIX_SPAWN_START_SUSPENDED; // Darwin specific posix_spawn flag
902
903 if (launch_info.GetFlags().Test(eLaunchFlagDisableASLR))
904 flags |= _POSIX_SPAWN_DISABLE_ASLR; // Darwin specific posix_spawn flag
905
906 if (launch_info.GetLaunchInSeparateProcessGroup())
907 flags |= POSIX_SPAWN_SETPGROUP;
908
909#ifdef POSIX_SPAWN_CLOEXEC_DEFAULT
910#if defined(__x86_64__) || defined(__i386__)
911 static LazyBool g_use_close_on_exec_flag = eLazyBoolCalculate;
912 if (g_use_close_on_exec_flag == eLazyBoolCalculate) {
913 g_use_close_on_exec_flag = eLazyBoolNo;
914
915 llvm::VersionTuple version = HostInfo::GetOSVersion();
916 if (version > llvm::VersionTuple(10, 7)) {
917 // Kernel panic if we use the POSIX_SPAWN_CLOEXEC_DEFAULT on 10.7 or
918 // earlier
919 g_use_close_on_exec_flag = eLazyBoolYes;
920 }
921 }
922#else
923 static LazyBool g_use_close_on_exec_flag = eLazyBoolYes;
924#endif // defined(__x86_64__) || defined(__i386__)
925 // Close all files exception those with file actions if this is supported.
926 if (g_use_close_on_exec_flag == eLazyBoolYes)
927 flags |= POSIX_SPAWN_CLOEXEC_DEFAULT;
928#endif // ifdef POSIX_SPAWN_CLOEXEC_DEFAULT
929 return flags;
930}
931
932static void finalize_xpc(void *xpc_object) {
933 xpc_release((xpc_object_t)xpc_object);
934}
935
936static Status LaunchProcessXPC(const char *exe_path,
937 ProcessLaunchInfo &launch_info,
938 lldb::pid_t &pid) {
939#if TARGET_OS_OSX
940 Status error = getXPCAuthorization(launch_info);
941 if (error.Fail())
942 return error;
943
945
946 uid_t requested_uid = launch_info.GetUserID();
947 const char *xpc_service = nil;
948 bool send_auth = false;
949 AuthorizationExternalForm extForm;
950 if (requested_uid == 0) {
951 if (AuthorizationMakeExternalForm(authorizationRef, &extForm) ==
952 errAuthorizationSuccess) {
953 send_auth = true;
954 } else {
957 "Launching root via XPC needs to "
958 "externalize authorization reference.");
959 LLDB_LOG(log, "error: {0}", error);
960 return error;
961 }
962 xpc_service = LaunchUsingXPCRightName;
963 } else {
966 "Launching via XPC is only currently available for root.");
967 LLDB_LOG(log, "error: {0}", error);
968 return error;
969 }
970
971 xpc_connection_t conn = xpc_connection_create(xpc_service, NULL);
972
973 xpc_connection_set_event_handler(conn, ^(xpc_object_t event) {
974 xpc_type_t type = xpc_get_type(event);
975
976 if (type == XPC_TYPE_ERROR) {
977 if (event == XPC_ERROR_CONNECTION_INTERRUPTED) {
978 // The service has either canceled itself, crashed, or been terminated.
979 // The XPC connection is still valid and sending a message to it will
980 // re-launch the service.
981 // If the service is state-full, this is the time to initialize the new
982 // service.
983 return;
984 } else if (event == XPC_ERROR_CONNECTION_INVALID) {
985 // The service is invalid. Either the service name supplied to
986 // xpc_connection_create() is incorrect
987 // or we (this process) have canceled the service; we can do any cleanup
988 // of application state at this point.
989 // printf("Service disconnected");
990 return;
991 } else {
992 // printf("Unexpected error from service: %s",
993 // xpc_dictionary_get_string(event, XPC_ERROR_KEY_DESCRIPTION));
994 }
995
996 } else {
997 // printf("Received unexpected event in handler");
998 }
999 });
1000
1001 xpc_connection_set_finalizer_f(conn, finalize_xpc);
1002 xpc_connection_resume(conn);
1003 xpc_object_t message = xpc_dictionary_create(nil, nil, 0);
1004
1005 if (send_auth) {
1006 xpc_dictionary_set_data(message, LauncherXPCServiceAuthKey, extForm.bytes,
1007 sizeof(AuthorizationExternalForm));
1008 }
1009
1010 PackageXPCArguments(message, LauncherXPCServiceArgPrefxKey,
1011 launch_info.GetArguments());
1012 PackageXPCEnvironment(message, LauncherXPCServiceEnvPrefxKey,
1013 launch_info.GetEnvironment());
1014
1015 // Posix spawn stuff.
1016 xpc_dictionary_set_int64(message, LauncherXPCServiceCPUTypeKey,
1017 launch_info.GetArchitecture().GetMachOCPUType());
1018 xpc_dictionary_set_int64(message, LauncherXPCServicePosixspawnFlagsKey,
1019 GetPosixspawnFlags(launch_info));
1020 const FileAction *file_action = launch_info.GetFileActionForFD(STDIN_FILENO);
1021 std::string file_action_path;
1022 if (file_action)
1023 file_action_path = file_action->GetFileSpec().GetPath();
1024
1025 if (!file_action_path.empty())
1026 xpc_dictionary_set_string(message, LauncherXPCServiceStdInPathKeyKey,
1027 file_action_path.c_str());
1028
1029 file_action = launch_info.GetFileActionForFD(STDOUT_FILENO);
1030 if (file_action)
1031 file_action_path = file_action->GetFileSpec().GetPath();
1032
1033 if (!file_action_path.empty())
1034 xpc_dictionary_set_string(message, LauncherXPCServiceStdOutPathKeyKey,
1035 file_action_path.c_str());
1036
1037 file_action = launch_info.GetFileActionForFD(STDERR_FILENO);
1038 if (file_action)
1039 file_action_path = file_action->GetFileSpec().GetPath();
1040
1041 if (!file_action_path.empty())
1042 xpc_dictionary_set_string(message, LauncherXPCServiceStdErrPathKeyKey,
1043 file_action_path.c_str());
1044
1045 xpc_object_t reply =
1046 xpc_connection_send_message_with_reply_sync(conn, message);
1047 xpc_type_t returnType = xpc_get_type(reply);
1048 if (returnType == XPC_TYPE_DICTIONARY) {
1049 pid = xpc_dictionary_get_int64(reply, LauncherXPCServiceChildPIDKey);
1050 if (pid == 0) {
1051 int errorType =
1052 xpc_dictionary_get_int64(reply, LauncherXPCServiceErrorTypeKey);
1053 int errorCode =
1054 xpc_dictionary_get_int64(reply, LauncherXPCServiceCodeTypeKey);
1055
1056 error = Status(errorCode, eErrorTypeGeneric);
1058 "Problems with launching via XPC. Error type : %i, code : %i",
1059 errorType, errorCode);
1060 LLDB_LOG(log, "error: {0}", error);
1061
1062 if (authorizationRef) {
1063 AuthorizationFree(authorizationRef, kAuthorizationFlagDefaults);
1064 authorizationRef = NULL;
1065 }
1066 }
1067 } else if (returnType == XPC_TYPE_ERROR) {
1070 "Problems with launching via XPC. XPC error : %s",
1071 xpc_dictionary_get_string(reply, XPC_ERROR_KEY_DESCRIPTION));
1072 LLDB_LOG(log, "error: {0}", error);
1073 }
1074
1075 return error;
1076#else
1077 Status error;
1078 return error;
1079#endif
1080}
1081
1082static bool AddPosixSpawnFileAction(void *_file_actions, const FileAction *info,
1083 Log *log, Status &error) {
1084 if (info == NULL)
1085 return false;
1086
1087 posix_spawn_file_actions_t *file_actions =
1088 static_cast<posix_spawn_file_actions_t *>(_file_actions);
1089
1090 switch (info->GetAction()) {
1092 error.Clear();
1093 break;
1094
1096 if (info->GetFD() == -1)
1098 "invalid fd for posix_spawn_file_actions_addclose(...)");
1099 else {
1100 error = Status(
1101 ::posix_spawn_file_actions_addclose(file_actions, info->GetFD()),
1103 if (error.Fail())
1104 LLDB_LOG(log,
1105 "error: {0}, posix_spawn_file_actions_addclose "
1106 "(action={1}, fd={2})",
1107 error, file_actions, info->GetFD());
1108 }
1109 break;
1110
1112 if (info->GetFD() == -1)
1114 "invalid fd for posix_spawn_file_actions_adddup2(...)");
1115 else if (info->GetActionArgument() == -1)
1117 "invalid duplicate fd for posix_spawn_file_actions_adddup2(...)");
1118 else if (info->GetFD() != info->GetActionArgument()) {
1119 error =
1120 Status(::posix_spawn_file_actions_adddup2(file_actions, info->GetFD(),
1121 info->GetActionArgument()),
1123 if (error.Fail())
1124 LLDB_LOG(log,
1125 "error: {0}, posix_spawn_file_actions_adddup2 "
1126 "(action={1}, fd={2}, dup_fd={3})",
1127 error, file_actions, info->GetFD(), info->GetActionArgument());
1128 } else {
1129 error =
1130 Status(::posix_spawn_file_actions_addinherit_np(file_actions, info->GetFD()),
1132 if (error.Fail())
1133 LLDB_LOG(log,
1134 "error: {0}, posix_spawn_file_actions_addinherit_np "
1135 "(action={1}, fd={2})",
1136 error, file_actions, info->GetFD());
1137 }
1138 break;
1139
1141 if (info->GetFD() == -1)
1143 "invalid fd in posix_spawn_file_actions_addopen(...)");
1144 else {
1145 int oflag = info->GetActionArgument();
1146
1147 mode_t mode = 0;
1148
1149 if (oflag & O_CREAT)
1150 mode = 0640;
1151
1152 const std::string file_path(info->GetFileSpec().GetPath());
1153 error = Status(
1154 ::posix_spawn_file_actions_addopen(file_actions, info->GetFD(),
1155 file_path.c_str(), oflag, mode),
1157 if (error.Fail())
1158 LLDB_LOG(log,
1159 "error: {0}, posix_spawn_file_actions_addopen (action={1}, "
1160 "fd={2}, path='{3}', oflag={4}, mode={5})",
1161 error, file_actions, info->GetFD(), file_path, oflag, mode);
1162 }
1163 break;
1164 }
1165 return error.Success();
1166}
1167
1168static Status LaunchProcessPosixSpawn(const char *exe_path,
1169 const ProcessLaunchInfo &launch_info,
1170 lldb::pid_t &pid) {
1171 Status error;
1173
1174 posix_spawnattr_t attr;
1175 error = Status(::posix_spawnattr_init(&attr), eErrorTypePOSIX);
1176
1177 if (error.Fail()) {
1178 LLDB_LOG(log, "error: {0}, ::posix_spawnattr_init ( &attr )", error);
1179 return error;
1180 }
1181
1182 // Make sure we clean up the posix spawn attributes before exiting this scope.
1183 llvm::scope_exit cleanup_attr([&]() { posix_spawnattr_destroy(&attr); });
1184
1185 sigset_t no_signals;
1186 sigset_t all_signals;
1187 sigemptyset(&no_signals);
1188 sigfillset(&all_signals);
1189 ::posix_spawnattr_setsigmask(&attr, &no_signals);
1190 ::posix_spawnattr_setsigdefault(&attr, &all_signals);
1191
1192 short flags = GetPosixspawnFlags(launch_info);
1193
1194 error = Status(::posix_spawnattr_setflags(&attr, flags), eErrorTypePOSIX);
1195 if (error.Fail()) {
1196 LLDB_LOG(log,
1197 "error: {0}, ::posix_spawnattr_setflags ( &attr, flags={1:x} )",
1198 error, flags);
1199 return error;
1200 }
1201
1202 bool is_graphical = true;
1203
1204#if TARGET_OS_OSX
1205 SecuritySessionId session_id;
1206 SessionAttributeBits session_attributes;
1207 OSStatus status =
1208 SessionGetInfo(callerSecuritySession, &session_id, &session_attributes);
1209 if (status == errSessionSuccess)
1210 is_graphical = session_attributes & sessionHasGraphicAccess;
1211#endif
1212
1213 // When lldb is ran through a graphical session, make the debuggee process
1214 // responsible for its own TCC permissions instead of inheriting them from
1215 // its parent.
1216 if (is_graphical && launch_info.GetFlags().Test(eLaunchFlagDebug) &&
1217 !launch_info.GetFlags().Test(eLaunchFlagInheritTCCFromParent)) {
1219 if (error.Fail()) {
1220 LLDB_LOG(log, "error: {0}, setup_posix_spawn_responsible_flag(&attr)",
1221 error);
1222 return error;
1223 }
1224 }
1225
1226 if (launch_info.GetFlags().Test(eLaunchFlagMemoryTagging)) {
1227 // The following function configures the spawn attributes to launch the
1228 // process with memory tagging explicitly enabled. We look it up
1229 // dynamically since it is only available on newer OS. Does nothing on
1230 // hardware which does not support MTE.
1231 //
1232 // int posix_spawnattr_set_use_sec_transition_shims_np(
1233 // posix_spawnattr_t *attr, uint32_t flags);
1234 //
1235 using posix_spawnattr_set_use_sec_transition_shims_np_t =
1236 int (*)(posix_spawnattr_t *attr, uint32_t flags);
1237 auto posix_spawnattr_enable_memory_tagging_fn =
1238 (posix_spawnattr_set_use_sec_transition_shims_np_t)dlsym(
1239 RTLD_DEFAULT, "posix_spawnattr_set_use_sec_transition_shims_np");
1240 if (posix_spawnattr_enable_memory_tagging_fn) {
1241 error = Status(posix_spawnattr_enable_memory_tagging_fn(&attr, 0),
1243 if (error.Fail()) {
1244 LLDB_LOG(log,
1245 "error: {}, "
1246 "posix_spawnattr_set_use_sec_transition_shims_np(&attr, 0)",
1247 error);
1248 return error;
1249 }
1250 } else {
1251 LLDB_LOG(log,
1252 "error: {}, posix_spawnattr_set_use_sec_transition_shims_np "
1253 "not available",
1254 error);
1255 }
1256 }
1257
1258 // Don't set the binpref if a shell was provided. After all, that's only
1259 // going to affect what version of the shell is launched, not what fork of
1260 // the binary is launched. We insert "arch --arch <ARCH> as part of the
1261 // shell invocation to do that job on OSX.
1262 if (launch_info.GetShell() == FileSpec()) {
1263 const ArchSpec &arch_spec = launch_info.GetArchitecture();
1264 cpu_type_t cpu_type = arch_spec.GetMachOCPUType();
1265 cpu_type_t cpu_subtype = arch_spec.GetMachOCPUSubType();
1266 const bool set_cpu_type =
1267 cpu_type != 0 && cpu_type != static_cast<cpu_type_t>(UINT32_MAX) &&
1268 cpu_type != static_cast<cpu_type_t>(LLDB_INVALID_CPUTYPE);
1269 const bool set_cpu_subtype =
1270 cpu_subtype != 0 &&
1271 cpu_subtype != static_cast<cpu_subtype_t>(UINT32_MAX) &&
1272 cpu_subtype != CPU_SUBTYPE_X86_64_H;
1273 if (set_cpu_type) {
1274 size_t ocount = 0;
1275 typedef int (*posix_spawnattr_setarchpref_np_t)(
1276 posix_spawnattr_t *, size_t, cpu_type_t *, cpu_subtype_t *, size_t *);
1277 posix_spawnattr_setarchpref_np_t posix_spawnattr_setarchpref_np_fn =
1278 (posix_spawnattr_setarchpref_np_t)dlsym(
1279 RTLD_DEFAULT, "posix_spawnattr_setarchpref_np");
1280 if (set_cpu_subtype && posix_spawnattr_setarchpref_np_fn) {
1281 error = Status((*posix_spawnattr_setarchpref_np_fn)(
1282 &attr, 1, &cpu_type, &cpu_subtype, &ocount),
1284 if (error.Fail())
1285 LLDB_LOG(log,
1286 "error: {}, ::posix_spawnattr_setarchpref_np ( &attr, 1, "
1287 "cpu_type = {:x}, cpu_subtype = {:x}, count => {} )",
1288 error, cpu_type, cpu_subtype, ocount);
1289
1290 if (error.Fail() || ocount != 1)
1291 return error;
1292 } else {
1293 error = Status(
1294 ::posix_spawnattr_setbinpref_np(&attr, 1, &cpu_type, &ocount),
1296 if (error.Fail())
1297 LLDB_LOG(log,
1298 "error: {0}, ::posix_spawnattr_setbinpref_np ( &attr, 1, "
1299 "cpu_type = {1:x}, count => {2} )",
1300 error, cpu_type, ocount);
1301 if (error.Fail() || ocount != 1)
1302 return error;
1303 }
1304 }
1305 }
1306
1307 const char *tmp_argv[2];
1308 char *const *argv = const_cast<char *const *>(
1309 launch_info.GetArguments().GetConstArgumentVector());
1310 Environment::Envp envp = launch_info.GetEnvironment().getEnvp();
1311 if (argv == NULL) {
1312 // posix_spawn gets very unhappy if it doesn't have at least the program
1313 // name in argv[0]. One of the side affects I have noticed is the
1314 // environment
1315 // variables don't make it into the child process if "argv == NULL"!!!
1316 tmp_argv[0] = exe_path;
1317 tmp_argv[1] = NULL;
1318 argv = const_cast<char *const *>(tmp_argv);
1319 }
1320
1321 FileSpec working_dir{launch_info.GetWorkingDirectory()};
1322 if (working_dir) {
1323 // Set the working directory on this thread only
1324 std::string working_dir_path = working_dir.GetPath();
1325 if (__pthread_chdir(working_dir_path.c_str()) < 0) {
1326 if (errno == ENOENT) {
1328 "No such file or directory: %s", working_dir_path.c_str());
1329 } else if (errno == ENOTDIR) {
1331 "Path doesn't name a directory: %s", working_dir_path.c_str());
1332 } else {
1333 error =
1334 Status::FromErrorStringWithFormat("An unknown error occurred when "
1335 "changing directory for process "
1336 "execution.");
1337 }
1338 return error;
1339 }
1340 }
1341
1342 ::pid_t result_pid = LLDB_INVALID_PROCESS_ID;
1343 const size_t num_file_actions = launch_info.GetNumFileActions();
1344 if (num_file_actions > 0) {
1345 posix_spawn_file_actions_t file_actions;
1346 error =
1347 Status(::posix_spawn_file_actions_init(&file_actions), eErrorTypePOSIX);
1348 if (error.Fail()) {
1349 LLDB_LOG(log,
1350 "error: {0}, ::posix_spawn_file_actions_init ( &file_actions )",
1351 error);
1352 return error;
1353 }
1354
1355 // Make sure we clean up the posix file actions before exiting this scope.
1356 llvm::scope_exit cleanup_fileact(
1357 [&]() { posix_spawn_file_actions_destroy(&file_actions); });
1358
1359 for (size_t i = 0; i < num_file_actions; ++i) {
1360 const FileAction *launch_file_action =
1361 launch_info.GetFileActionAtIndex(i);
1362 if (launch_file_action) {
1363 if (!AddPosixSpawnFileAction(&file_actions, launch_file_action, log,
1364 error))
1365 return error;
1366 }
1367 }
1368
1369 error = Status(
1370 ::posix_spawnp(&result_pid, exe_path, &file_actions, &attr, argv, envp),
1372
1373 if (error.Fail()) {
1374 LLDB_LOG(log,
1375 "error: {0}, ::posix_spawnp(pid => {1}, path = '{2}', "
1376 "file_actions = {3}, "
1377 "attr = {4}, argv = {5}, envp = {6} )",
1378 error, result_pid, exe_path, &file_actions, &attr, argv,
1379 envp.get());
1380 if (log) {
1381 for (int ii = 0; argv[ii]; ++ii)
1382 LLDB_LOG(log, "argv[{0}] = '{1}'", ii, argv[ii]);
1383 }
1384 }
1385
1386 } else {
1387 error =
1388 Status(::posix_spawnp(&result_pid, exe_path, NULL, &attr, argv, envp),
1390
1391 if (error.Fail()) {
1392 LLDB_LOG(log,
1393 "error: {0}, ::posix_spawnp ( pid => {1}, path = '{2}', "
1394 "file_actions = NULL, attr = {3}, argv = {4}, envp = {5} )",
1395 error, result_pid, exe_path, &attr, argv, envp.get());
1396 if (log) {
1397 for (int ii = 0; argv[ii]; ++ii)
1398 LLDB_LOG(log, "argv[{0}] = '{1}'", ii, argv[ii]);
1399 }
1400 }
1401 }
1402 pid = result_pid;
1403
1404 if (working_dir) {
1405 // No more thread specific current working directory
1406 __pthread_fchdir(-1);
1407 }
1408
1409 return error;
1410}
1411
1412static bool ShouldLaunchUsingXPC(ProcessLaunchInfo &launch_info) {
1413 bool result = false;
1414
1415#if TARGET_OS_OSX
1416 bool launchingAsRoot = launch_info.GetUserID() == 0;
1417 bool currentUserIsRoot = HostInfo::GetEffectiveUserID() == 0;
1418
1419 if (launchingAsRoot && !currentUserIsRoot) {
1420 // If current user is already root, we don't need XPC's help.
1421 result = true;
1422 }
1423#endif
1424
1425 return result;
1426}
1427
1429 Status error;
1430
1431 FileSystem &fs = FileSystem::Instance();
1432 FileSpec exe_spec(launch_info.GetExecutableFile());
1433
1434 if (!fs.Exists(exe_spec))
1435 FileSystem::Instance().Resolve(exe_spec);
1436
1437 if (!fs.Exists(exe_spec))
1439
1440 if (!fs.Exists(exe_spec)) {
1442 "executable doesn't exist: '{0}'", exe_spec);
1443 return error;
1444 }
1445
1446 if (launch_info.GetFlags().Test(eLaunchFlagLaunchInTTY)) {
1447#if TARGET_OS_OSX
1448 return LaunchInNewTerminalWithAppleScript(exe_spec.GetPath().c_str(),
1449 launch_info);
1450#else
1451 error =
1452 Status::FromErrorString("launching a process in a new terminal is not "
1453 "supported on iOS devices");
1454 return error;
1455#endif
1456 }
1457
1459
1460 auto exe_path = exe_spec.GetPath();
1461
1462 if (ShouldLaunchUsingXPC(launch_info))
1463 error = LaunchProcessXPC(exe_path.c_str(), launch_info, pid);
1464 else
1465 error = LaunchProcessPosixSpawn(exe_path.c_str(), launch_info, pid);
1466
1467 if (pid != LLDB_INVALID_PROCESS_ID) {
1468 // If all went well, then set the process ID into the launch info
1469 launch_info.SetProcessID(pid);
1470
1471 // Make sure we reap any processes we spawn or we will have zombies.
1472 bool monitoring = launch_info.MonitorProcess();
1473 UNUSED_IF_ASSERT_DISABLED(monitoring);
1474 assert(monitoring);
1475 } else {
1476 // Invalid process ID, something didn't go well
1477 if (error.Success())
1478 error =
1479 Status::FromErrorString("process launch failed for unknown reasons");
1480 }
1481 return error;
1482}
1483
1485 Status error;
1486 if (launch_info.GetFlags().Test(eLaunchFlagShellExpandArguments)) {
1487 FileSpec expand_tool_spec;
1488 Environment host_env = Host::GetEnvironment();
1489 std::string env_argdumper_path = host_env.lookup("LLDB_ARGDUMPER_PATH");
1490 if (!env_argdumper_path.empty()) {
1491 expand_tool_spec.SetFile(env_argdumper_path, FileSpec::Style::native);
1493 LLDB_LOGF(log,
1494 "lldb-argdumper exe path set from environment variable: %s",
1495 env_argdumper_path.c_str());
1496 }
1497 bool argdumper_exists = FileSystem::Instance().Exists(env_argdumper_path);
1498 if (!argdumper_exists) {
1499 expand_tool_spec = HostInfo::GetSupportExeDir();
1500 if (!expand_tool_spec) {
1502 "could not get support executable directory for "
1503 "lldb-argdumper tool");
1504 return error;
1505 }
1506 expand_tool_spec.AppendPathComponent("lldb-argdumper");
1507 if (!FileSystem::Instance().Exists(expand_tool_spec)) {
1509 "could not find the lldb-argdumper tool: %s",
1510 expand_tool_spec.GetPath().c_str());
1511 return error;
1512 }
1513 }
1514
1515 StreamString expand_tool_spec_stream;
1516 expand_tool_spec_stream.Printf("\"%s\"",
1517 expand_tool_spec.GetPath().c_str());
1518
1519 Args expand_command(expand_tool_spec_stream.GetData());
1520 expand_command.AppendArguments(launch_info.GetArguments());
1521
1522 int status;
1523 std::string output;
1524 FileSpec cwd(launch_info.GetWorkingDirectory());
1525 if (!FileSystem::Instance().Exists(cwd)) {
1526 char *wd = getcwd(nullptr, 0);
1527 if (wd == nullptr) {
1529 "cwd does not exist: Cannot launch with shell argument expansion");
1530 return error;
1531 } else {
1532 FileSpec working_dir(wd);
1533 free(wd);
1534 launch_info.SetWorkingDirectory(working_dir);
1535 }
1536 }
1537 bool run_in_shell = true;
1538 std::string error_output; // Pass stderr string arg so it is not mixed with
1539 // stdout.
1540 Status e =
1541 RunShellCommand(expand_command, cwd, &status, nullptr, &output,
1542 &error_output, std::chrono::seconds(10), run_in_shell);
1543
1544 if (e.Fail())
1545 return e;
1546
1547 if (status != 0) {
1549 "lldb-argdumper exited with error %d", status);
1550 return error;
1551 }
1552
1553 auto data_sp = StructuredData::ParseJSON(output);
1554 if (!data_sp) {
1555 error = Status::FromErrorString("invalid JSON");
1556 return error;
1557 }
1558
1559 auto dict_sp = data_sp->GetAsDictionary();
1560 if (!data_sp) {
1561 error = Status::FromErrorString("invalid JSON");
1562 return error;
1563 }
1564
1565 auto args_sp = dict_sp->GetObjectForDotSeparatedPath("arguments");
1566 if (!args_sp) {
1567 error = Status::FromErrorString("invalid JSON");
1568 return error;
1569 }
1570
1571 auto args_array_sp = args_sp->GetAsArray();
1572 if (!args_array_sp) {
1573 error = Status::FromErrorString("invalid JSON");
1574 return error;
1575 }
1576
1577 launch_info.GetArguments().Clear();
1578
1579 for (size_t i = 0; i < args_array_sp->GetSize(); i++) {
1580 auto item_sp = args_array_sp->GetItemAtIndex(i);
1581 if (!item_sp)
1582 continue;
1583 auto str_sp = item_sp->GetAsString();
1584 if (!str_sp)
1585 continue;
1586
1587 launch_info.GetArguments().AppendArgument(str_sp->GetValue());
1588 }
1589 }
1590
1591 return error;
1592}
1593
1594llvm::Expected<HostThread> Host::StartMonitoringChildProcess(
1595 const Host::MonitorChildProcessCallback &callback, lldb::pid_t pid) {
1596 unsigned long mask = DISPATCH_PROC_EXIT;
1597
1599
1600 dispatch_source_t source = ::dispatch_source_create(
1601 DISPATCH_SOURCE_TYPE_PROC, pid, mask,
1602 ::dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0));
1603
1604 LLDB_LOGF(log,
1605 "Host::StartMonitoringChildProcess(callback, pid=%i) source = %p\n",
1606 static_cast<int>(pid), static_cast<void *>(source));
1607
1608 if (source) {
1609 Host::MonitorChildProcessCallback callback_copy = callback;
1610 ::dispatch_source_set_cancel_handler(source, ^{
1611 dispatch_release(source);
1612 });
1613 ::dispatch_source_set_event_handler(source, ^{
1614
1615 int status = 0;
1616 int wait_pid = 0;
1617 wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, pid, &status, 0);
1618 if (wait_pid >= 0) {
1619 int signal = 0;
1620 int exit_status = 0;
1621 const char *status_cstr = NULL;
1622 if (WIFEXITED(status)) {
1623 exit_status = WEXITSTATUS(status);
1624 status_cstr = "EXITED";
1625 } else if (WIFSIGNALED(status)) {
1626 signal = WTERMSIG(status);
1627 status_cstr = "SIGNALED";
1628 exit_status = -1;
1629 } else {
1630 llvm_unreachable("Unknown status");
1631 }
1632
1633 LLDB_LOGF(log,
1634 "::waitpid (pid = %llu, &status, 0) => pid = %i, status "
1635 "= 0x%8.8x (%s), signal = %i, exit_status = %i",
1636 pid, wait_pid, status, status_cstr, signal, exit_status);
1637
1638 if (callback_copy)
1639 callback_copy(pid, signal, exit_status);
1640
1641 ::dispatch_source_cancel(source);
1642 }
1643 });
1644
1645 ::dispatch_resume(source);
1646 }
1647 return HostThread();
1648}
static llvm::raw_ostream & error(Stream &strm)
#define CPU_SUBTYPE_X86_64_H
#define CPU_TYPE_ARM64
#define CPU_TYPE_ARM64_32
static Status LaunchProcessPosixSpawn(const char *exe_path, const ProcessLaunchInfo &launch_info, lldb::pid_t &pid)
Definition Host.mm:1168
static os_log_t g_os_log
Definition Host.mm:102
static Status LaunchProcessXPC(const char *exe_path, ProcessLaunchInfo &launch_info, lldb::pid_t &pid)
Definition Host.mm:936
static short GetPosixspawnFlags(const ProcessLaunchInfo &launch_info)
Definition Host.mm:894
#define _POSIX_SPAWN_DISABLE_ASLR
Definition Host.mm:91
int __pthread_chdir(const char *path)
static bool GetMacOSXProcessUserAndGroup(ProcessInstanceInfo &process_info)
Definition Host.mm:654
static std::once_flag g_os_log_once
Definition Host.mm:103
static bool GetMacOSXProcessCPUType(ProcessInstanceInfo &process_info)
Definition Host.mm:499
static void finalize_xpc(void *xpc_object)
Definition Host.mm:932
int __pthread_fchdir(int fildes)
static bool ShouldLaunchUsingXPC(ProcessLaunchInfo &launch_info)
Definition Host.mm:1412
static bool AddPosixSpawnFileAction(void *_file_actions, const FileAction *info, Log *log, Status &error)
Definition Host.mm:1082
static bool GetMacOSXProcessArgs(const ProcessInstanceInfoMatch *match_info_ptr, ProcessInstanceInfo &process_info)
Definition Host.mm:572
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:364
#define LLDB_LOGF(log,...)
Definition Log.h:378
static int setup_posix_spawn_responsible_flag(posix_spawnattr_t *attr)
int cpu_subtype_t
int cpu_type_t
An architecture specification class.
Definition ArchSpec.h:32
bool IsValid() const
Tests if this ArchSpec is valid.
Definition ArchSpec.h:370
void Clear()
Clears the object state.
Definition ArchSpec.cpp:547
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition ArchSpec.h:460
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.
Definition ArchSpec.cpp:852
uint32_t GetMachOCPUSubType() const
Definition ArchSpec.cpp:670
uint32_t GetMachOCPUType() const
Definition ArchSpec.cpp:658
Core GetCore() const
Definition ArchSpec.h:451
const char * GetArchitectureName() const
Returns a static string representing the current architecture.
Definition ArchSpec.cpp:557
A command line argument class.
Definition Args.h:33
size_t GetArgumentCount() const
Gets the number of arguments left in this command object.
Definition Args.h:120
void AppendArgument(llvm::StringRef arg_str, char quote_char='\0')
Appends a new argument to the end of the list argument list.
Definition Args.cpp:332
const char * GetArgumentAtIndex(size_t idx) const
Gets the NULL terminated C string argument pointer for the argument at index idx.
Definition Args.cpp:273
const char ** GetConstArgumentVector() const
Gets the argument vector.
Definition Args.cpp:289
void Clear()
Clear the arguments.
Definition Args.cpp:388
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.
An data extractor class.
const char * GetCStr(lldb::offset_t *offset_ptr) const
Extract a C string from *offset_ptr.
virtual const uint8_t * PeekData(lldb::offset_t offset, lldb::offset_t length) const
Peek at a bytes at offset.
uint32_t GetU32(lldb::offset_t *offset_ptr) const
Extract a uint32_t value from *offset_ptr.
char *const * get() const
Definition Environment.h:27
static std::string compose(const value_type &KeyValue)
Definition Environment.h:80
std::pair< iterator, bool > insert(llvm::StringRef KeyEqValue)
Definition Environment.h:71
Represents a file descriptor action to be performed during process launch.
Definition FileAction.h:21
Action GetAction() const
Get the type of action.
Definition FileAction.h:59
int GetActionArgument() const
Get the action-specific argument.
Definition FileAction.h:65
const FileSpec & GetFileSpec() const
Get the file specification for open actions.
int GetFD() const
Get the file descriptor this action applies to.
Definition FileAction.h:56
A file utility class.
Definition FileSpec.h:57
void SetFile(llvm::StringRef path, Style style)
Change the file specified with a new path.
Definition FileSpec.cpp:174
void AppendPathComponent(llvm::StringRef component)
Definition FileSpec.cpp:454
const ConstString & GetFilename() const
Filename string const get accessor.
Definition FileSpec.h:250
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:374
void Clear()
Clears the object state.
Definition FileSpec.cpp:259
void SetFilename(ConstString filename)
Filename string set accessor.
Definition FileSpec.cpp:352
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()
void Resolve(llvm::SmallVectorImpl< char > &path, bool force_make_absolute=false)
Resolve path to make it canonical.
bool Test(ValueType bit) const
Test a single flag bit.
Definition Flags.h:96
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 llvm::Error OpenURL(llvm::StringRef url)
Definition Host.mm:455
static Status ShellExpandArguments(ProcessLaunchInfo &launch_info)
Perform expansion of the command-line for this launch info This can potentially involve wildcard expa...
Definition aix/Host.cpp:216
static Environment GetEnvironment()
static Status RunShellCommand(llvm::StringRef command, const FileSpec &working_dir, int *status_ptr, int *signo_ptr, std::string *command_output, std::string *error_output, const Timeout< std::micro > &timeout, bool run_in_shell=true)
Run a shell command.
static uint32_t FindProcessesImpl(const ProcessInstanceInfoMatch &match_info, ProcessInstanceInfoList &proc_infos)
Definition aix/Host.cpp:169
static bool GetProcessInfo(lldb::pid_t pid, ProcessInstanceInfo &proc_info)
Definition aix/Host.cpp:211
std::function< void(lldb::pid_t pid, int signal, int status)> MonitorChildProcessCallback
Definition Host.h:88
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)
Definition ProcessInfo.h:60
bool ProcessIDIsValid() const
Definition ProcessInfo.h:72
void SetArg0(llvm::StringRef arg)
const char * GetName() const
lldb::pid_t GetProcessID() const
Definition ProcessInfo.h:68
void SetProcessID(lldb::pid_t pid)
Definition ProcessInfo.h:70
FileSpec & GetExecutableFile()
Definition ProcessInfo.h:43
uint32_t GetUserID() const
Definition ProcessInfo.h:50
Environment & GetEnvironment()
Definition ProcessInfo.h:88
void SetUserID(uint32_t uid)
Definition ProcessInfo.h:58
ArchSpec & GetArchitecture()
Definition ProcessInfo.h:62
bool Matches(const ProcessInstanceInfo &proc_info) 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
const FileAction * GetFileActionAtIndex(size_t idx) const
const FileAction * GetFileActionForFD(int fd) const
void SetWorkingDirectory(const FileSpec &working_dir)
const FileSpec & GetWorkingDirectory() const
An error handling class.
Definition Status.h:118
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Definition Status.cpp:106
static Status FromErrorString(const char *str)
Definition Status.h:141
bool Fail() const
Test for error condition.
Definition Status.cpp:293
static Status static Status FromErrorStringWithFormatv(const char *format, Args &&...args)
Definition Status.h:151
static Status FromError(llvm::Error error)
Avoid using this in new code. Migrate APIs to llvm::Expected instead.
Definition Status.cpp:136
bool Success() const
Test for success condition.
Definition Status.cpp:303
const char * GetData() const
llvm::StringRef GetString() const
void Format(const char *format, Args &&... args)
Forwards the arguments to llvm::formatv and writes to the stream.
Definition Stream.h:370
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:134
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
Definition Stream.cpp:63
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.
Definition DataBuffer.h:108
#define LLDB_INVALID_CPUTYPE
#define UNUSED_IF_ASSERT_DISABLED(x)
#define UINT32_MAX
#define LLDB_INVALID_PROCESS_ID
lldb::ByteOrder InlHostByteOrder()
Definition Endian.h:25
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:327
bool NameMatches(llvm::StringRef name, NameMatch match_type, llvm::StringRef match)
std::vector< ProcessInstanceInfo > ProcessInstanceInfoList
Definition Host.h:32
Severity
Used for expressing severity in logs and diagnostics.
void * thread_result_t
Definition lldb-types.h:62
ConnectionStatus
Connection Status Types.
@ eConnectionStatusSuccess
Success.
uint64_t offset_t
Definition lldb-types.h:85
@ eErrorTypeGeneric
Generic errors that can be any value.
@ eErrorTypePOSIX
POSIX error codes.
uint64_t pid_t
Definition lldb-types.h:83
#define PATH_MAX