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