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