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  m_task = TASK_NULL;
149  m_exception_thread = 0;
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::MemoryRegionInfo
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, "MachTask::MemoryRegionInfo ( addr = 0x%8.8llx "
223                               ") => %i  (start = 0x%8.8llx, size = 0x%8.8llx, "
224                               "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#define TIME_VALUE_TO_TIMEVAL(a, r)                                            \
231  do {                                                                         \
232    (r)->tv_sec = (a)->seconds;                                                \
233    (r)->tv_usec = (a)->microseconds;                                          \
234  } while (0)
235
236// We should consider moving this into each MacThread.
237static void get_threads_profile_data(DNBProfileDataScanType scanType,
238                                     task_t task, nub_process_t pid,
239                                     std::vector<uint64_t> &threads_id,
240                                     std::vector<std::string> &threads_name,
241                                     std::vector<uint64_t> &threads_used_usec) {
242  kern_return_t kr;
243  thread_act_array_t threads;
244  mach_msg_type_number_t tcnt;
245
246  kr = task_threads(task, &threads, &tcnt);
247  if (kr != KERN_SUCCESS)
248    return;
249
250  for (mach_msg_type_number_t i = 0; i < tcnt; i++) {
251    thread_identifier_info_data_t identifier_info;
252    mach_msg_type_number_t count = THREAD_IDENTIFIER_INFO_COUNT;
253    kr = ::thread_info(threads[i], THREAD_IDENTIFIER_INFO,
254                       (thread_info_t)&identifier_info, &count);
255    if (kr != KERN_SUCCESS)
256      continue;
257
258    thread_basic_info_data_t basic_info;
259    count = THREAD_BASIC_INFO_COUNT;
260    kr = ::thread_info(threads[i], THREAD_BASIC_INFO,
261                       (thread_info_t)&basic_info, &count);
262    if (kr != KERN_SUCCESS)
263      continue;
264
265    if ((basic_info.flags & TH_FLAGS_IDLE) == 0) {
266      nub_thread_t tid =
267          MachThread::GetGloballyUniqueThreadIDForMachPortID(threads[i]);
268      threads_id.push_back(tid);
269
270      if ((scanType & eProfileThreadName) &&
271          (identifier_info.thread_handle != 0)) {
272        struct proc_threadinfo proc_threadinfo;
273        int len = ::proc_pidinfo(pid, PROC_PIDTHREADINFO,
274                                 identifier_info.thread_handle,
275                                 &proc_threadinfo, PROC_PIDTHREADINFO_SIZE);
276        if (len && proc_threadinfo.pth_name[0]) {
277          threads_name.push_back(proc_threadinfo.pth_name);
278        } else {
279          threads_name.push_back("");
280        }
281      } else {
282        threads_name.push_back("");
283      }
284      struct timeval tv;
285      struct timeval thread_tv;
286      TIME_VALUE_TO_TIMEVAL(&basic_info.user_time, &thread_tv);
287      TIME_VALUE_TO_TIMEVAL(&basic_info.system_time, &tv);
288      timeradd(&thread_tv, &tv, &thread_tv);
289      uint64_t used_usec = thread_tv.tv_sec * 1000000ULL + thread_tv.tv_usec;
290      threads_used_usec.push_back(used_usec);
291    }
292
293    mach_port_deallocate(mach_task_self(), threads[i]);
294  }
295  mach_vm_deallocate(mach_task_self(), (mach_vm_address_t)(uintptr_t)threads,
296                     tcnt * sizeof(*threads));
297}
298
299#define RAW_HEXBASE std::setfill('0') << std::hex << std::right
300#define DECIMAL std::dec << std::setfill(' ')
301std::string MachTask::GetProfileData(DNBProfileDataScanType scanType) {
302  std::string result;
303
304  static int32_t numCPU = -1;
305  struct host_cpu_load_info host_info;
306  if (scanType & eProfileHostCPU) {
307    int32_t mib[] = {CTL_HW, HW_AVAILCPU};
308    size_t len = sizeof(numCPU);
309    if (numCPU == -1) {
310      if (sysctl(mib, sizeof(mib) / sizeof(int32_t), &numCPU, &len, NULL, 0) !=
311          0)
312        return result;
313    }
314
315    mach_port_t localHost = mach_host_self();
316    mach_msg_type_number_t count = HOST_CPU_LOAD_INFO_COUNT;
317    kern_return_t kr = host_statistics(localHost, HOST_CPU_LOAD_INFO,
318                                       (host_info_t)&host_info, &count);
319    if (kr != KERN_SUCCESS)
320      return result;
321  }
322
323  task_t task = TaskPort();
324  if (task == TASK_NULL)
325    return result;
326
327  pid_t pid = m_process->ProcessID();
328
329  struct task_basic_info task_info;
330  DNBError err;
331  err = BasicInfo(task, &task_info);
332
333  if (!err.Success())
334    return result;
335
336  uint64_t elapsed_usec = 0;
337  uint64_t task_used_usec = 0;
338  if (scanType & eProfileCPU) {
339    // Get current used time.
340    struct timeval current_used_time;
341    struct timeval tv;
342    TIME_VALUE_TO_TIMEVAL(&task_info.user_time, &current_used_time);
343    TIME_VALUE_TO_TIMEVAL(&task_info.system_time, &tv);
344    timeradd(&current_used_time, &tv, &current_used_time);
345    task_used_usec =
346        current_used_time.tv_sec * 1000000ULL + current_used_time.tv_usec;
347
348    struct timeval current_elapsed_time;
349    int res = gettimeofday(&current_elapsed_time, NULL);
350    if (res == 0) {
351      elapsed_usec = current_elapsed_time.tv_sec * 1000000ULL +
352                     current_elapsed_time.tv_usec;
353    }
354  }
355
356  std::vector<uint64_t> threads_id;
357  std::vector<std::string> threads_name;
358  std::vector<uint64_t> threads_used_usec;
359
360  if (scanType & eProfileThreadsCPU) {
361    get_threads_profile_data(scanType, task, pid, threads_id, threads_name,
362                             threads_used_usec);
363  }
364
365  vm_statistics64_data_t vminfo;
366  uint64_t physical_memory = 0;
367  uint64_t anonymous = 0;
368  uint64_t phys_footprint = 0;
369  uint64_t memory_cap = 0;
370  if (m_vm_memory.GetMemoryProfile(scanType, task, task_info,
371                                   m_process->GetCPUType(), pid, vminfo,
372                                   physical_memory, anonymous,
373                                   phys_footprint, memory_cap)) {
374    std::ostringstream profile_data_stream;
375
376    if (scanType & eProfileHostCPU) {
377      profile_data_stream << "num_cpu:" << numCPU << ';';
378      profile_data_stream << "host_user_ticks:"
379                          << host_info.cpu_ticks[CPU_STATE_USER] << ';';
380      profile_data_stream << "host_sys_ticks:"
381                          << host_info.cpu_ticks[CPU_STATE_SYSTEM] << ';';
382      profile_data_stream << "host_idle_ticks:"
383                          << host_info.cpu_ticks[CPU_STATE_IDLE] << ';';
384    }
385
386    if (scanType & eProfileCPU) {
387      profile_data_stream << "elapsed_usec:" << elapsed_usec << ';';
388      profile_data_stream << "task_used_usec:" << task_used_usec << ';';
389    }
390
391    if (scanType & eProfileThreadsCPU) {
392      const size_t num_threads = threads_id.size();
393      for (size_t i = 0; i < num_threads; i++) {
394        profile_data_stream << "thread_used_id:" << std::hex << threads_id[i]
395                            << std::dec << ';';
396        profile_data_stream << "thread_used_usec:" << threads_used_usec[i]
397                            << ';';
398
399        if (scanType & eProfileThreadName) {
400          profile_data_stream << "thread_used_name:";
401          const size_t len = threads_name[i].size();
402          if (len) {
403            const char *thread_name = threads_name[i].c_str();
404            // Make sure that thread name doesn't interfere with our delimiter.
405            profile_data_stream << RAW_HEXBASE << std::setw(2);
406            const uint8_t *ubuf8 = (const uint8_t *)(thread_name);
407            for (size_t j = 0; j < len; j++) {
408              profile_data_stream << (uint32_t)(ubuf8[j]);
409            }
410            // Reset back to DECIMAL.
411            profile_data_stream << DECIMAL;
412          }
413          profile_data_stream << ';';
414        }
415      }
416    }
417
418    if (scanType & eProfileHostMemory)
419      profile_data_stream << "total:" << physical_memory << ';';
420
421    if (scanType & eProfileMemory) {
422      static vm_size_t pagesize = vm_kernel_page_size;
423
424      // This mimicks Activity Monitor.
425      uint64_t total_used_count =
426          (physical_memory / pagesize) -
427          (vminfo.free_count - vminfo.speculative_count) -
428          vminfo.external_page_count - vminfo.purgeable_count;
429      profile_data_stream << "used:" << total_used_count * pagesize << ';';
430
431      if (scanType & eProfileMemoryAnonymous) {
432        profile_data_stream << "anonymous:" << anonymous << ';';
433      }
434
435      profile_data_stream << "phys_footprint:" << phys_footprint << ';';
436    }
437
438    if (scanType & eProfileMemoryCap) {
439      profile_data_stream << "mem_cap:" << memory_cap << ';';
440    }
441
442#ifdef LLDB_ENERGY
443    if (scanType & eProfileEnergy) {
444      struct rusage_info_v2 info;
445      int rc = proc_pid_rusage(pid, RUSAGE_INFO_V2, (rusage_info_t *)&info);
446      if (rc == 0) {
447        uint64_t now = mach_absolute_time();
448        pm_task_energy_data_t pm_energy;
449        memset(&pm_energy, 0, sizeof(pm_energy));
450        /*
451         * Disable most features of pm_sample_pid. It will gather
452         * network/GPU/WindowServer information; fill in the rest.
453         */
454        pm_sample_task_and_pid(task, pid, &pm_energy, now,
455                               PM_SAMPLE_ALL & ~PM_SAMPLE_NAME &
456                                   ~PM_SAMPLE_INTERVAL & ~PM_SAMPLE_CPU &
457                                   ~PM_SAMPLE_DISK);
458        pm_energy.sti.total_user = info.ri_user_time;
459        pm_energy.sti.total_system = info.ri_system_time;
460        pm_energy.sti.task_interrupt_wakeups = info.ri_interrupt_wkups;
461        pm_energy.sti.task_platform_idle_wakeups = info.ri_pkg_idle_wkups;
462        pm_energy.diskio_bytesread = info.ri_diskio_bytesread;
463        pm_energy.diskio_byteswritten = info.ri_diskio_byteswritten;
464        pm_energy.pageins = info.ri_pageins;
465
466        uint64_t total_energy =
467            (uint64_t)(pm_energy_impact(&pm_energy) * NSEC_PER_SEC);
468        // uint64_t process_age = now - info.ri_proc_start_abstime;
469        // uint64_t avg_energy = 100.0 * (double)total_energy /
470        // (double)process_age;
471
472        profile_data_stream << "energy:" << total_energy << ';';
473      }
474    }
475#endif
476
477    if (scanType & eProfileEnergyCPUCap) {
478      int percentage = -1;
479      int interval = -1;
480      int result = proc_get_cpumon_params(pid, &percentage, &interval);
481      if ((result == 0) && (percentage >= 0) && (interval >= 0)) {
482        profile_data_stream << "cpu_cap_p:" << percentage << ';';
483        profile_data_stream << "cpu_cap_t:" << interval << ';';
484      }
485    }
486
487    profile_data_stream << "--end--;";
488
489    result = profile_data_stream.str();
490  }
491
492  return result;
493}
494
495//----------------------------------------------------------------------
496// MachTask::TaskPortForProcessID
497//----------------------------------------------------------------------
498task_t MachTask::TaskPortForProcessID(DNBError &err, bool force) {
499  if (((m_task == TASK_NULL) || force) && m_process != NULL)
500    m_task = MachTask::TaskPortForProcessID(m_process->ProcessID(), err);
501  return m_task;
502}
503
504//----------------------------------------------------------------------
505// MachTask::TaskPortForProcessID
506//----------------------------------------------------------------------
507task_t MachTask::TaskPortForProcessID(pid_t pid, DNBError &err,
508                                      uint32_t num_retries,
509                                      uint32_t usec_interval) {
510  if (pid != INVALID_NUB_PROCESS) {
511    DNBError err;
512    mach_port_t task_self = mach_task_self();
513    task_t task = TASK_NULL;
514    for (uint32_t i = 0; i < num_retries; i++) {
515      err = ::task_for_pid(task_self, pid, &task);
516
517      if (DNBLogCheckLogBit(LOG_TASK) || err.Fail()) {
518        char str[1024];
519        ::snprintf(str, sizeof(str), "::task_for_pid ( target_tport = 0x%4.4x, "
520                                     "pid = %d, &task ) => err = 0x%8.8x (%s)",
521                   task_self, pid, err.Status(),
522                   err.AsString() ? err.AsString() : "success");
523        if (err.Fail()) {
524          err.SetErrorString(str);
525          DNBLogError ("MachTask::TaskPortForProcessID task_for_pid failed: %s", str);
526        }
527        err.LogThreaded(str);
528      }
529
530      if (err.Success())
531        return task;
532
533      // Sleep a bit and try again
534      ::usleep(usec_interval);
535    }
536  }
537  return TASK_NULL;
538}
539
540//----------------------------------------------------------------------
541// MachTask::BasicInfo
542//----------------------------------------------------------------------
543kern_return_t MachTask::BasicInfo(struct task_basic_info *info) {
544  return BasicInfo(TaskPort(), info);
545}
546
547//----------------------------------------------------------------------
548// MachTask::BasicInfo
549//----------------------------------------------------------------------
550kern_return_t MachTask::BasicInfo(task_t task, struct task_basic_info *info) {
551  if (info == NULL)
552    return KERN_INVALID_ARGUMENT;
553
554  DNBError err;
555  mach_msg_type_number_t count = TASK_BASIC_INFO_COUNT;
556  err = ::task_info(task, TASK_BASIC_INFO, (task_info_t)info, &count);
557  const bool log_process = DNBLogCheckLogBit(LOG_TASK);
558  if (log_process || err.Fail())
559    err.LogThreaded("::task_info ( target_task = 0x%4.4x, flavor = "
560                    "TASK_BASIC_INFO, task_info_out => %p, task_info_outCnt => "
561                    "%u )",
562                    task, info, count);
563  if (DNBLogCheckLogBit(LOG_TASK) && DNBLogCheckLogBit(LOG_VERBOSE) &&
564      err.Success()) {
565    float user = (float)info->user_time.seconds +
566                 (float)info->user_time.microseconds / 1000000.0f;
567    float system = (float)info->user_time.seconds +
568                   (float)info->user_time.microseconds / 1000000.0f;
569    DNBLogThreaded("task_basic_info = { suspend_count = %i, virtual_size = "
570                   "0x%8.8llx, resident_size = 0x%8.8llx, user_time = %f, "
571                   "system_time = %f }",
572                   info->suspend_count, (uint64_t)info->virtual_size,
573                   (uint64_t)info->resident_size, user, system);
574  }
575  return err.Status();
576}
577
578//----------------------------------------------------------------------
579// MachTask::IsValid
580//
581// Returns true if a task is a valid task port for a current process.
582//----------------------------------------------------------------------
583bool MachTask::IsValid() const { return MachTask::IsValid(TaskPort()); }
584
585//----------------------------------------------------------------------
586// MachTask::IsValid
587//
588// Returns true if a task is a valid task port for a current process.
589//----------------------------------------------------------------------
590bool MachTask::IsValid(task_t task) {
591  if (task != TASK_NULL) {
592    struct task_basic_info task_info;
593    return BasicInfo(task, &task_info) == KERN_SUCCESS;
594  }
595  return false;
596}
597
598bool MachTask::StartExceptionThread(DNBError &err) {
599  DNBLogThreadedIf(LOG_EXCEPTIONS, "MachTask::%s ( )", __FUNCTION__);
600
601  task_t task = TaskPortForProcessID(err);
602  if (MachTask::IsValid(task)) {
603    // Got the mach port for the current process
604    mach_port_t task_self = mach_task_self();
605
606    // Allocate an exception port that we will use to track our child process
607    err = ::mach_port_allocate(task_self, MACH_PORT_RIGHT_RECEIVE,
608                               &m_exception_port);
609    if (err.Fail())
610      return false;
611
612    // Add the ability to send messages on the new exception port
613    err = ::mach_port_insert_right(task_self, m_exception_port,
614                                   m_exception_port, MACH_MSG_TYPE_MAKE_SEND);
615    if (err.Fail())
616      return false;
617
618    // Save the original state of the exception ports for our child process
619    SaveExceptionPortInfo();
620
621    // We weren't able to save the info for our exception ports, we must stop...
622    if (m_exc_port_info.mask == 0) {
623      err.SetErrorString("failed to get exception port info");
624      return false;
625    }
626
627    // Set the ability to get all exceptions on this port
628    err = ::task_set_exception_ports(
629        task, m_exc_port_info.mask, m_exception_port,
630        EXCEPTION_DEFAULT | MACH_EXCEPTION_CODES, THREAD_STATE_NONE);
631    if (DNBLogCheckLogBit(LOG_EXCEPTIONS) || err.Fail()) {
632      err.LogThreaded("::task_set_exception_ports ( task = 0x%4.4x, "
633                      "exception_mask = 0x%8.8x, new_port = 0x%4.4x, behavior "
634                      "= 0x%8.8x, new_flavor = 0x%8.8x )",
635                      task, m_exc_port_info.mask, m_exception_port,
636                      (EXCEPTION_DEFAULT | MACH_EXCEPTION_CODES),
637                      THREAD_STATE_NONE);
638    }
639
640    if (err.Fail())
641      return false;
642
643    // Create the exception thread
644    err = ::pthread_create(&m_exception_thread, NULL, MachTask::ExceptionThread,
645                           this);
646    return err.Success();
647  } else {
648    DNBLogError("MachTask::%s (): task invalid, exception thread start failed.",
649                __FUNCTION__);
650  }
651  return false;
652}
653
654kern_return_t MachTask::ShutDownExcecptionThread() {
655  DNBError err;
656
657  err = RestoreExceptionPortInfo();
658
659  // NULL our our exception port and let our exception thread exit
660  mach_port_t exception_port = m_exception_port;
661  m_exception_port = 0;
662
663  err.SetError(::pthread_cancel(m_exception_thread), DNBError::POSIX);
664  if (DNBLogCheckLogBit(LOG_TASK) || err.Fail())
665    err.LogThreaded("::pthread_cancel ( thread = %p )", m_exception_thread);
666
667  err.SetError(::pthread_join(m_exception_thread, NULL), DNBError::POSIX);
668  if (DNBLogCheckLogBit(LOG_TASK) || err.Fail())
669    err.LogThreaded("::pthread_join ( thread = %p, value_ptr = NULL)",
670                    m_exception_thread);
671
672  // Deallocate our exception port that we used to track our child process
673  mach_port_t task_self = mach_task_self();
674  err = ::mach_port_deallocate(task_self, exception_port);
675  if (DNBLogCheckLogBit(LOG_TASK) || err.Fail())
676    err.LogThreaded("::mach_port_deallocate ( task = 0x%4.4x, name = 0x%4.4x )",
677                    task_self, exception_port);
678
679  m_exec_will_be_suspended = false;
680  m_do_double_resume = false;
681
682  return err.Status();
683}
684
685void *MachTask::ExceptionThread(void *arg) {
686  if (arg == NULL)
687    return NULL;
688
689  MachTask *mach_task = (MachTask *)arg;
690  MachProcess *mach_proc = mach_task->Process();
691  DNBLogThreadedIf(LOG_EXCEPTIONS,
692                   "MachTask::%s ( arg = %p ) starting thread...", __FUNCTION__,
693                   arg);
694
695#if defined(__APPLE__)
696  pthread_setname_np("exception monitoring thread");
697#if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
698  struct sched_param thread_param;
699  int thread_sched_policy;
700  if (pthread_getschedparam(pthread_self(), &thread_sched_policy,
701                            &thread_param) == 0) {
702    thread_param.sched_priority = 47;
703    pthread_setschedparam(pthread_self(), thread_sched_policy, &thread_param);
704  }
705#endif
706#endif
707
708  // We keep a count of the number of consecutive exceptions received so
709  // we know to grab all exceptions without a timeout. We do this to get a
710  // bunch of related exceptions on our exception port so we can process
711  // then together. When we have multiple threads, we can get an exception
712  // per thread and they will come in consecutively. The main loop in this
713  // thread can stop periodically if needed to service things related to this
714  // process.
715  // flag set in the options, so we will wait forever for an exception on
716  // our exception port. After we get one exception, we then will use the
717  // MACH_RCV_TIMEOUT option with a zero timeout to grab all other current
718  // exceptions for our process. After we have received the last pending
719  // exception, we will get a timeout which enables us to then notify
720  // our main thread that we have an exception bundle available. We then wait
721  // for the main thread to tell this exception thread to start trying to get
722  // exceptions messages again and we start again with a mach_msg read with
723  // infinite timeout.
724  uint32_t num_exceptions_received = 0;
725  DNBError err;
726  task_t task = mach_task->TaskPort();
727  mach_msg_timeout_t periodic_timeout = 0;
728
729#if defined(WITH_SPRINGBOARD) && !defined(WITH_BKS)
730  mach_msg_timeout_t watchdog_elapsed = 0;
731  mach_msg_timeout_t watchdog_timeout = 60 * 1000;
732  pid_t pid = mach_proc->ProcessID();
733  CFReleaser<SBSWatchdogAssertionRef> watchdog;
734
735  if (mach_proc->ProcessUsingSpringBoard()) {
736    // Request a renewal for every 60 seconds if we attached using SpringBoard
737    watchdog.reset(::SBSWatchdogAssertionCreateForPID(NULL, pid, 60));
738    DNBLogThreadedIf(
739        LOG_TASK, "::SBSWatchdogAssertionCreateForPID (NULL, %4.4x, 60 ) => %p",
740        pid, watchdog.get());
741
742    if (watchdog.get()) {
743      ::SBSWatchdogAssertionRenew(watchdog.get());
744
745      CFTimeInterval watchdogRenewalInterval =
746          ::SBSWatchdogAssertionGetRenewalInterval(watchdog.get());
747      DNBLogThreadedIf(
748          LOG_TASK,
749          "::SBSWatchdogAssertionGetRenewalInterval ( %p ) => %g seconds",
750          watchdog.get(), watchdogRenewalInterval);
751      if (watchdogRenewalInterval > 0.0) {
752        watchdog_timeout = (mach_msg_timeout_t)watchdogRenewalInterval * 1000;
753        if (watchdog_timeout > 3000)
754          watchdog_timeout -= 1000; // Give us a second to renew our timeout
755        else if (watchdog_timeout > 1000)
756          watchdog_timeout -=
757              250; // Give us a quarter of a second to renew our timeout
758      }
759    }
760    if (periodic_timeout == 0 || periodic_timeout > watchdog_timeout)
761      periodic_timeout = watchdog_timeout;
762  }
763#endif // #if defined (WITH_SPRINGBOARD) && !defined (WITH_BKS)
764
765#ifdef WITH_BKS
766  CFReleaser<BKSWatchdogAssertionRef> watchdog;
767  if (mach_proc->ProcessUsingBackBoard()) {
768    pid_t pid = mach_proc->ProcessID();
769    CFAllocatorRef alloc = kCFAllocatorDefault;
770    watchdog.reset(::BKSWatchdogAssertionCreateForPID(alloc, pid));
771  }
772#endif // #ifdef WITH_BKS
773
774  while (mach_task->ExceptionPortIsValid()) {
775    ::pthread_testcancel();
776
777    MachException::Message exception_message;
778
779    if (num_exceptions_received > 0) {
780      // No timeout, just receive as many exceptions as we can since we already
781      // have one and we want
782      // to get all currently available exceptions for this task
783      err = exception_message.Receive(
784          mach_task->ExceptionPort(),
785          MACH_RCV_MSG | MACH_RCV_INTERRUPT | MACH_RCV_TIMEOUT, 1);
786    } else if (periodic_timeout > 0) {
787      // We need to stop periodically in this loop, so try and get a mach
788      // message with a valid timeout (ms)
789      err = exception_message.Receive(mach_task->ExceptionPort(),
790                                      MACH_RCV_MSG | MACH_RCV_INTERRUPT |
791                                          MACH_RCV_TIMEOUT,
792                                      periodic_timeout);
793    } else {
794      // We don't need to parse all current exceptions or stop periodically,
795      // just wait for an exception forever.
796      err = exception_message.Receive(mach_task->ExceptionPort(),
797                                      MACH_RCV_MSG | MACH_RCV_INTERRUPT, 0);
798    }
799
800    if (err.Status() == MACH_RCV_INTERRUPTED) {
801      // If we have no task port we should exit this thread
802      if (!mach_task->ExceptionPortIsValid()) {
803        DNBLogThreadedIf(LOG_EXCEPTIONS, "thread cancelled...");
804        break;
805      }
806
807      // Make sure our task is still valid
808      if (MachTask::IsValid(task)) {
809        // Task is still ok
810        DNBLogThreadedIf(LOG_EXCEPTIONS,
811                         "interrupted, but task still valid, continuing...");
812        continue;
813      } else {
814        DNBLogThreadedIf(LOG_EXCEPTIONS, "task has exited...");
815        mach_proc->SetState(eStateExited);
816        // Our task has died, exit the thread.
817        break;
818      }
819    } else if (err.Status() == MACH_RCV_TIMED_OUT) {
820      if (num_exceptions_received > 0) {
821        // We were receiving all current exceptions with a timeout of zero
822        // it is time to go back to our normal looping mode
823        num_exceptions_received = 0;
824
825        // Notify our main thread we have a complete exception message
826        // bundle available and get the possibly updated task port back
827        // from the process in case we exec'ed and our task port changed
828        task = mach_proc->ExceptionMessageBundleComplete();
829
830        // in case we use a timeout value when getting exceptions...
831        // Make sure our task is still valid
832        if (MachTask::IsValid(task)) {
833          // Task is still ok
834          DNBLogThreadedIf(LOG_EXCEPTIONS, "got a timeout, continuing...");
835          continue;
836        } else {
837          DNBLogThreadedIf(LOG_EXCEPTIONS, "task has exited...");
838          mach_proc->SetState(eStateExited);
839          // Our task has died, exit the thread.
840          break;
841        }
842      }
843
844#if defined(WITH_SPRINGBOARD) && !defined(WITH_BKS)
845      if (watchdog.get()) {
846        watchdog_elapsed += periodic_timeout;
847        if (watchdog_elapsed >= watchdog_timeout) {
848          DNBLogThreadedIf(LOG_TASK, "SBSWatchdogAssertionRenew ( %p )",
849                           watchdog.get());
850          ::SBSWatchdogAssertionRenew(watchdog.get());
851          watchdog_elapsed = 0;
852        }
853      }
854#endif
855    } else if (err.Status() != KERN_SUCCESS) {
856      DNBLogThreadedIf(LOG_EXCEPTIONS, "got some other error, do something "
857                                       "about it??? nah, continuing for "
858                                       "now...");
859      // TODO: notify of error?
860    } else {
861      if (exception_message.CatchExceptionRaise(task)) {
862        if (exception_message.state.task_port != task) {
863          if (exception_message.state.IsValid()) {
864            // We exec'ed and our task port changed on us.
865            DNBLogThreadedIf(LOG_EXCEPTIONS,
866                             "task port changed from 0x%4.4x to 0x%4.4x",
867                             task, exception_message.state.task_port);
868            task = exception_message.state.task_port;
869            mach_task->TaskPortChanged(exception_message.state.task_port);
870          }
871        }
872        ++num_exceptions_received;
873        mach_proc->ExceptionMessageReceived(exception_message);
874      }
875    }
876  }
877
878#if defined(WITH_SPRINGBOARD) && !defined(WITH_BKS)
879  if (watchdog.get()) {
880    // TODO: change SBSWatchdogAssertionRelease to SBSWatchdogAssertionCancel
881    // when we
882    // all are up and running on systems that support it. The SBS framework has
883    // a #define
884    // that will forward SBSWatchdogAssertionRelease to
885    // SBSWatchdogAssertionCancel for now
886    // so it should still build either way.
887    DNBLogThreadedIf(LOG_TASK, "::SBSWatchdogAssertionRelease(%p)",
888                     watchdog.get());
889    ::SBSWatchdogAssertionRelease(watchdog.get());
890  }
891#endif // #if defined (WITH_SPRINGBOARD) && !defined (WITH_BKS)
892
893  DNBLogThreadedIf(LOG_EXCEPTIONS, "MachTask::%s (%p): thread exiting...",
894                   __FUNCTION__, arg);
895  return NULL;
896}
897
898// So the TASK_DYLD_INFO used to just return the address of the all image infos
899// as a single member called "all_image_info". Then someone decided it would be
900// a good idea to rename this first member to "all_image_info_addr" and add a
901// size member called "all_image_info_size". This of course can not be detected
902// using code or #defines. So to hack around this problem, we define our own
903// version of the TASK_DYLD_INFO structure so we can guarantee what is inside
904// it.
905
906struct hack_task_dyld_info {
907  mach_vm_address_t all_image_info_addr;
908  mach_vm_size_t all_image_info_size;
909};
910
911nub_addr_t MachTask::GetDYLDAllImageInfosAddress(DNBError &err) {
912  struct hack_task_dyld_info dyld_info;
913  mach_msg_type_number_t count = TASK_DYLD_INFO_COUNT;
914  // Make sure that COUNT isn't bigger than our hacked up struct
915  // hack_task_dyld_info.
916  // If it is, then make COUNT smaller to match.
917  if (count > (sizeof(struct hack_task_dyld_info) / sizeof(natural_t)))
918    count = (sizeof(struct hack_task_dyld_info) / sizeof(natural_t));
919
920  task_t task = TaskPortForProcessID(err);
921  if (err.Success()) {
922    err = ::task_info(task, TASK_DYLD_INFO, (task_info_t)&dyld_info, &count);
923    if (err.Success()) {
924      // We now have the address of the all image infos structure
925      return dyld_info.all_image_info_addr;
926    }
927  }
928  return INVALID_NUB_ADDRESS;
929}
930
931//----------------------------------------------------------------------
932// MachTask::AllocateMemory
933//----------------------------------------------------------------------
934nub_addr_t MachTask::AllocateMemory(size_t size, uint32_t permissions) {
935  mach_vm_address_t addr;
936  task_t task = TaskPort();
937  if (task == TASK_NULL)
938    return INVALID_NUB_ADDRESS;
939
940  DNBError err;
941  err = ::mach_vm_allocate(task, &addr, size, TRUE);
942  if (err.Status() == KERN_SUCCESS) {
943    // Set the protections:
944    vm_prot_t mach_prot = VM_PROT_NONE;
945    if (permissions & eMemoryPermissionsReadable)
946      mach_prot |= VM_PROT_READ;
947    if (permissions & eMemoryPermissionsWritable)
948      mach_prot |= VM_PROT_WRITE;
949    if (permissions & eMemoryPermissionsExecutable)
950      mach_prot |= VM_PROT_EXECUTE;
951
952    err = ::mach_vm_protect(task, addr, size, 0, mach_prot);
953    if (err.Status() == KERN_SUCCESS) {
954      m_allocations.insert(std::make_pair(addr, size));
955      return addr;
956    }
957    ::mach_vm_deallocate(task, addr, size);
958  }
959  return INVALID_NUB_ADDRESS;
960}
961
962//----------------------------------------------------------------------
963// MachTask::DeallocateMemory
964//----------------------------------------------------------------------
965nub_bool_t MachTask::DeallocateMemory(nub_addr_t addr) {
966  task_t task = TaskPort();
967  if (task == TASK_NULL)
968    return false;
969
970  // We have to stash away sizes for the allocations...
971  allocation_collection::iterator pos, end = m_allocations.end();
972  for (pos = m_allocations.begin(); pos != end; pos++) {
973    if ((*pos).first == addr) {
974      m_allocations.erase(pos);
975#define ALWAYS_ZOMBIE_ALLOCATIONS 0
976      if (ALWAYS_ZOMBIE_ALLOCATIONS ||
977          getenv("DEBUGSERVER_ZOMBIE_ALLOCATIONS")) {
978        ::mach_vm_protect(task, (*pos).first, (*pos).second, 0, VM_PROT_NONE);
979        return true;
980      } else
981        return ::mach_vm_deallocate(task, (*pos).first, (*pos).second) ==
982               KERN_SUCCESS;
983    }
984  }
985  return false;
986}
987
988void MachTask::TaskPortChanged(task_t task)
989{
990  m_task = task;
991
992  // If we've just exec'd to a new process, and it
993  // is started suspended, we'll need to do two
994  // task_resume's to get the inferior process to
995  // continue.
996  if (m_exec_will_be_suspended)
997    m_do_double_resume = true;
998  else
999    m_do_double_resume = false;
1000  m_exec_will_be_suspended = false;
1001}
1002