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      DNBLog("[LaunchAttach] (%d) about to task_for_pid(%d)", getpid(), pid);
516      err = ::task_for_pid(task_self, pid, &task);
517
518      if (DNBLogCheckLogBit(LOG_TASK) || err.Fail()) {
519        char str[1024];
520        ::snprintf(str, sizeof(str), "::task_for_pid ( target_tport = 0x%4.4x, "
521                                     "pid = %d, &task ) => err = 0x%8.8x (%s)",
522                   task_self, pid, err.Status(),
523                   err.AsString() ? err.AsString() : "success");
524        if (err.Fail()) {
525          err.SetErrorString(str);
526          DNBLogError(
527              "[LaunchAttach] MachTask::TaskPortForProcessID task_for_pid(%d) "
528              "failed: %s",
529              pid, str);
530        }
531        err.LogThreaded(str);
532      }
533
534      if (err.Success()) {
535        DNBLog("[LaunchAttach] (%d) successfully task_for_pid(%d)'ed", getpid(),
536               pid);
537        return task;
538      }
539
540      // Sleep a bit and try again
541      ::usleep(usec_interval);
542    }
543  }
544  return TASK_NULL;
545}
546
547//----------------------------------------------------------------------
548// MachTask::BasicInfo
549//----------------------------------------------------------------------
550kern_return_t MachTask::BasicInfo(struct task_basic_info *info) {
551  return BasicInfo(TaskPort(), info);
552}
553
554//----------------------------------------------------------------------
555// MachTask::BasicInfo
556//----------------------------------------------------------------------
557kern_return_t MachTask::BasicInfo(task_t task, struct task_basic_info *info) {
558  if (info == NULL)
559    return KERN_INVALID_ARGUMENT;
560
561  DNBError err;
562  mach_msg_type_number_t count = TASK_BASIC_INFO_COUNT;
563  err = ::task_info(task, TASK_BASIC_INFO, (task_info_t)info, &count);
564  const bool log_process = DNBLogCheckLogBit(LOG_TASK);
565  if (log_process || err.Fail())
566    err.LogThreaded("::task_info ( target_task = 0x%4.4x, flavor = "
567                    "TASK_BASIC_INFO, task_info_out => %p, task_info_outCnt => "
568                    "%u )",
569                    task, info, count);
570  if (DNBLogCheckLogBit(LOG_TASK) && DNBLogCheckLogBit(LOG_VERBOSE) &&
571      err.Success()) {
572    float user = (float)info->user_time.seconds +
573                 (float)info->user_time.microseconds / 1000000.0f;
574    float system = (float)info->user_time.seconds +
575                   (float)info->user_time.microseconds / 1000000.0f;
576    DNBLogThreaded("task_basic_info = { suspend_count = %i, virtual_size = "
577                   "0x%8.8llx, resident_size = 0x%8.8llx, user_time = %f, "
578                   "system_time = %f }",
579                   info->suspend_count, (uint64_t)info->virtual_size,
580                   (uint64_t)info->resident_size, user, system);
581  }
582  return err.Status();
583}
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() const { return MachTask::IsValid(TaskPort()); }
591
592//----------------------------------------------------------------------
593// MachTask::IsValid
594//
595// Returns true if a task is a valid task port for a current process.
596//----------------------------------------------------------------------
597bool MachTask::IsValid(task_t task) {
598  if (task != TASK_NULL) {
599    struct task_basic_info task_info;
600    return BasicInfo(task, &task_info) == KERN_SUCCESS;
601  }
602  return false;
603}
604
605bool MachTask::StartExceptionThread(bool unmask_signals, DNBError &err) {
606  DNBLogThreadedIf(LOG_EXCEPTIONS, "MachTask::%s ( )", __FUNCTION__);
607
608  task_t task = TaskPortForProcessID(err);
609  if (MachTask::IsValid(task)) {
610    // Got the mach port for the current process
611    mach_port_t task_self = mach_task_self();
612
613    // Allocate an exception port that we will use to track our child process
614    err = ::mach_port_allocate(task_self, MACH_PORT_RIGHT_RECEIVE,
615                               &m_exception_port);
616    if (err.Fail())
617      return false;
618
619    // Add the ability to send messages on the new exception port
620    err = ::mach_port_insert_right(task_self, m_exception_port,
621                                   m_exception_port, MACH_MSG_TYPE_MAKE_SEND);
622    if (err.Fail())
623      return false;
624
625    // Save the original state of the exception ports for our child process
626    SaveExceptionPortInfo();
627
628    // We weren't able to save the info for our exception ports, we must stop...
629    if (m_exc_port_info.mask == 0) {
630      err.SetErrorString("failed to get exception port info");
631      return false;
632    }
633
634    if (unmask_signals) {
635      m_exc_port_info.mask = m_exc_port_info.mask &
636                             ~(EXC_MASK_BAD_ACCESS | EXC_MASK_BAD_INSTRUCTION |
637                               EXC_MASK_ARITHMETIC);
638    }
639
640    // Set the ability to get all exceptions on this port
641    err = ::task_set_exception_ports(
642        task, m_exc_port_info.mask, m_exception_port,
643        EXCEPTION_DEFAULT | MACH_EXCEPTION_CODES, THREAD_STATE_NONE);
644    if (DNBLogCheckLogBit(LOG_EXCEPTIONS) || err.Fail()) {
645      err.LogThreaded("::task_set_exception_ports ( task = 0x%4.4x, "
646                      "exception_mask = 0x%8.8x, new_port = 0x%4.4x, behavior "
647                      "= 0x%8.8x, new_flavor = 0x%8.8x )",
648                      task, m_exc_port_info.mask, m_exception_port,
649                      (EXCEPTION_DEFAULT | MACH_EXCEPTION_CODES),
650                      THREAD_STATE_NONE);
651    }
652
653    if (err.Fail())
654      return false;
655
656    // Create the exception thread
657    err = ::pthread_create(&m_exception_thread, NULL, MachTask::ExceptionThread,
658                           this);
659    return err.Success();
660  } else {
661    DNBLogError("MachTask::%s (): task invalid, exception thread start failed.",
662                __FUNCTION__);
663  }
664  return false;
665}
666
667kern_return_t MachTask::ShutDownExcecptionThread() {
668  DNBError err;
669
670  err = RestoreExceptionPortInfo();
671
672  // NULL our our exception port and let our exception thread exit
673  mach_port_t exception_port = m_exception_port;
674  m_exception_port = 0;
675
676  err.SetError(::pthread_cancel(m_exception_thread), DNBError::POSIX);
677  if (DNBLogCheckLogBit(LOG_TASK) || err.Fail())
678    err.LogThreaded("::pthread_cancel ( thread = %p )", m_exception_thread);
679
680  err.SetError(::pthread_join(m_exception_thread, NULL), DNBError::POSIX);
681  if (DNBLogCheckLogBit(LOG_TASK) || err.Fail())
682    err.LogThreaded("::pthread_join ( thread = %p, value_ptr = NULL)",
683                    m_exception_thread);
684
685  // Deallocate our exception port that we used to track our child process
686  mach_port_t task_self = mach_task_self();
687  err = ::mach_port_deallocate(task_self, exception_port);
688  if (DNBLogCheckLogBit(LOG_TASK) || err.Fail())
689    err.LogThreaded("::mach_port_deallocate ( task = 0x%4.4x, name = 0x%4.4x )",
690                    task_self, exception_port);
691
692  m_exec_will_be_suspended = false;
693  m_do_double_resume = false;
694
695  return err.Status();
696}
697
698void *MachTask::ExceptionThread(void *arg) {
699  if (arg == NULL)
700    return NULL;
701
702  MachTask *mach_task = (MachTask *)arg;
703  MachProcess *mach_proc = mach_task->Process();
704  DNBLogThreadedIf(LOG_EXCEPTIONS,
705                   "MachTask::%s ( arg = %p ) starting thread...", __FUNCTION__,
706                   arg);
707
708#if defined(__APPLE__)
709  pthread_setname_np("exception monitoring thread");
710#if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
711  struct sched_param thread_param;
712  int thread_sched_policy;
713  if (pthread_getschedparam(pthread_self(), &thread_sched_policy,
714                            &thread_param) == 0) {
715    thread_param.sched_priority = 47;
716    pthread_setschedparam(pthread_self(), thread_sched_policy, &thread_param);
717  }
718#endif
719#endif
720
721  // We keep a count of the number of consecutive exceptions received so
722  // we know to grab all exceptions without a timeout. We do this to get a
723  // bunch of related exceptions on our exception port so we can process
724  // then together. When we have multiple threads, we can get an exception
725  // per thread and they will come in consecutively. The main loop in this
726  // thread can stop periodically if needed to service things related to this
727  // process.
728  // flag set in the options, so we will wait forever for an exception on
729  // our exception port. After we get one exception, we then will use the
730  // MACH_RCV_TIMEOUT option with a zero timeout to grab all other current
731  // exceptions for our process. After we have received the last pending
732  // exception, we will get a timeout which enables us to then notify
733  // our main thread that we have an exception bundle available. We then wait
734  // for the main thread to tell this exception thread to start trying to get
735  // exceptions messages again and we start again with a mach_msg read with
736  // infinite timeout.
737  uint32_t num_exceptions_received = 0;
738  DNBError err;
739  task_t task = mach_task->TaskPort();
740  mach_msg_timeout_t periodic_timeout = 0;
741
742#if defined(WITH_SPRINGBOARD) && !defined(WITH_BKS)
743  mach_msg_timeout_t watchdog_elapsed = 0;
744  mach_msg_timeout_t watchdog_timeout = 60 * 1000;
745  pid_t pid = mach_proc->ProcessID();
746  CFReleaser<SBSWatchdogAssertionRef> watchdog;
747
748  if (mach_proc->ProcessUsingSpringBoard()) {
749    // Request a renewal for every 60 seconds if we attached using SpringBoard
750    watchdog.reset(::SBSWatchdogAssertionCreateForPID(NULL, pid, 60));
751    DNBLogThreadedIf(
752        LOG_TASK, "::SBSWatchdogAssertionCreateForPID (NULL, %4.4x, 60 ) => %p",
753        pid, watchdog.get());
754
755    if (watchdog.get()) {
756      ::SBSWatchdogAssertionRenew(watchdog.get());
757
758      CFTimeInterval watchdogRenewalInterval =
759          ::SBSWatchdogAssertionGetRenewalInterval(watchdog.get());
760      DNBLogThreadedIf(
761          LOG_TASK,
762          "::SBSWatchdogAssertionGetRenewalInterval ( %p ) => %g seconds",
763          watchdog.get(), watchdogRenewalInterval);
764      if (watchdogRenewalInterval > 0.0) {
765        watchdog_timeout = (mach_msg_timeout_t)watchdogRenewalInterval * 1000;
766        if (watchdog_timeout > 3000)
767          watchdog_timeout -= 1000; // Give us a second to renew our timeout
768        else if (watchdog_timeout > 1000)
769          watchdog_timeout -=
770              250; // Give us a quarter of a second to renew our timeout
771      }
772    }
773    if (periodic_timeout == 0 || periodic_timeout > watchdog_timeout)
774      periodic_timeout = watchdog_timeout;
775  }
776#endif // #if defined (WITH_SPRINGBOARD) && !defined (WITH_BKS)
777
778#ifdef WITH_BKS
779  CFReleaser<BKSWatchdogAssertionRef> watchdog;
780  if (mach_proc->ProcessUsingBackBoard()) {
781    pid_t pid = mach_proc->ProcessID();
782    CFAllocatorRef alloc = kCFAllocatorDefault;
783    watchdog.reset(::BKSWatchdogAssertionCreateForPID(alloc, pid));
784  }
785#endif // #ifdef WITH_BKS
786
787  while (mach_task->ExceptionPortIsValid()) {
788    ::pthread_testcancel();
789
790    MachException::Message exception_message;
791
792    if (num_exceptions_received > 0) {
793      // No timeout, just receive as many exceptions as we can since we already
794      // have one and we want
795      // to get all currently available exceptions for this task
796      err = exception_message.Receive(
797          mach_task->ExceptionPort(),
798          MACH_RCV_MSG | MACH_RCV_INTERRUPT | MACH_RCV_TIMEOUT, 1);
799    } else if (periodic_timeout > 0) {
800      // We need to stop periodically in this loop, so try and get a mach
801      // message with a valid timeout (ms)
802      err = exception_message.Receive(mach_task->ExceptionPort(),
803                                      MACH_RCV_MSG | MACH_RCV_INTERRUPT |
804                                          MACH_RCV_TIMEOUT,
805                                      periodic_timeout);
806    } else {
807      // We don't need to parse all current exceptions or stop periodically,
808      // just wait for an exception forever.
809      err = exception_message.Receive(mach_task->ExceptionPort(),
810                                      MACH_RCV_MSG | MACH_RCV_INTERRUPT, 0);
811    }
812
813    if (err.Status() == MACH_RCV_INTERRUPTED) {
814      // If we have no task port we should exit this thread
815      if (!mach_task->ExceptionPortIsValid()) {
816        DNBLogThreadedIf(LOG_EXCEPTIONS, "thread cancelled...");
817        break;
818      }
819
820      // Make sure our task is still valid
821      if (MachTask::IsValid(task)) {
822        // Task is still ok
823        DNBLogThreadedIf(LOG_EXCEPTIONS,
824                         "interrupted, but task still valid, continuing...");
825        continue;
826      } else {
827        DNBLogThreadedIf(LOG_EXCEPTIONS, "task has exited...");
828        mach_proc->SetState(eStateExited);
829        // Our task has died, exit the thread.
830        break;
831      }
832    } else if (err.Status() == MACH_RCV_TIMED_OUT) {
833      if (num_exceptions_received > 0) {
834        // We were receiving all current exceptions with a timeout of zero
835        // it is time to go back to our normal looping mode
836        num_exceptions_received = 0;
837
838        // Notify our main thread we have a complete exception message
839        // bundle available and get the possibly updated task port back
840        // from the process in case we exec'ed and our task port changed
841        task = mach_proc->ExceptionMessageBundleComplete();
842
843        // in case we use a timeout value when getting exceptions...
844        // Make sure our task is still valid
845        if (MachTask::IsValid(task)) {
846          // Task is still ok
847          DNBLogThreadedIf(LOG_EXCEPTIONS, "got a timeout, continuing...");
848          continue;
849        } else {
850          DNBLogThreadedIf(LOG_EXCEPTIONS, "task has exited...");
851          mach_proc->SetState(eStateExited);
852          // Our task has died, exit the thread.
853          break;
854        }
855      }
856
857#if defined(WITH_SPRINGBOARD) && !defined(WITH_BKS)
858      if (watchdog.get()) {
859        watchdog_elapsed += periodic_timeout;
860        if (watchdog_elapsed >= watchdog_timeout) {
861          DNBLogThreadedIf(LOG_TASK, "SBSWatchdogAssertionRenew ( %p )",
862                           watchdog.get());
863          ::SBSWatchdogAssertionRenew(watchdog.get());
864          watchdog_elapsed = 0;
865        }
866      }
867#endif
868    } else if (err.Status() != KERN_SUCCESS) {
869      DNBLogThreadedIf(LOG_EXCEPTIONS, "got some other error, do something "
870                                       "about it??? nah, continuing for "
871                                       "now...");
872      // TODO: notify of error?
873    } else {
874      if (exception_message.CatchExceptionRaise(task)) {
875        if (exception_message.state.task_port != task) {
876          if (exception_message.state.IsValid()) {
877            // We exec'ed and our task port changed on us.
878            DNBLogThreadedIf(LOG_EXCEPTIONS,
879                             "task port changed from 0x%4.4x to 0x%4.4x",
880                             task, exception_message.state.task_port);
881            task = exception_message.state.task_port;
882            mach_task->TaskPortChanged(exception_message.state.task_port);
883          }
884        }
885        ++num_exceptions_received;
886        mach_proc->ExceptionMessageReceived(exception_message);
887      }
888    }
889  }
890
891#if defined(WITH_SPRINGBOARD) && !defined(WITH_BKS)
892  if (watchdog.get()) {
893    // TODO: change SBSWatchdogAssertionRelease to SBSWatchdogAssertionCancel
894    // when we
895    // all are up and running on systems that support it. The SBS framework has
896    // a #define
897    // that will forward SBSWatchdogAssertionRelease to
898    // SBSWatchdogAssertionCancel for now
899    // so it should still build either way.
900    DNBLogThreadedIf(LOG_TASK, "::SBSWatchdogAssertionRelease(%p)",
901                     watchdog.get());
902    ::SBSWatchdogAssertionRelease(watchdog.get());
903  }
904#endif // #if defined (WITH_SPRINGBOARD) && !defined (WITH_BKS)
905
906  DNBLogThreadedIf(LOG_EXCEPTIONS, "MachTask::%s (%p): thread exiting...",
907                   __FUNCTION__, arg);
908  return NULL;
909}
910
911// So the TASK_DYLD_INFO used to just return the address of the all image infos
912// as a single member called "all_image_info". Then someone decided it would be
913// a good idea to rename this first member to "all_image_info_addr" and add a
914// size member called "all_image_info_size". This of course can not be detected
915// using code or #defines. So to hack around this problem, we define our own
916// version of the TASK_DYLD_INFO structure so we can guarantee what is inside
917// it.
918
919struct hack_task_dyld_info {
920  mach_vm_address_t all_image_info_addr;
921  mach_vm_size_t all_image_info_size;
922};
923
924nub_addr_t MachTask::GetDYLDAllImageInfosAddress(DNBError &err) {
925  struct hack_task_dyld_info dyld_info;
926  mach_msg_type_number_t count = TASK_DYLD_INFO_COUNT;
927  // Make sure that COUNT isn't bigger than our hacked up struct
928  // hack_task_dyld_info.
929  // If it is, then make COUNT smaller to match.
930  if (count > (sizeof(struct hack_task_dyld_info) / sizeof(natural_t)))
931    count = (sizeof(struct hack_task_dyld_info) / sizeof(natural_t));
932
933  task_t task = TaskPortForProcessID(err);
934  if (err.Success()) {
935    err = ::task_info(task, TASK_DYLD_INFO, (task_info_t)&dyld_info, &count);
936    if (err.Success()) {
937      // We now have the address of the all image infos structure
938      return dyld_info.all_image_info_addr;
939    }
940  }
941  return INVALID_NUB_ADDRESS;
942}
943
944//----------------------------------------------------------------------
945// MachTask::AllocateMemory
946//----------------------------------------------------------------------
947nub_addr_t MachTask::AllocateMemory(size_t size, uint32_t permissions) {
948  mach_vm_address_t addr;
949  task_t task = TaskPort();
950  if (task == TASK_NULL)
951    return INVALID_NUB_ADDRESS;
952
953  DNBError err;
954  err = ::mach_vm_allocate(task, &addr, size, TRUE);
955  if (err.Status() == KERN_SUCCESS) {
956    // Set the protections:
957    vm_prot_t mach_prot = VM_PROT_NONE;
958    if (permissions & eMemoryPermissionsReadable)
959      mach_prot |= VM_PROT_READ;
960    if (permissions & eMemoryPermissionsWritable)
961      mach_prot |= VM_PROT_WRITE;
962    if (permissions & eMemoryPermissionsExecutable)
963      mach_prot |= VM_PROT_EXECUTE;
964
965    err = ::mach_vm_protect(task, addr, size, 0, mach_prot);
966    if (err.Status() == KERN_SUCCESS) {
967      m_allocations.insert(std::make_pair(addr, size));
968      return addr;
969    }
970    ::mach_vm_deallocate(task, addr, size);
971  }
972  return INVALID_NUB_ADDRESS;
973}
974
975//----------------------------------------------------------------------
976// MachTask::DeallocateMemory
977//----------------------------------------------------------------------
978nub_bool_t MachTask::DeallocateMemory(nub_addr_t addr) {
979  task_t task = TaskPort();
980  if (task == TASK_NULL)
981    return false;
982
983  // We have to stash away sizes for the allocations...
984  allocation_collection::iterator pos, end = m_allocations.end();
985  for (pos = m_allocations.begin(); pos != end; pos++) {
986    if ((*pos).first == addr) {
987      size_t size = (*pos).second;
988      m_allocations.erase(pos);
989#define ALWAYS_ZOMBIE_ALLOCATIONS 0
990      if (ALWAYS_ZOMBIE_ALLOCATIONS ||
991          getenv("DEBUGSERVER_ZOMBIE_ALLOCATIONS")) {
992        ::mach_vm_protect(task, addr, size, 0, VM_PROT_NONE);
993        return true;
994      } else
995        return ::mach_vm_deallocate(task, addr, size) == KERN_SUCCESS;
996    }
997  }
998  return false;
999}
1000
1001void MachTask::TaskPortChanged(task_t task)
1002{
1003  m_task = task;
1004
1005  // If we've just exec'd to a new process, and it
1006  // is started suspended, we'll need to do two
1007  // task_resume's to get the inferior process to
1008  // continue.
1009  if (m_exec_will_be_suspended)
1010    m_do_double_resume = true;
1011  else
1012    m_do_double_resume = false;
1013  m_exec_will_be_suspended = false;
1014}
1015