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