userclient_hv_trap.m 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. @import Darwin;
  2. @import Foundation;
  3. typedef io_object_t io_connect_t;
  4. kern_return_t IOConnectTrap6(io_connect_t connect, uint32_t index, uintptr_t p1, uintptr_t p2,
  5. uintptr_t p3, uintptr_t p4, uintptr_t p5, uintptr_t p6);
  6. extern mach_port_t bootstrap_port;
  7. kern_return_t bootstrap_look_up(mach_port_t bp, const char* service_name, mach_port_t* sp);
  8. static mach_port_t gUserClient;
  9. static uint64_t gCodePtrs[14];
  10. static uint64_t gDiscriminant;
  11. static int init_hv_trap() {
  12. NSError* nserror = nil;
  13. NSString* inStr = [NSString stringWithContentsOfFile:@"/tmp/zhuowei_portinfo"
  14. encoding:NSUTF8StringEncoding
  15. error:&nserror];
  16. if (!inStr) {
  17. NSLog(@"Error opening portinfo: %@", nserror);
  18. return 1;
  19. }
  20. NSArray<NSString*>* parts = [inStr componentsSeparatedByString:@"\n"];
  21. int target_pid = parts[0].intValue;
  22. mach_port_t target_task = 0;
  23. kern_return_t err;
  24. err = bootstrap_look_up(bootstrap_port, "com.worthdoingbadly.hypervisor", &target_task);
  25. if (err) {
  26. NSLog(@"Can't lookup bootstrap: %d; trying task_for_pid\n", err);
  27. err = task_for_pid(mach_task_self_, target_pid, &target_task);
  28. if (err) {
  29. NSLog(@"Failed to get task port: %s\n", mach_error_string(err));
  30. return 1;
  31. }
  32. }
  33. if (target_task == MACH_PORT_NULL) {
  34. NSLog(@"Can't get task port for pid %d\n", target_pid);
  35. return 1;
  36. }
  37. mach_port_name_t remote_port_id = parts[1].intValue;
  38. mach_port_t user_client = 0;
  39. mach_msg_type_name_t user_client_type = 0;
  40. err = mach_port_extract_right(target_task, remote_port_id, MACH_MSG_TYPE_COPY_SEND, &user_client,
  41. &user_client_type);
  42. if (err) {
  43. NSLog(@"Failed to extract user client port: %s\n", mach_error_string(err));
  44. return 1;
  45. }
  46. NSLog(@"ok port = %u", user_client);
  47. gDiscriminant = strtoull(parts[2].UTF8String, nil, 0x10);
  48. for (int i = 0; i < 14; i++) {
  49. gCodePtrs[i] = strtoull(parts[3 + i].UTF8String, nil, 0x10);
  50. }
  51. gUserClient = user_client;
  52. return 0;
  53. }
  54. kern_return_t hv_trap(unsigned int hv_call, void* hv_arg) {
  55. static dispatch_once_t init_token;
  56. dispatch_once(&init_token, ^{
  57. init_hv_trap();
  58. });
  59. if (gUserClient == 0) {
  60. // TODO(zhuowei): make an error code??
  61. return 0x1337;
  62. }
  63. uint64_t signed_code_ptr = gCodePtrs[hv_call];
  64. return IOConnectTrap6(gUserClient, /*index=*/0, /*arg1*/ (uintptr_t)hv_arg, /*arg2*/ 0,
  65. signed_code_ptr, gDiscriminant, 0, 0);
  66. }