#include <errno.h>
#include <string.h>             // strcmp, strerror
#include <sys/utsname.h>        // uname

#include "liboffsetfinder64.hpp"
#include "getoffsets.h"

static offsets_t off;
static bool didInit = false;
static tihmstar::offsetfinder64* finder = 0;

offsets_t* get_offsets()
{
  if (!didInit){
    finder = new tihmstar::offsetfinder64("/System/Library/Caches/com.apple.kernelcaches/kernelcache");

    off.base                               = 0xfffffff007004000;
    off.sizeof_task                         = (kptr_t)finder->find_sizeof_task();
    off.task_itk_self                       = (kptr_t)finder->find_task_itk_self();
    off.task_itk_registered                 = (kptr_t)finder->find_task_itk_registered();
    off.task_bsd_info                       = (kptr_t)finder->find_task_bsd_info();
    off.proc_ucred                          = (kptr_t)finder->find_proc_ucred();
    off.vm_map_hdr                          = (kptr_t)finder->find_vm_map_hdr();
    off.ipc_space_is_task                   = (kptr_t)finder->find_ipc_space_is_task();
    off.realhost_special                    = 0x10;
    off.iouserclient_ipc                    = (kptr_t)finder->find_iouserclient_ipc();
    off.vtab_get_retain_count               = (kptr_t)finder->find_vtab_get_retain_count();
    off.vtab_get_external_trap_for_index    = (kptr_t)finder->find_vtab_get_external_trap_for_index();
    off.zone_map                            = (kptr_t)finder->find_zone_map();
    off.kernel_map                          = (kptr_t)finder->find_kernel_map();
    off.kernel_task                         = (kptr_t)finder->find_kernel_task();
    off.realhost                            = (kptr_t)finder->find_realhost();
    off.copyin                              = (kptr_t)finder->find_copyin();
    off.copyout                             = (kptr_t)finder->find_copyout();
    off.chgproccnt                          = (kptr_t)finder->find_chgproccnt();
    off.kauth_cred_ref                      = (kptr_t)finder->find_kauth_cred_ref();
    off.ipc_port_alloc_special              = (kptr_t)finder->find_ipc_port_alloc_special();
    off.ipc_kobject_set                     = (kptr_t)finder->find_ipc_kobject_set();
    off.ipc_port_make_send                  = (kptr_t)finder->find_ipc_port_make_send();
    off.osserializer_serialize              = (kptr_t)finder->find_osserializer_serialize();
    off.rop_ldr_x0_x0_0x10                  = (kptr_t)finder->find_rop_ldr_x0_x0_0x10();

    didInit = true;
  }
  return &off;
}

kptr_t find_symbol(const char* symbol) {
  if (!didInit){
    finder = new tihmstar::offsetfinder64("/System/Library/Caches/com.apple.kernelcaches/kernelcache");
    didInit = true;
  }
  return (kptr_t)finder->find_sym(symbol);
}

