//
//  nvramutils.c
//  Chimera
//
//  Created by CoolStar on 9/3/19.
//  Copyright © 2019 Electra Team. All rights reserved.
//

#include "cutils.h"
#include <ptrauth.h>
#include <dlfcn.h>

uint64_t lookup_key_in_dicts(dict_entry_t *os_dict_entries, uint32_t count, uint64_t key){
    uint64_t value = 0;
    for (int i = 0; i < count; ++i){
        if (os_dict_entries[i].key == key){
            value = os_dict_entries[i].value;
            break;
        }
    }
    return value;
}

bool isArm64e(void){
#if __arm64e__
    return true;
#else
    return false;
#endif
}

uint64_t signPtr(uint64_t data, uint64_t key) {
    return (uint64_t)ptrauth_sign_unauthenticated((void *)data, ptrauth_key_asia, key);
}

uint64_t getLr(arm_thread_state64_t state){
    return arm_thread_state64_get_lr(state);
}

uint64_t getPc(arm_thread_state64_t state){
    return arm_thread_state64_get_pc(state);
}

void setPc(arm_thread_state64_t *state, uint64_t pc){
    void *ptr = ptrauth_sign_unauthenticated((void *)pc, ptrauth_key_asia, 0);
    
    arm_thread_state64_t localState;
    memcpy(&localState, state, sizeof(arm_thread_state64_t));
    
    arm_thread_state64_set_pc_fptr(localState, ptr);
    memcpy(state, &localState, sizeof(arm_thread_state64_t));
}

uint64_t findSymbol(const char *symbol){
    return (uint64_t)ptrauth_strip(dlsym(RTLD_DEFAULT, symbol), ptrauth_key_asia);
}

#ifdef ENABLE_XPC
xpc_object_t xpc_bootstrap_pipe(void) {
    struct xpc_global_data *xpc_gd = _os_alloc_once_table[1].ptr;
    return xpc_gd->xpc_bootstrap_pipe;
}
#endif
