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