bool inject_trap_mem(drakvuf_t drakvuf, drakvuf_trap_t* trap, bool guard2)
{
    struct wrapper* s = (struct wrapper*)g_hash_table_lookup(drakvuf->memaccess_lookup_gfn, &trap->memaccess.gfn);
 
    // We already have a trap registered on this page
    // check if type matches, if so, add trap to the list
    if (s)
    {
        drakvuf_trap_t* havetrap = (drakvuf_trap_t*)s->traps->data;
        if (havetrap->type != trap->type)
        {
            PRINT_DEBUG("Failed to add memaccess trap as gfn is already trapped!\n");
            return 0;
        }
 
        /*
         * Guard2 types are protecting remapped gfns, thus when hit
         * these need to be swapped to the altp2m_idr view.
         */
        s->memaccess.guard2 = guard2;
 
        if ( s->memaccess.access != trap->memaccess.access )
        {
 
            vmi_mem_access_t update_access = (s->memaccess.access | trap->memaccess.access);
            status_t ret = vmi_set_mem_event(drakvuf->vmi, trap->memaccess.gfn, update_access, drakvuf->altp2m_idx);
 
            if ( ret == VMI_FAILURE )
            {
                PRINT_DEBUG("*** FAILED TO SET MEMORY TRAP @ PAGE %lu ***\n", trap->memaccess.gfn);
                return 0;
            }
 
            s->memaccess.access = update_access;
        }
 
        s->traps = g_slist_prepend(s->traps, trap);
        g_hash_table_insert(drakvuf->memaccess_lookup_trap, trap, s);
        return 1;
    }
    else
    {
        s = (struct wrapper*)g_slice_alloc0(sizeof(struct wrapper));
        s->drakvuf = drakvuf;
        s->traps = g_slist_prepend(s->traps, trap);
        s->memaccess.gfn = trap->memaccess.gfn;
        s->memaccess.access = trap->memaccess.access;
 
        /*
         * Guard2 types are protecting remapped gfns, thus when hit
         * these need to be swapped to the altp2m_idr view.
         */
        s->memaccess.guard2 = guard2;
 
        status_t ret = vmi_set_mem_event(drakvuf->vmi, trap->memaccess.gfn, trap->memaccess.access, drakvuf->altp2m_idx);
        if ( ret == VMI_FAILURE )
        {
            PRINT_DEBUG("*** FAILED TO SET MEMORY TRAP @ PAGE %lu ***\n",
                trap->memaccess.gfn);
            g_slist_free(s->traps);
            g_slice_free(struct wrapper, s);
            return 0;
        }
 
        g_hash_table_insert(drakvuf->memaccess_lookup_gfn, g_memdup_compat(&s->memaccess.gfn, sizeof(addr_t)), s);
        g_hash_table_insert(drakvuf->memaccess_lookup_trap, trap, s);
    }
 
    return 1;
}

🌱 Back to Garden