llvm-project/lldb/tools/debugserver/source/MacOSX/MachTask.mm
1//===-- MachTask.cpp --------------------------------------------*- 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//
10// MachTask.cpp
11// debugserver
12//
13// Created by Greg Clayton on 12/5/08.
14//
15//===----------------------------------------------------------------------===//
16
17#include "MachTask.h"
18
19// C Includes
20
21#include <mach-o/dyld_images.h>
22#include <mach/mach_vm.h>
23#import <sys/sysctl.h>
24
25#if defined(__APPLE__)
26#include <pthread.h>
27#include <sched.h>
28#endif
29
30// C++ Includes
31#include <iomanip>
32#include <sstream>
33
34// Other libraries and framework includes
35// Project includes
36#include "CFUtils.h"
37#include "DNB.h"
38#include "DNBDataRef.h"
39#include "DNBError.h"
40#include "DNBLog.h"
41#include "MachProcess.h"
42
43#ifdef WITH_SPRINGBOARD
44
45#include <CoreFoundation/CoreFoundation.h>
46#include <SpringBoardServices/SBSWatchdogAssertion.h>
47#include <SpringBoardServices/SpringBoardServer.h>
48
49#endif
50
51#ifdef WITH_BKS
52extern "C" {
53#import <BackBoardServices/BKSWatchdogAssertion.h>
54#import <BackBoardServices/BackBoardServices.h>
55#import <Foundation/Foundation.h>
56}
57#endif
58
59#include <AvailabilityMacros.h>
60
61#ifdef LLDB_ENERGY
62#include <mach/mach_time.h>
63#include <pmenergy.h>
64#include <pmsample.h>
65#endif
66
67extern "C" int
68proc_get_cpumon_params(pid_t pid, int *percentage,
69 int *interval); // <libproc_internal.h> SPI
70
71//----------------------------------------------------------------------
72// MachTask constructor
73//----------------------------------------------------------------------
74MachTask::MachTask(MachProcess *process)
75 : m_process(process), m_task(TASK_NULL), m_vm_memory(),
76 m_exception_thread(0), m_exception_port(MACH_PORT_NULL),
77 m_exec_will_be_suspended(false), m_do_double_resume(false) {
78 memset(&m_exc_port_info, 0, sizeof(m_exc_port_info));
79}
80
81//----------------------------------------------------------------------
82// Destructor
83//----------------------------------------------------------------------
84MachTask::~MachTask() { Clear(); }
85
86//----------------------------------------------------------------------
87// MachTask::Suspend
88//----------------------------------------------------------------------
89kern_return_t MachTask::Suspend() {
90 DNBError err;
91 task_t task = TaskPort();
92 err = ::task_suspend(task);
93 if (DNBLogCheckLogBit(LOG_TASK) || err.Fail())
94 err.LogThreaded("::task_suspend ( target_task = 0x%4.4x )", task);
95 return err.Status();
96}
97
98//----------------------------------------------------------------------
99// MachTask::Resume
100//----------------------------------------------------------------------
101kern_return_t MachTask::Resume() {
102 struct task_basic_info task_info;
103 task_t task = TaskPort();
104 if (task == TASK_NULL)
105 return KERN_INVALID_ARGUMENT;
106
107 DNBError err;
108 err = BasicInfo(task, &task_info);
109
110 if (err.Success()) {
111 if (m_do_double_resume && task_info.suspend_count == 2) {
112 err = ::task_resume(task);
113 if (DNBLogCheckLogBit(LOG_TASK) || err.Fail())
114 err.LogThreaded("::task_resume double-resume after exec-start-stopped "
115 "( target_task = 0x%4.4x )", task);
116 }
117 m_do_double_resume = false;
118
119 // task_resume isn't counted like task_suspend calls are, are, so if the
120 // task is not suspended, don't try and resume it since it is already
121 // running
122 if (task_info.suspend_count > 0) {
123 err = ::task_resume(task);
124 if (DNBLogCheckLogBit(LOG_TASK) || err.Fail())
125 err.LogThreaded("::task_resume ( target_task = 0x%4.4x )", task);
126 }
127 }
128 return err.Status();
129}
130
131//----------------------------------------------------------------------
132// MachTask::ExceptionPort
133//----------------------------------------------------------------------
134mach_port_t MachTask::ExceptionPort() const { return m_exception_port; }
135
136//----------------------------------------------------------------------
137// MachTask::ExceptionPortIsValid
138//----------------------------------------------------------------------
139bool MachTask::ExceptionPortIsValid() const {
140 return MACH_PORT_VALID(m_exception_port);
141}
142
143//----------------------------------------------------------------------
144// MachTask::Clear
145//----------------------------------------------------------------------
146void MachTask::Clear() {
147 // Do any cleanup needed for this task
148 ShutDownExceptionThread();
149 m_task = TASK_NULL;
150 m_exception_port = MACH_PORT_NULL;
151 m_exec_will_be_suspended = false;
152 m_do_double_resume = false;
153}
154
155//----------------------------------------------------------------------
156// MachTask::SaveExceptionPortInfo
157//----------------------------------------------------------------------
158kern_return_t MachTask::SaveExceptionPortInfo() {
159 return m_exc_port_info.Save(TaskPort());
160}
161
162//----------------------------------------------------------------------
163// MachTask::RestoreExceptionPortInfo
164//----------------------------------------------------------------------
165kern_return_t MachTask::RestoreExceptionPortInfo() {
166 return m_exc_port_info.Restore(TaskPort());
167}
168
169//----------------------------------------------------------------------
170// MachTask::ReadMemory
171//----------------------------------------------------------------------
172nub_size_t MachTask::ReadMemory(nub_addr_t addr, nub_size_t size, void *buf) {
173 nub_size_t n = 0;
174 task_t task = TaskPort();
175 if (task != TASK_NULL) {
176 n = m_vm_memory.Read(task, addr, buf, size);
177
178 DNBLogThreadedIf(LOG_MEMORY, "MachTask::ReadMemory ( addr = 0x%8.8llx, "
179 "size = %llu, buf = %p) => %llu bytes read",
180 (uint64_t)addr, (uint64_t)size, buf, (uint64_t)n);
181 if (DNBLogCheckLogBit(LOG_MEMORY_DATA_LONG) ||
182 (DNBLogCheckLogBit(LOG_MEMORY_DATA_SHORT) && size <= 8)) {
183 DNBDataRef data((uint8_t *)buf, n, false);
184 data.Dump(0, static_cast<DNBDataRef::offset_t>(n), addr,
185 DNBDataRef::TypeUInt8, 16);
186 }
187 }
188 return n;
189}
190
191//----------------------------------------------------------------------
192// MachTask::WriteMemory
193//----------------------------------------------------------------------
194nub_size_t MachTask::WriteMemory(nub_addr_t addr, nub_size_t size,
195 const void *buf) {
196 nub_size_t n = 0;
197 task_t task = TaskPort();
198 if (task != TASK_NULL) {
199 n = m_vm_memory.Write(task, addr, buf, size);
200 DNBLogThreadedIf(LOG_MEMORY, "MachTask::WriteMemory ( addr = 0x%8.8llx, "
201 "size = %llu, buf = %p) => %llu bytes written",
202 (uint64_t)addr, (uint64_t)size, buf, (uint64_t)n);
203 if (DNBLogCheckLogBit(LOG_MEMORY_DATA_LONG) ||
204 (DNBLogCheckLogBit(LOG_MEMORY_DATA_SHORT) && size <= 8)) {
205 DNBDataRef data((const uint8_t *)buf, n, false);
206 data.Dump(0, static_cast<DNBDataRef::offset_t>(n), addr,
207 DNBDataRef::TypeUInt8, 16);
208 }
209 }
210 return n;
211}
212
213//----------------------------------------------------------------------
214// MachTask::GetMemoryRegionInfo
215//----------------------------------------------------------------------
216int MachTask::GetMemoryRegionInfo(nub_addr_t addr, DNBRegionInfo *region_info) {
217 task_t task = TaskPort();
218 if (task == TASK_NULL)
219 return -1;
220
221 int ret = m_vm_memory.GetMemoryRegionInfo(task, addr, region_info);
222 DNBLogThreadedIf(LOG_MEMORY,
223 "MachTask::GetMemoryRegionInfo ( addr = 0x%8.8llx ) => %i "
224 "(start = 0x%8.8llx, size = 0x%8.8llx, permissions = %u)",
225 (uint64_t)addr, ret, (uint64_t)region_info->addr,
226 (uint64_t)region_info->size, region_info->permissions);
227 return ret;
228}
229
230//----------------------------------------------------------------------
231// MachTask::GetMemoryTags
232//----------------------------------------------------------------------
233nub_bool_t MachTask::GetMemoryTags(nub_addr_t addr, nub_size_t size,
234 std::vector<uint8_t> &tags) {
235 task_t task = TaskPort();
236 if (task == TASK_NULL)
237 return false;
238
239 bool ok = m_vm_memory.GetMemoryTags(task, addr, size, tags);
240 DNBLogThreadedIf(LOG_MEMORY, "MachTask::GetMemoryTags ( addr = 0x%8.8llx, "
241 "size = 0x%8.8llx ) => %s ( tag count = %llu)",
242 (uint64_t)addr, (uint64_t)size, (ok ? "ok" : "err"),
243 (uint64_t)tags.size());
244 return ok;
245}
246
247#define TIME_VALUE_TO_TIMEVAL(a, r) \
248 do { \
249 (r)->tv_sec = (a)->seconds; \
250 (r)->tv_usec = (a)->microseconds; \
251 } while (0)
252
253// We should consider moving this into each MacThread.
254static void get_threads_profile_data(DNBProfileDataScanType scanType,
255 task_t task, nub_process_t pid,
256 std::vector<uint64_t> &threads_id,
257 std::vector<std::string> &threads_name,
258 std::vector<uint64_t> &threads_used_usec) {
259 kern_return_t kr;
260 thread_act_array_t threads;
261 mach_msg_type_number_t tcnt;
262
263 kr = task_threads(task, &threads, &tcnt);
264 if (kr != KERN_SUCCESS)
265 return;
266
267 for (mach_msg_type_number_t i = 0; i < tcnt; i++) {
268 thread_identifier_info_data_t identifier_info;
269 mach_msg_type_number_t count = THREAD_IDENTIFIER_INFO_COUNT;
270 kr = ::thread_info(threads[i], THREAD_IDENTIFIER_INFO,
271 (thread_info_t)&identifier_info, &count);
272 if (kr != KERN_SUCCESS)
273 continue;
274
275 thread_basic_info_data_t basic_info;
276 count = THREAD_BASIC_INFO_COUNT;
277 kr = ::thread_info(threads[i], THREAD_BASIC_INFO,
278 (thread_info_t)&basic_info, &count);
279 if (kr != KERN_SUCCESS)
280 continue;
281
282 if ((basic_info.flags & TH_FLAGS_IDLE) == 0) {
283 nub_thread_t tid =
284 MachThread::GetGloballyUniqueThreadIDForMachPortID(threads[i]);
285 threads_id.push_back(tid);
286
287 if ((scanType & eProfileThreadName) &&
288 (identifier_info.thread_handle != 0)) {
289 struct proc_threadinfo proc_threadinfo;
290 int len = ::proc_pidinfo(pid, PROC_PIDTHREADINFO,
291 identifier_info.thread_handle,
292 &proc_threadinfo, PROC_PIDTHREADINFO_SIZE);
293 if (len && proc_threadinfo.pth_name[0]) {
294 threads_name.push_back(proc_threadinfo.pth_name);
295 } else {
296 threads_name.push_back("");
297 }
298 } else {
299 threads_name.push_back("");
300 }
301 struct timeval tv;
302 struct timeval thread_tv;
303 TIME_VALUE_TO_TIMEVAL(&basic_info.user_time, &thread_tv);
304 TIME_VALUE_TO_TIMEVAL(&basic_info.system_time, &tv);
305 timeradd(&thread_tv, &tv, &thread_tv);
306 uint64_t used_usec = thread_tv.tv_sec * 1000000ULL + thread_tv.tv_usec;
307 threads_used_usec.push_back(used_usec);
308 }
309
310 mach_port_deallocate(mach_task_self(), threads[i]);
311 }
312 mach_vm_deallocate(mach_task_self(), (mach_vm_address_t)(uintptr_t)threads,
313 tcnt * sizeof(*threads));
314}
315
316#define RAW_HEXBASE std::setfill('0') << std::hex << std::right
317#define DECIMAL std::dec << std::setfill(' ')
318std::string MachTask::GetProfileData(DNBProfileDataScanType scanType) {
319 std::string result;
320
321 static int32_t numCPU = -1;
322 struct host_cpu_load_info host_info;
323 if (scanType & eProfileHostCPU) {
324 int32_t mib[] = {CTL_HW, HW_AVAILCPU};
325 size_t len = sizeof(numCPU);
326 if (numCPU == -1) {
327 if (sysctl(mib, sizeof(mib) / sizeof(int32_t), &numCPU, &len, NULL, 0) !=
328 0)
329 return result;
330 }
331
332 mach_port_t localHost = mach_host_self();
333 mach_msg_type_number_t count = HOST_CPU_LOAD_INFO_COUNT;
334 kern_return_t kr = host_statistics(localHost, HOST_CPU_LOAD_INFO,
335 (host_info_t)&host_info, &count);
336 if (kr != KERN_SUCCESS)
337 return result;
338 }
339
340 task_t task = TaskPort();
341 if (task == TASK_NULL)
342 return result;
343
344 pid_t pid = m_process->ProcessID();
345
346 struct task_basic_info task_info;
347 DNBError err;
348 err = BasicInfo(task, &task_info);
349
350 if (!err.Success())
351 return result;
352
353 uint64_t elapsed_usec = 0;
354 uint64_t task_used_usec = 0;
355 if (scanType & eProfileCPU) {
356 // Get current used time.
357 struct timeval current_used_time;
358 struct timeval tv;
359 TIME_VALUE_TO_TIMEVAL(&task_info.user_time, ¤t_used_time);
360 TIME_VALUE_TO_TIMEVAL(&task_info.system_time, &tv);
361 timeradd(¤t_used_time, &tv, ¤t_used_time);
362 task_used_usec =
363 current_used_time.tv_sec * 1000000ULL + current_used_time.tv_usec;
364
365 struct timeval current_elapsed_time;
366 int res = gettimeofday(¤t_elapsed_time, NULL);
367 if (res == 0) {
368 elapsed_usec = current_elapsed_time.tv_sec * 1000000ULL +
369 current_elapsed_time.tv_usec;
370 }
371 }
372
373 std::vector<uint64_t> threads_id;
374 std::vector<std::string> threads_name;
375 std::vector<uint64_t> threads_used_usec;
376
377 if (scanType & eProfileThreadsCPU) {
378 get_threads_profile_data(scanType, task, pid, threads_id, threads_name,
379 threads_used_usec);
380 }
381
382 vm_statistics64_data_t vminfo;
383 uint64_t physical_memory = 0;
384 uint64_t anonymous = 0;
385 uint64_t phys_footprint = 0;
386 uint64_t memory_cap = 0;
387 if (m_vm_memory.GetMemoryProfile(scanType, task, task_info,
388 m_process->GetCPUType(), pid, vminfo,
389 physical_memory, anonymous,
390 phys_footprint, memory_cap)) {
391 std::ostringstream profile_data_stream;
392
393 if (scanType & eProfileHostCPU) {
394 profile_data_stream << "num_cpu:" << numCPU << ';';
395 profile_data_stream << "host_user_ticks:"
396 << host_info.cpu_ticks[CPU_STATE_USER] << ';';
397 profile_data_stream << "host_sys_ticks:"
398 << host_info.cpu_ticks[CPU_STATE_SYSTEM] << ';';
399 profile_data_stream << "host_idle_ticks:"
400 << host_info.cpu_ticks[CPU_STATE_IDLE] << ';';
401 }
402
403 if (scanType & eProfileCPU) {
404 profile_data_stream << "elapsed_usec:" << elapsed_usec << ';';
405 profile_data_stream << "task_used_usec:" << task_used_usec << ';';
406 }
407
408 if (scanType & eProfileThreadsCPU) {
409 const size_t num_threads = threads_id.size();
410 for (size_t i = 0; i < num_threads; i++) {
411 profile_data_stream << "thread_used_id:" << std::hex << threads_id[i]
412 << std::dec << ';';
413 profile_data_stream << "thread_used_usec:" << threads_used_usec[i]
414 << ';';
415
416 if (scanType & eProfileThreadName) {
417 profile_data_stream << "thread_used_name:";
418 const size_t len = threads_name[i].size();
419 if (len) {
420 const char *thread_name = threads_name[i].c_str();
421 // Make sure that thread name doesn't interfere with our delimiter.
422 profile_data_stream << RAW_HEXBASE << std::setw(2);
423 const uint8_t *ubuf8 = (const uint8_t *)(thread_name);
424 for (size_t j = 0; j < len; j++) {
425 profile_data_stream << (uint32_t)(ubuf8[j]);
426 }
427 // Reset back to DECIMAL.
428 profile_data_stream << DECIMAL;
429 }
430 profile_data_stream << ';';
431 }
432 }
433 }
434
435 if (scanType & eProfileHostMemory)
436 profile_data_stream << "total:" << physical_memory << ';';
437
438 if (scanType & eProfileMemory) {
439 static vm_size_t pagesize = vm_kernel_page_size;
440
441 // This mimicks Activity Monitor.
442 uint64_t total_used_count =
443 (physical_memory / pagesize) -
444 (vminfo.free_count - vminfo.speculative_count) -
445 vminfo.external_page_count - vminfo.purgeable_count;
446 profile_data_stream << "used:" << total_used_count * pagesize << ';';
447
448 if (scanType & eProfileMemoryAnonymous) {
449 profile_data_stream << "anonymous:" << anonymous << ';';
450 }
451
452 profile_data_stream << "phys_footprint:" << phys_footprint << ';';
453 }
454
455 if (scanType & eProfileMemoryCap) {
456 profile_data_stream << "mem_cap:" << memory_cap << ';';
457 }
458
459#ifdef LLDB_ENERGY
460 if (scanType & eProfileEnergy) {
461 struct rusage_info_v2 info;
462 int rc = proc_pid_rusage(pid, RUSAGE_INFO_V2, (rusage_info_t *)&info);
463 if (rc == 0) {
464 uint64_t now = mach_absolute_time();
465 pm_task_energy_data_t pm_energy;
466 memset(&pm_energy, 0, sizeof(pm_energy));
467 /*
468 * Disable most features of pm_sample_pid. It will gather
469 * network/GPU/WindowServer information; fill in the rest.
470 */
471 pm_sample_task_and_pid(task, pid, &pm_energy, now,
472 PM_SAMPLE_ALL & ~PM_SAMPLE_NAME &
473 ~PM_SAMPLE_INTERVAL & ~PM_SAMPLE_CPU &
474 ~PM_SAMPLE_DISK);
475 pm_energy.sti.total_user = info.ri_user_time;
476 pm_energy.sti.total_system = info.ri_system_time;
477 pm_energy.sti.task_interrupt_wakeups = info.ri_interrupt_wkups;
478 pm_energy.sti.task_platform_idle_wakeups = info.ri_pkg_idle_wkups;
479 pm_energy.diskio_bytesread = info.ri_diskio_bytesread;
480 pm_energy.diskio_byteswritten = info.ri_diskio_byteswritten;
481 pm_energy.pageins = info.ri_pageins;
482
483 uint64_t total_energy =
484 (uint64_t)(pm_energy_impact(&pm_energy) * NSEC_PER_SEC);
485 // uint64_t process_age = now - info.ri_proc_start_abstime;
486 // uint64_t avg_energy = 100.0 * (double)total_energy /
487 // (double)process_age;
488
489 profile_data_stream << "energy:" << total_energy << ';';
490 }
491 }
492#endif
493
494 if (scanType & eProfileEnergyCPUCap) {
495 int percentage = -1;
496 int interval = -1;
497 int result = proc_get_cpumon_params(pid, &percentage, &interval);
498 if ((result == 0) && (percentage >= 0) && (interval >= 0)) {
499 profile_data_stream << "cpu_cap_p:" << percentage << ';';
500 profile_data_stream << "cpu_cap_t:" << interval << ';';
501 }
502 }
503
504 profile_data_stream << "--end--;";
505
506 result = profile_data_stream.str();
507 }
508
509 return result;
510}
511
512//----------------------------------------------------------------------
513// MachTask::TaskPortForProcessID
514//----------------------------------------------------------------------
515task_t MachTask::TaskPortForProcessID(DNBError &err, bool force) {
516 if (((m_task == TASK_NULL) || force) && m_process != NULL)
517 m_task = MachTask::TaskPortForProcessID(m_process->ProcessID(), err);
518 return m_task;
519}
520
521//----------------------------------------------------------------------
522// MachTask::TaskPortForProcessID
523//----------------------------------------------------------------------
524task_t MachTask::TaskPortForProcessID(pid_t pid, DNBError &err) {
525 static constexpr uint32_t k_num_retries = 10;
526 static constexpr uint32_t k_usec_delay = 10000;
527
528 if (pid != INVALID_NUB_PROCESS) {
529 DNBError err;
530 mach_port_t task_self = mach_task_self();
531 task_t task = TASK_NULL;
532 uint32_t interval = k_usec_delay;
533
534 for (uint32_t i = 0; i < k_num_retries; i++) {
535 DNBLog("[LaunchAttach] (%d) about to task_for_pid(%d)", getpid(), pid);
536 err = ::task_for_pid(task_self, pid, &task);
537
538 if (DNBLogCheckLogBit(LOG_TASK) || err.Fail()) {
539 char str[1024];
540 ::snprintf(str, sizeof(str), "::task_for_pid ( target_tport = 0x%4.4x, "
541 "pid = %d, &task ) => err = 0x%8.8x (%s)",
542 task_self, pid, err.Status(),
543 err.AsString() ? err.AsString() : "success");
544 if (err.Fail()) {
545 err.SetErrorString(str);
546 DNBLogError(
547 "[LaunchAttach] MachTask::TaskPortForProcessID task_for_pid(%d) "
548 "failed: %s",
549 pid, str);
550 }
551 err.LogThreaded(str);
552 }
553
554 if (err.Success()) {
555 DNBLog("[LaunchAttach] (%d) successfully task_for_pid(%d)'ed", getpid(),
556 pid);
557 return task;
558 }
559
560 // Sleep a bit and try again
561 // Use an increasing interval so that if there's a short term traffic
562 // jam, we skip past rather than exacerbating it. We see this sequence
563 // timing out occasionally on heavily loaded bots, seemingly because the
564 // syspolicyd isn't keeping up.
565 interval += k_usec_delay * i;
566 ::usleep(interval);
567 }
568 }
569 return TASK_NULL;
570}
571
572//----------------------------------------------------------------------
573// MachTask::BasicInfo
574//----------------------------------------------------------------------
575kern_return_t MachTask::BasicInfo(struct task_basic_info *info) {
576 return BasicInfo(TaskPort(), info);
577}
578
579//----------------------------------------------------------------------
580// MachTask::BasicInfo
581//----------------------------------------------------------------------
582kern_return_t MachTask::BasicInfo(task_t task, struct task_basic_info *info) {
583 if (info == NULL)
584 return KERN_INVALID_ARGUMENT;
585
586 DNBError err;
587 mach_msg_type_number_t count = TASK_BASIC_INFO_COUNT;
588 err = ::task_info(task, TASK_BASIC_INFO, (task_info_t)info, &count);
589 const bool log_process = DNBLogCheckLogBit(LOG_TASK);
590 if (log_process || err.Fail())
591 err.LogThreaded("::task_info ( target_task = 0x%4.4x, flavor = "
592 "TASK_BASIC_INFO, task_info_out => %p, task_info_outCnt => "
593 "%u )",
594 task, info, count);
595 if (DNBLogCheckLogBit(LOG_TASK) && DNBLogCheckLogBit(LOG_VERBOSE) &&
596 err.Success()) {
597 float user = (float)info->user_time.seconds +
598 (float)info->user_time.microseconds / 1000000.0f;
599 float system = (float)info->user_time.seconds +
600 (float)info->user_time.microseconds / 1000000.0f;
601 DNBLogThreaded("task_basic_info = { suspend_count = %i, virtual_size = "
602 "0x%8.8llx, resident_size = 0x%8.8llx, user_time = %f, "
603 "system_time = %f }",
604 info->suspend_count, (uint64_t)info->virtual_size,
605 (uint64_t)info->resident_size, user, system);
606 }
607 return err.Status();
608}
609
610//----------------------------------------------------------------------
611// MachTask::IsValid
612//
613// Returns true if a task is a valid task port for a current process.
614//----------------------------------------------------------------------
615bool MachTask::IsValid() const { return MachTask::IsValid(TaskPort()); }
616
617//----------------------------------------------------------------------
618// MachTask::IsValid
619//
620// Returns true if a task is a valid task port for a current process.
621//----------------------------------------------------------------------
622bool MachTask::IsValid(task_t task) {
623 if (task != TASK_NULL) {
624 struct task_basic_info task_info;
625 return BasicInfo(task, &task_info) == KERN_SUCCESS;
626 }
627 return false;
628}
629
630bool MachTask::StartExceptionThread(
631 const RNBContext::IgnoredExceptions &ignored_exceptions,
632 DNBError &err) {
633 DNBLogThreadedIf(LOG_EXCEPTIONS, "MachTask::%s ( )", __FUNCTION__);
634
635 task_t task = TaskPortForProcessID(err);
636 if (MachTask::IsValid(task)) {
637 // Got the mach port for the current process
638 mach_port_t task_self = mach_task_self();
639
640 // Allocate an exception port that we will use to track our child process
641 err = ::mach_port_allocate(task_self, MACH_PORT_RIGHT_RECEIVE,
642 &m_exception_port);
643 if (err.Fail())
644 return false;
645
646 // Add the ability to send messages on the new exception port
647 err = ::mach_port_insert_right(task_self, m_exception_port,
648 m_exception_port, MACH_MSG_TYPE_MAKE_SEND);
649 if (err.Fail())
650 return false;
651
652 // Save the original state of the exception ports for our child process
653 SaveExceptionPortInfo();
654
655 // We weren't able to save the info for our exception ports, we must stop...
656 if (m_exc_port_info.mask == 0) {
657 err.SetErrorString("failed to get exception port info");
658 return false;
659 }
660
661 if (!ignored_exceptions.empty()) {
662 for (exception_mask_t mask : ignored_exceptions)
663 m_exc_port_info.mask = m_exc_port_info.mask & ~mask;
664 }
665
666 // Set the ability to get all exceptions on this port
667 err = ::task_set_exception_ports(
668 task, m_exc_port_info.mask, m_exception_port,
669 EXCEPTION_DEFAULT | MACH_EXCEPTION_CODES, THREAD_STATE_NONE);
670 if (DNBLogCheckLogBit(LOG_EXCEPTIONS) || err.Fail()) {
671 err.LogThreaded("::task_set_exception_ports ( task = 0x%4.4x, "
672 "exception_mask = 0x%8.8x, new_port = 0x%4.4x, behavior "
673 "= 0x%8.8x, new_flavor = 0x%8.8x )",
674 task, m_exc_port_info.mask, m_exception_port,
675 (EXCEPTION_DEFAULT | MACH_EXCEPTION_CODES),
676 THREAD_STATE_NONE);
677 }
678
679 if (err.Fail())
680 return false;
681
682 // Create the exception thread
683 err = ::pthread_create(&m_exception_thread, NULL, MachTask::ExceptionThread,
684 this);
685 return err.Success();
686 } else {
687 DNBLogError("MachTask::%s (): task invalid, exception thread start failed.",
688 __FUNCTION__);
689 }
690 return false;
691}
692
693void MachTask::ShutDownExceptionThread() {
694 DNBError err;
695
696 if (!m_exception_thread)
697 return;
698
699 err = RestoreExceptionPortInfo();
700
701 // NULL our exception port and let our exception thread exit
702 mach_port_t exception_port = m_exception_port;
703 m_exception_port = 0;
704
705 err.SetError(::pthread_cancel(m_exception_thread), DNBError::POSIX);
706 if (DNBLogCheckLogBit(LOG_TASK) || err.Fail())
707 err.LogThreaded("::pthread_cancel ( thread = %p )", m_exception_thread);
708
709 err.SetError(::pthread_join(m_exception_thread, NULL), DNBError::POSIX);
710 if (DNBLogCheckLogBit(LOG_TASK) || err.Fail())
711 err.LogThreaded("::pthread_join ( thread = %p, value_ptr = NULL)",
712 m_exception_thread);
713
714 m_exception_thread = nullptr;
715
716 // Deallocate our exception port that we used to track our child process
717 mach_port_t task_self = mach_task_self();
718 err = ::mach_port_deallocate(task_self, exception_port);
719 if (DNBLogCheckLogBit(LOG_TASK) || err.Fail())
720 err.LogThreaded("::mach_port_deallocate ( task = 0x%4.4x, name = 0x%4.4x )",
721 task_self, exception_port);
722
723 m_exec_will_be_suspended = false;
724 m_do_double_resume = false;
725
726 return;
727}
728
729void *MachTask::ExceptionThread(void *arg) {
730 if (arg == NULL)
731 return NULL;
732
733 MachTask *mach_task = (MachTask *)arg;
734 MachProcess *mach_proc = mach_task->Process();
735 DNBLogThreadedIf(LOG_EXCEPTIONS,
736 "MachTask::%s ( arg = %p ) starting thread...", __FUNCTION__,
737 arg);
738
739#if defined(__APPLE__)
740 pthread_setname_np("exception monitoring thread");
741#if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
742 struct sched_param thread_param;
743 int thread_sched_policy;
744 if (pthread_getschedparam(pthread_self(), &thread_sched_policy,
745 &thread_param) == 0) {
746 thread_param.sched_priority = 47;
747 pthread_setschedparam(pthread_self(), thread_sched_policy, &thread_param);
748 }
749#endif
750#endif
751
752 // We keep a count of the number of consecutive exceptions received so
753 // we know to grab all exceptions without a timeout. We do this to get a
754 // bunch of related exceptions on our exception port so we can process
755 // then together. When we have multiple threads, we can get an exception
756 // per thread and they will come in consecutively. The main loop in this
757 // thread can stop periodically if needed to service things related to this
758 // process.
759 // flag set in the options, so we will wait forever for an exception on
760 // our exception port. After we get one exception, we then will use the
761 // MACH_RCV_TIMEOUT option with a zero timeout to grab all other current
762 // exceptions for our process. After we have received the last pending
763 // exception, we will get a timeout which enables us to then notify
764 // our main thread that we have an exception bundle available. We then wait
765 // for the main thread to tell this exception thread to start trying to get
766 // exceptions messages again and we start again with a mach_msg read with
767 // infinite timeout.
768 uint32_t num_exceptions_received = 0;
769 DNBError err;
770 task_t task = mach_task->TaskPort();
771 mach_msg_timeout_t periodic_timeout = 0;
772
773#if defined(WITH_SPRINGBOARD) && !defined(WITH_BKS)
774 mach_msg_timeout_t watchdog_elapsed = 0;
775 mach_msg_timeout_t watchdog_timeout = 60 * 1000;
776 pid_t pid = mach_proc->ProcessID();
777 CFReleaser<SBSWatchdogAssertionRef> watchdog;
778
779 if (mach_proc->ProcessUsingSpringBoard()) {
780 // Request a renewal for every 60 seconds if we attached using SpringBoard
781 watchdog.reset(::SBSWatchdogAssertionCreateForPID(NULL, pid, 60));
782 DNBLogThreadedIf(
783 LOG_TASK, "::SBSWatchdogAssertionCreateForPID (NULL, %4.4x, 60 ) => %p",
784 pid, watchdog.get());
785
786 if (watchdog.get()) {
787 ::SBSWatchdogAssertionRenew(watchdog.get());
788
789 CFTimeInterval watchdogRenewalInterval =
790 ::SBSWatchdogAssertionGetRenewalInterval(watchdog.get());
791 DNBLogThreadedIf(
792 LOG_TASK,
793 "::SBSWatchdogAssertionGetRenewalInterval ( %p ) => %g seconds",
794 watchdog.get(), watchdogRenewalInterval);
795 if (watchdogRenewalInterval > 0.0) {
796 watchdog_timeout = (mach_msg_timeout_t)watchdogRenewalInterval * 1000;
797 if (watchdog_timeout > 3000)
798 watchdog_timeout -= 1000; // Give us a second to renew our timeout
799 else if (watchdog_timeout > 1000)
800 watchdog_timeout -=
801 250; // Give us a quarter of a second to renew our timeout
802 }
803 }
804 if (periodic_timeout == 0 || periodic_timeout > watchdog_timeout)
805 periodic_timeout = watchdog_timeout;
806 }
807#endif // #if defined (WITH_SPRINGBOARD) && !defined (WITH_BKS)
808
809#ifdef WITH_BKS
810 CFReleaser<BKSWatchdogAssertionRef> watchdog;
811 if (mach_proc->ProcessUsingBackBoard()) {
812 pid_t pid = mach_proc->ProcessID();
813 CFAllocatorRef alloc = kCFAllocatorDefault;
814 watchdog.reset(::BKSWatchdogAssertionCreateForPID(alloc, pid));
815 }
816#endif // #ifdef WITH_BKS
817
818 while (mach_task->ExceptionPortIsValid()) {
819 ::pthread_testcancel();
820
821 MachException::Message exception_message;
822
823 if (num_exceptions_received > 0) {
824 // No timeout, just receive as many exceptions as we can since we already
825 // have one and we want
826 // to get all currently available exceptions for this task
827 err = exception_message.Receive(
828 mach_task->ExceptionPort(),
829 MACH_RCV_MSG | MACH_RCV_INTERRUPT | MACH_RCV_TIMEOUT, 1);
830 } else if (periodic_timeout > 0) {
831 // We need to stop periodically in this loop, so try and get a mach
832 // message with a valid timeout (ms)
833 err = exception_message.Receive(mach_task->ExceptionPort(),
834 MACH_RCV_MSG | MACH_RCV_INTERRUPT |
835 MACH_RCV_TIMEOUT,
836 periodic_timeout);
837 } else {
838 // We don't need to parse all current exceptions or stop periodically,
839 // just wait for an exception forever.
840 err = exception_message.Receive(mach_task->ExceptionPort(),
841 MACH_RCV_MSG | MACH_RCV_INTERRUPT, 0);
842 }
843
844 if (err.Status() == MACH_RCV_INTERRUPTED) {
845 // If we have no task port we should exit this thread
846 if (!mach_task->ExceptionPortIsValid()) {
847 DNBLogThreadedIf(LOG_EXCEPTIONS, "thread cancelled...");
848 break;
849 }
850
851 // Make sure our task is still valid
852 if (MachTask::IsValid(task)) {
853 // Task is still ok
854 DNBLogThreadedIf(LOG_EXCEPTIONS,
855 "interrupted, but task still valid, continuing...");
856 continue;
857 } else {
858 DNBLogThreadedIf(LOG_EXCEPTIONS, "task has exited...");
859 mach_proc->SetState(eStateExited);
860 // Our task has died, exit the thread.
861 break;
862 }
863 } else if (err.Status() == MACH_RCV_TIMED_OUT) {
864 if (num_exceptions_received > 0) {
865 // We were receiving all current exceptions with a timeout of zero
866 // it is time to go back to our normal looping mode
867 num_exceptions_received = 0;
868
869 // Notify our main thread we have a complete exception message
870 // bundle available and get the possibly updated task port back
871 // from the process in case we exec'ed and our task port changed
872 task = mach_proc->ExceptionMessageBundleComplete();
873
874 // in case we use a timeout value when getting exceptions...
875 // Make sure our task is still valid
876 if (MachTask::IsValid(task)) {
877 // Task is still ok
878 DNBLogThreadedIf(LOG_EXCEPTIONS, "got a timeout, continuing...");
879 continue;
880 } else {
881 DNBLogThreadedIf(LOG_EXCEPTIONS, "task has exited...");
882 mach_proc->SetState(eStateExited);
883 // Our task has died, exit the thread.
884 break;
885 }
886 }
887
888#if defined(WITH_SPRINGBOARD) && !defined(WITH_BKS)
889 if (watchdog.get()) {
890 watchdog_elapsed += periodic_timeout;
891 if (watchdog_elapsed >= watchdog_timeout) {
892 DNBLogThreadedIf(LOG_TASK, "SBSWatchdogAssertionRenew ( %p )",
893 watchdog.get());
894 ::SBSWatchdogAssertionRenew(watchdog.get());
895 watchdog_elapsed = 0;
896 }
897 }
898#endif
899 } else if (err.Status() != KERN_SUCCESS) {
900 DNBLogThreadedIf(LOG_EXCEPTIONS, "got some other error, do something "
901 "about it??? nah, continuing for "
902 "now...");
903 // TODO: notify of error?
904 } else {
905 if (exception_message.CatchExceptionRaise(task)) {
906 if (exception_message.state.task_port != task) {
907 if (exception_message.state.IsValid()) {
908 pid_t new_pid = -1;
909 kern_return_t kr =
910 pid_for_task(exception_message.state.task_port, &new_pid);
911 pid_t old_pid = mach_proc->ProcessID();
912 if (kr == KERN_SUCCESS && old_pid != new_pid) {
913 DNBLogError("Got an exec mach message but the pid of "
914 "the new task and the pid of the old task "
915 "do not match, something is wrong.");
916 // exit the thread.
917 break;
918 }
919 // We exec'ed and our task port changed on us.
920 DNBLogThreadedIf(LOG_EXCEPTIONS,
921 "task port changed from 0x%4.4x to 0x%4.4x",
922 task, exception_message.state.task_port);
923 task = exception_message.state.task_port;
924 mach_task->TaskPortChanged(exception_message.state.task_port);
925 }
926 }
927 ++num_exceptions_received;
928 mach_proc->ExceptionMessageReceived(exception_message);
929 }
930 }
931 }
932
933#if defined(WITH_SPRINGBOARD) && !defined(WITH_BKS)
934 if (watchdog.get()) {
935 // TODO: change SBSWatchdogAssertionRelease to SBSWatchdogAssertionCancel
936 // when we
937 // all are up and running on systems that support it. The SBS framework has
938 // a #define
939 // that will forward SBSWatchdogAssertionRelease to
940 // SBSWatchdogAssertionCancel for now
941 // so it should still build either way.
942 DNBLogThreadedIf(LOG_TASK, "::SBSWatchdogAssertionRelease(%p)",
943 watchdog.get());
944 ::SBSWatchdogAssertionRelease(watchdog.get());
945 }
946#endif // #if defined (WITH_SPRINGBOARD) && !defined (WITH_BKS)
947
948 DNBLogThreadedIf(LOG_EXCEPTIONS, "MachTask::%s (%p): thread exiting...",
949 __FUNCTION__, arg);
950 return NULL;
951}
952
953// So the TASK_DYLD_INFO used to just return the address of the all image infos
954// as a single member called "all_image_info". Then someone decided it would be
955// a good idea to rename this first member to "all_image_info_addr" and add a
956// size member called "all_image_info_size". This of course can not be detected
957// using code or #defines. So to hack around this problem, we define our own
958// version of the TASK_DYLD_INFO structure so we can guarantee what is inside
959// it.
960
961struct hack_task_dyld_info {
962 mach_vm_address_t all_image_info_addr;
963 mach_vm_size_t all_image_info_size;
964};
965
966nub_addr_t MachTask::GetDYLDAllImageInfosAddress(DNBError &err) {
967 struct hack_task_dyld_info dyld_info;
968 mach_msg_type_number_t count = TASK_DYLD_INFO_COUNT;
969 // Make sure that COUNT isn't bigger than our hacked up struct
970 // hack_task_dyld_info.
971 // If it is, then make COUNT smaller to match.
972 if (count > (sizeof(struct hack_task_dyld_info) / sizeof(natural_t)))
973 count = (sizeof(struct hack_task_dyld_info) / sizeof(natural_t));
974
975 task_t task = TaskPortForProcessID(err);
976 if (err.Success()) {
977 err = ::task_info(task, TASK_DYLD_INFO, (task_info_t)&dyld_info, &count);
978 if (err.Success()) {
979 // We now have the address of the all image infos structure
980 return dyld_info.all_image_info_addr;
981 }
982 }
983 return INVALID_NUB_ADDRESS;
984}
985
986//----------------------------------------------------------------------
987// MachTask::AllocateMemory
988//----------------------------------------------------------------------
989nub_addr_t MachTask::AllocateMemory(size_t size, uint32_t permissions) {
990 mach_vm_address_t addr;
991 task_t task = TaskPort();
992 if (task == TASK_NULL)
993 return INVALID_NUB_ADDRESS;
994
995 DNBError err;
996 err = ::mach_vm_allocate(task, &addr, size, TRUE);
997 if (err.Status() == KERN_SUCCESS) {
998 // Set the protections:
999 vm_prot_t mach_prot = VM_PROT_NONE;
1000 if (permissions & eMemoryPermissionsReadable)
1001 mach_prot |= VM_PROT_READ;
1002 if (permissions & eMemoryPermissionsWritable)
1003 mach_prot |= VM_PROT_WRITE;
1004 if (permissions & eMemoryPermissionsExecutable)
1005 mach_prot |= VM_PROT_EXECUTE;
1006
1007 err = ::mach_vm_protect(task, addr, size, 0, mach_prot);
1008 if (err.Status() == KERN_SUCCESS) {
1009 m_allocations.insert(std::make_pair(addr, size));
1010 return addr;
1011 }
1012 ::mach_vm_deallocate(task, addr, size);
1013 }
1014 return INVALID_NUB_ADDRESS;
1015}
1016
1017//----------------------------------------------------------------------
1018// MachTask::DeallocateMemory
1019//----------------------------------------------------------------------
1020nub_bool_t MachTask::DeallocateMemory(nub_addr_t addr) {
1021 task_t task = TaskPort();
1022 if (task == TASK_NULL)
1023 return false;
1024
1025 // We have to stash away sizes for the allocations...
1026 allocation_collection::iterator pos, end = m_allocations.end();
1027 for (pos = m_allocations.begin(); pos != end; pos++) {
1028 if ((*pos).first == addr) {
1029 size_t size = (*pos).second;
1030 m_allocations.erase(pos);
1031#define ALWAYS_ZOMBIE_ALLOCATIONS 0
1032 if (ALWAYS_ZOMBIE_ALLOCATIONS ||
1033 getenv("DEBUGSERVER_ZOMBIE_ALLOCATIONS")) {
1034 ::mach_vm_protect(task, addr, size, 0, VM_PROT_NONE);
1035 return true;
1036 } else
1037 return ::mach_vm_deallocate(task, addr, size) == KERN_SUCCESS;
1038 }
1039 }
1040 return false;
1041}
1042
1043//----------------------------------------------------------------------
1044// MachTask::ClearAllocations
1045//----------------------------------------------------------------------
1046void MachTask::ClearAllocations() {
1047 m_allocations.clear();
1048}
1049
1050void MachTask::TaskPortChanged(task_t task)
1051{
1052 m_task = task;
1053
1054 // If we've just exec'd to a new process, and it
1055 // is started suspended, we'll need to do two
1056 // task_resume's to get the inferior process to
1057 // continue.
1058 if (m_exec_will_be_suspended)
1059 m_do_double_resume = true;
1060 else
1061 m_do_double_resume = false;
1062 m_exec_will_be_suspended = false;
1063}