kern_utils.m 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <Foundation/Foundation.h>
  4. #include "helpers/kmem.h"
  5. #include "helpers/offsetof.h"
  6. #include "helpers/patchfinder64.h"
  7. #include "kern_utils.h"
  8. uint64_t proc_find(int pd, int tries) {
  9. while (tries-- > 0) {
  10. uint64_t ktask = rk64(offset_kernel_task);
  11. uint64_t kern_proc = rk64(ktask + offsetof_bsd_info);
  12. uint64_t proc = rk64(kern_proc + 0x08);
  13. while (proc) {
  14. uint32_t proc_pid = rk32(proc + 0x10);
  15. if (proc_pid == pd) {
  16. return proc;
  17. }
  18. proc = rk64(proc + 0x08);
  19. }
  20. }
  21. return 0;
  22. }
  23. uint64_t proc_find_by_name(const char *name) {
  24. uint64_t ktask = rk64(offset_kernel_task);
  25. uint64_t kern_proc = rk64(ktask + offsetof_bsd_info);
  26. uint64_t proc = rk64(kern_proc + 0x08);
  27. while (proc) {
  28. uint32_t pid = rk32(proc + 0x10);
  29. char proc_name[40] = { 0 };
  30. kread(proc + 0x26c, proc_name, 40);
  31. if (!strcmp(name, proc_name)) {
  32. return proc;
  33. }
  34. proc = rk64(proc + 0x08);
  35. }
  36. return 0;
  37. }
  38. CACHED_FIND(uint64_t, our_task_addr) {
  39. uint64_t our_proc = proc_find(getpid(), 3);
  40. if (our_proc == 0) {
  41. NSLog(@"failed to find our_task_addr!");
  42. return -1;
  43. }
  44. return rk64(our_proc + offsetof_task);
  45. }
  46. uint64_t find_port(mach_port_name_t port) {
  47. uint64_t task_addr = our_task_addr();
  48. if (task_addr == -1) {
  49. return -1;
  50. }
  51. uint64_t itk_space = rk64(task_addr + offsetof_itk_space);
  52. uint64_t is_table = rk64(itk_space + offsetof_ipc_space_is_table);
  53. uint32_t port_index = port >> 8;
  54. const int sizeof_ipc_entry_t = 0x18;
  55. uint64_t port_addr = rk64(is_table + (port_index * sizeof_ipc_entry_t));
  56. return port_addr;
  57. }