예제 #1
0
int
main()
{
    int round;
    int t;

    GET_NTDLL(NtTerminateProcess, (IN HANDLE ProcessHandle OPTIONAL,
                                   IN NTSTATUS ExitStatus));

    INIT();

    for (round = 0; round < ROUNDS; round++) {
#ifdef VERBOSE
        print("round %d\n", round);
#endif
        if (round > 0) {
            /* clean up first */
            NtTerminateProcess(0 /* everyone but me */, 666);
#ifdef VERBOSE
            print("all alone again %d\n", round);
#endif VERBOSE
        }

        global_started = 0;
        global_finished = 0;

        for (t = 0; t < TOTAL_THREADS; t++) {
            thread[t] = (HANDLE)create_thread(executor);
            if (thread[t] == NULL)
                print("GLE: %d\n", GetLastError());
            assert(thread[t] != NULL);
        }

#ifdef VERBOSE
        print("started %d threads\n", TOTAL_THREADS);
#else
        print("started some threads\n");
#endif

        /* wait for some to start */
        while (global_started < WAIT_TO_START)
            YIELD();

        /* wait for some work to get done */
        while (global_finished < WAIT_TO_FINISH)
            YIELD();
#ifdef VERBOSE
        print("some %d work, done %d\n", global_started, global_finished);
#endif
    }

    print("done\n");
    return 0;
}
예제 #2
0
NTSTATUS WINAPI
redirect_RtlDeleteCriticalSection(RTL_CRITICAL_SECTION* crit)
{
    GET_NTDLL(RtlDeleteCriticalSection, (RTL_CRITICAL_SECTION *crit));
    LOG(GLOBAL, LOG_LOADER, 2, "%s: "PFX"\n", __FUNCTION__, crit);
    IF_CLIENT_INTERFACE(ASSERT(get_own_teb()->ProcessEnvironmentBlock ==
                               get_private_peb() || standalone_library));
    if (crit == NULL)
        return STATUS_INVALID_PARAMETER;
    if (crit->DebugInfo != NULL) {
        if (is_dynamo_address((byte *)crit->DebugInfo))
            wrapped_dr_free((byte *)crit->DebugInfo);
        else {
            /* somehow a critsec created elsewhere is being destroyed here! */
            ASSERT_NOT_REACHED();
            return RtlDeleteCriticalSection(crit);
        }
    }
    close_handle(crit->LockSemaphore);
    memset(crit, 0, sizeof(*crit));
    crit->LockCount = -1;
    return STATUS_SUCCESS;
}
예제 #3
0
static DWORD WINAPI
ThreadProc1(LPVOID parm)
{
    LARGE_INTEGER waittime;
    NTSTATUS res;
    HANDLE e;
    GET_NTDLL(NtWaitForSingleObject,
              (IN HANDLE ObjectHandle, IN BOOLEAN Alertable, IN PLARGE_INTEGER TimeOut));
    print("starting thread...\n");

    e = CreateEvent(NULL, FALSE, FALSE, "foo");
    waittime.QuadPart = -((int)500 * TIMER_UNITS_PER_MILLISECOND);
    control = 1;
    do {
        res = NtWaitForSingleObject(e, false /* not alertable */, &waittime);
    } while (control);
    __asm {
        mov   reg_eax, eax
        mov   reg_ebx, ebx
        mov   reg_ecx, ecx
        mov   reg_edx, edx
        mov   reg_edi, edi
        mov   reg_esi, esi
        mov   reg_esp, esp
        mov   reg_ebp, ebp
    }
    print("res is " PFMT " but shouldn't get here!!!\n", res);
#if VERBOSE
    print("registers: " PFMT " " PFMT " " PFMT " " PFMT " " PFMT " " PFMT " " PFMT
          " " PFMT "\n",
          reg_eax, reg_ebx, reg_ecx, reg_edx, reg_edi, reg_esi, reg_esp, reg_ebp);
#endif
    CloseHandle(e);

    print("exiting thread\n");
    return -1;
}
예제 #4
0
파일: drmarker.c 프로젝트: AVGirl/dynamorio
/* For 32-bit build, supports looking for x64 marker (in WOW64 process).
 * For 64-bit build, only supports looking for x64 marker.
 */
static int
read_and_verify_dr_marker_common(HANDLE process, dr_marker_t *marker, bool x64)
{
    byte buf[8]; /* only needs to be 5, but dword pad just in case */
    size_t res;
    void *target = NULL;
#if !defined(NOT_DYNAMORIO_CORE) && !defined(NOT_DYNAMORIO_CORE_PROPER)
    GET_NTDLL(DR_MARKER_HOOKED_FUNCTION, DR_MARKER_HOOKED_FUNCTION_ARGS);
    void *hook_func = (void *)DR_MARKER_HOOKED_FUNCTION;
#else
    if (IF_X64_ELSE(!x64, x64 && !is_wow64_process(NT_CURRENT_PROCESS)))
        return DR_MARKER_ERROR;
    if (x64) {
# ifndef X64
        uint64 hook_func = get_proc_address_64
            (get_module_handle_64(L_DR_MARKER_HOOKED_DLL),
             DR_MARKER_HOOKED_FUNCTION_STRING);
        uint64 landing_pad = 0;
        if (hook_func == 0)
            return DR_MARKER_ERROR;
        if (!NT_SUCCESS(nt_wow64_read_virtual_memory64(process, hook_func, buf, 5, &res))
            || res != 5) {
            return DR_MARKER_ERROR;
        }
        if (buf[0] != OP_jmp_byte)
            return DR_MARKER_NOT_FOUND;

        /* jmp offset + EIP (after jmp = hook_func + size of jmp (5 bytes)) */
        /* for 64-bit, the target is stored in front of the trampoline */
        landing_pad = *(int *)&buf[1] + hook_func + 5 - 8;
         if (!NT_SUCCESS(nt_wow64_read_virtual_memory64(process, landing_pad, buf, 8,
                                                        &res)) ||
            res != 8U)
            return DR_MARKER_ERROR;
        /* trampoline address is stored at the top of the landing pad for 64-bit */
        target = (void *)PAGE_START(*(ptr_int_t *)buf);
    } else {
# endif /* !X64 */
        void *hook_func = (void *)GetProcAddress(GetModuleHandle(DR_MARKER_HOOKED_DLL),
                                                 DR_MARKER_HOOKED_FUNCTION_STRING);
#endif
        void *landing_pad;
        if (hook_func == NULL)
            return DR_MARKER_ERROR;
        if (!READ_FUNC(process, hook_func, buf, 5, &res) || res != 5)
            return DR_MARKER_ERROR;
        if (buf[0] != OP_jmp_byte)
            return DR_MARKER_NOT_FOUND;

        /* jmp offset + EIP (after jmp = hook_func + size of jmp (5 bytes)) */
        landing_pad = (void *)(*(int *)&buf[1] + (ptr_int_t)hook_func + 5);
        /* for 64-bit, the target is stored in front of the trampoline */
        if (x64)
            landing_pad = (byte *)landing_pad - 8;
        /* see emit_landing_pad_code() for layout of landing pad */
        if (!READ_FUNC(process, landing_pad, buf, (x64 ? 8 : 5), &res) ||
            res != (x64 ? 8U : 5U))
            return DR_MARKER_ERROR;
        if (x64) {
            /* trampoline address is stored at the top of the landing pad for 64-bit */
            target = (void *)PAGE_START(*(ptr_int_t *)buf);
        } else {
            /* jmp offset + EIP (after jmp = landing_pad + size of jmp (5 bytes)) */
            target = (void *)PAGE_START(*(int *)&buf[1] + (ptr_int_t)landing_pad + 5);
        }
#if defined(NOT_DYNAMORIO_CORE) || defined(NOT_DYNAMORIO_CORE_PROPER)
    }
#endif

    if (target == NULL)
        return DR_MARKER_ERROR;
    if (!READ_FUNC(process, target, marker, sizeof(dr_marker_t), &res) ||
        res != sizeof(dr_marker_t)) {
        return DR_MARKER_NOT_FOUND;
    }

    if (dr_marker_verify(process, marker)) {
        return DR_MARKER_FOUND;
    }

    return DR_MARKER_NOT_FOUND; /* probably some other hooker */
}
예제 #5
0
/* FIXME - like inject_into_thread we assume esp, but we could allocate our
 * own stack in the child and swap to that for transparency. */
bool
inject_into_new_process(HANDLE phandle, char *dynamo_path, bool map,
                        uint inject_location, void *inject_address)
{
    void *hook_target = NULL, *hook_location = NULL;
    uint old_prot; 
    size_t num_bytes_out;
    byte hook_buf[5];

    /* Possible child hook points */
    GET_NTDLL(KiUserApcDispatcher, (IN PVOID Unknown1, 
                                    IN PVOID Unknown2, 
                                    IN PVOID Unknown3, 
                                    IN PVOID ContextStart, 
                                    IN PVOID ContextBody));
    GET_NTDLL(KiUserExceptionDispatcher, (IN PVOID Unknown1, 
                                          IN PVOID Unknown2));

    /* Only ones that work, though I have hopes for KiUserException if can
     * find a better spot to trigger the exception, or we should implement
     * KiUserApc map requirement. */
    ASSERT_NOT_IMPLEMENTED(INJECT_LOCATION_IS_LDR(inject_location));
    switch(inject_location) {
    case INJECT_LOCATION_LdrLoadDll:
    case INJECT_LOCATION_LdrpLoadDll:
    case INJECT_LOCATION_LdrCustom:
    case INJECT_LOCATION_LdrpLoadImportModule:
    case INJECT_LOCATION_LdrDefault:
        /* caller provides the ldr address to use */
        ASSERT(inject_address != NULL);
        hook_location = inject_address;
        if (hook_location == NULL) {
            goto error;
        }
        break;
    case INJECT_LOCATION_KiUserApc:
        hook_location = (void *)KiUserApcDispatcher;
        ASSERT(map);
        break;
    case INJECT_LOCATION_KiUserException:
        hook_location = (void *)KiUserExceptionDispatcher;
        break;
    default:
        ASSERT_NOT_REACHED();
        goto error;
    }

    /* read in code at hook */
    if (!nt_read_virtual_memory(phandle, hook_location, hook_buf,
                                sizeof(hook_buf), &num_bytes_out) ||
        num_bytes_out != sizeof(hook_buf)) {
        goto error;
    }

    if (map) {
        hook_target = NULL; /* for compiler */
        /* NYI see case 102, plan is to remote map in our dll, link and rebase if
         * necessary and hook to a routine in our dll */
        ASSERT_NOT_IMPLEMENTED(false);
    } else {
        byte *remote_code_buffer = NULL, *remote_data_buffer;
        /* max usage for local_buf is for writing the dr library name
         * 2*MAX_PATH (unicode) + sizoef(UNICODE_STRING) + 2, round up to
         * 3*MAX_PATH to be safe */
        byte local_buf[3*MAX_PATH];
        byte *cur_local_pos, *cur_remote_pos, *jmp_fixup1, *jmp_fixup2;
        char *takeover_func = "dynamorio_app_init_and_early_takeover";
        PUNICODE_STRING mod, mod_remote;
        PANSI_STRING func, func_remote;
        int res;
        size_t num_bytes_in;

        GET_NTDLL(LdrLoadDll, (IN PCWSTR PathToFile OPTIONAL,
                               IN PULONG Flags OPTIONAL,
                               IN PUNICODE_STRING ModuleFileName,
                               OUT PHANDLE ModuleHandle));
        GET_NTDLL(LdrGetProcedureAddress, (IN HANDLE ModuleHandle,
                                           IN PANSI_STRING ProcedureName OPTIONAL,
                                           IN ULONG Ordinal OPTIONAL,
                                           OUT FARPROC *ProcedureAddress));
#define GET_PROC_ADDR_BAD_ADDR 0xffbadd11
        GET_NTDLL(NtProtectVirtualMemory, (IN HANDLE ProcessHandle,
                                           IN OUT PVOID *BaseAddress,
                                           IN OUT PULONG ProtectSize,
                                           IN ULONG NewProtect,
                                           OUT PULONG OldProtect));
        GET_NTDLL(NtContinue, (IN PCONTEXT Context,
                               IN BOOLEAN TestAlert));

        /* get buffer for emitted code and data */
        if (!NT_SUCCESS(nt_remote_allocate_virtual_memory(phandle, &remote_code_buffer,
                                                          2*PAGE_SIZE, PAGE_READWRITE,
                                                          MEM_COMMIT))) {
            goto error;
        }
        remote_data_buffer = remote_code_buffer + PAGE_SIZE;
        
        /* write data */
        /* FIXME the two writes are similar (unicode vs ascii), could combine */
        /* First UNICODE_STRING to library */
        cur_remote_pos = remote_data_buffer;
        cur_local_pos = local_buf;
        ASSERT_ROOM(cur_local_pos, local_buf, sizeof(UNICODE_STRING));
        mod = (PUNICODE_STRING)cur_local_pos;
        memset(mod, 0, sizeof(UNICODE_STRING));
        cur_local_pos += sizeof(UNICODE_STRING);
        mod->Buffer = (wchar_t *)(cur_remote_pos + (cur_local_pos - local_buf));
        ASSERT_ROOM(cur_local_pos, local_buf, 2*MAX_PATH+2 /* plus null */);
        res = snwprintf((wchar_t *)cur_local_pos, 2*MAX_PATH, L"%hs", dynamo_path);
        ASSERT(res > 0);
        if (res > 0) {
            cur_local_pos += (2*res);
            ASSERT_TRUNCATE(mod->Length, ushort, 2*res);
            mod->Length = (ushort)(2*res);
            mod->MaximumLength = (ushort)(2*res);
        }
        /* ensure NULL termination, just in case */
        *(wchar_t *)cur_local_pos = L'\0';
        cur_local_pos += sizeof(wchar_t);
        /* write to remote process */
        num_bytes_in = cur_local_pos - local_buf;
        if (!nt_write_virtual_memory(phandle, cur_remote_pos, local_buf,
                                     num_bytes_in, &num_bytes_out) ||
            num_bytes_out != num_bytes_in) {
            goto error;
        }
        mod_remote = (PUNICODE_STRING)cur_remote_pos;
        cur_remote_pos += num_bytes_out;

        /* now write init/takeover func */
        cur_local_pos = local_buf;
        ASSERT_ROOM(cur_local_pos, local_buf, sizeof(ANSI_STRING));
        func = (PANSI_STRING)cur_local_pos;
        memset(func, 0, sizeof(ANSI_STRING));
        cur_local_pos += sizeof(ANSI_STRING);
        func->Buffer = (PCHAR) cur_remote_pos + (cur_local_pos - local_buf);
        ASSERT_ROOM(cur_local_pos, local_buf, strlen(takeover_func)+1);
        strncpy((char *)cur_local_pos, takeover_func, strlen(takeover_func));
        cur_local_pos += strlen(takeover_func);
        ASSERT_TRUNCATE(func->Length, ushort, strlen(takeover_func));
        func->Length = (ushort)strlen(takeover_func);
        func->MaximumLength = (ushort)strlen(takeover_func);
        *cur_local_pos++ = '\0'; /* ensure NULL termination, just in case */
        /* write to remote_process */
        num_bytes_in = cur_local_pos - local_buf;
        if (!nt_write_virtual_memory(phandle, cur_remote_pos, local_buf,
                                     num_bytes_in, &num_bytes_out) ||
            num_bytes_out != num_bytes_in) {
            goto error;
        }
        func_remote = (PANSI_STRING)cur_remote_pos;
        cur_remote_pos += num_bytes_out;
        
        /* now make data page read only */
        res = nt_remote_protect_virtual_memory(phandle, remote_data_buffer, 
                                               PAGE_SIZE, PAGE_READONLY,
                                               &old_prot);
        ASSERT(res);
        
#define INSERT_INT(value)         \
  *(int *)cur_local_pos = value;  \
  cur_local_pos += sizeof(int)

#define PUSH_IMMEDIATE(value)     \
  *cur_local_pos++ = PUSH_IMM32;  \
  INSERT_INT(value)

#define PUSH_SHORT_IMMEDIATE(value)     \
  *cur_local_pos++ = PUSH_IMM8;         \
  *cur_local_pos++ = value

#define MOV_ESP_TO_EAX()                \
  *cur_local_pos++ = MOV_RM32_2_REG32;  \
  *cur_local_pos++ = MOV_ESP_2_EAX_RM

/* FIXME - all values are small use imm8 version */
#define ADD_TO_EAX(value)               \
  *cur_local_pos++ = ADD_EAX_IMM32;     \
  INSERT_INT(value)

#define INSERT_REL32_ADDRESS(target)    \
  IF_X64(ASSERT_NOT_IMPLEMENTED(false)); \
  INSERT_INT((int)(ptr_int_t)((byte *)target - \
                              (((cur_local_pos - local_buf)+4)+cur_remote_pos)))

#define CALL(target_func)               \
  *cur_local_pos++ = CALL_REL32;        \
  INSERT_REL32_ADDRESS(target_func)

/* ecx will hold OldProtection afterwards */
#define PROT_IN_ECX 0xbad15bad /* doesn't match a PAGE_* define */
#define CHANGE_PROTECTION(start, size, new_protection)                \
  *cur_local_pos++ = PUSH_EAX; /* OldProtect slot */                  \
  MOV_ESP_TO_EAX(); /* get &OldProtect */                             \
  IF_X64(ASSERT_NOT_IMPLEMENTED(false));                              \
  PUSH_IMMEDIATE((int)(ALIGN_FORWARD(start+size, PAGE_SIZE) -         \
                 ALIGN_BACKWARD(start, PAGE_SIZE))); /* ProtectSize */ \
  PUSH_IMMEDIATE((int)ALIGN_BACKWARD(start, PAGE_SIZE)); /* BaseAddress */ \
  *cur_local_pos++ = PUSH_EAX; /* arg 5 &OldProtect */                \
  if (new_protection == PROT_IN_ECX) {                                \
      *cur_local_pos++ = PUSH_ECX; /* arg 4 NewProtect */             \
  } else {                                                            \
      PUSH_IMMEDIATE(new_protection); /* arg 4 NewProtect */          \
  }                                                                   \
  ADD_TO_EAX(-4); /* get &ProtectSize */                              \
  *cur_local_pos++ = PUSH_EAX; /* arg 3 &ProtectSize */               \
  ADD_TO_EAX(-4); /* get &BaseAddress */                              \
  *cur_local_pos++ = PUSH_EAX; /* arg 2 &BaseAddress */               \
  PUSH_IMMEDIATE((int)(ptr_int_t)NT_CURRENT_PROCESS); /* arg ProcessHandle */ \
  CALL(NtProtectVirtualMemory);                                       \
  /* no error checking, can't really do anything about it, FIXME */   \
  /* stdcall so just the three slots we made for the ptr arguments    \
   * left on the stack */                                             \
  *cur_local_pos++ = POP_ECX; /* pop BaseAddress */                   \
  *cur_local_pos++ = POP_ECX; /* pop ProtectSize */                   \
  *cur_local_pos++ = POP_ECX /* pop OldProtect into ecx */


        /* write code */
        /* xref case 3821, first call to a possibly hooked routine should be
         * more then 5 bytes into the page, which is satisfied (though is not
         * clear if any hookers would manage to get in first). */
        cur_remote_pos = remote_code_buffer;
        cur_local_pos = local_buf;
        hook_target = cur_remote_pos;
        /* for inject_location INJECT_LOCATION_Ldr* we stick the address used
         * at the start of the code for the child's use */
        if (INJECT_LOCATION_IS_LDR(inject_location)) {
            IF_X64(ASSERT_NOT_IMPLEMENTED(false));
            INSERT_INT((int)(ptr_int_t)inject_address);
            hook_target = cur_remote_pos + 4;  /* skip the address */
        }

#if DEBUG_LOOP
        *cur_local_pos++ = JMP_REL8;
        *cur_local_pos++ = 0xfe;
#endif

        /* save current state */
        *cur_local_pos++ = PUSHA;
        *cur_local_pos++ = PUSHF;

        /* restore trampoline, first make writable */
        CHANGE_PROTECTION(hook_location, 5, PAGE_EXECUTE_READWRITE);
        *cur_local_pos++ = MOV_IMM32_2_RM32; /* restore first 4 bytes of hook */
        *cur_local_pos++ = MOV_IMM_RM_ABS;
        IF_X64(ASSERT_NOT_IMPLEMENTED(false));
        INSERT_INT((int)(ptr_int_t)hook_location);
        INSERT_INT(*(int *)hook_buf);
        *cur_local_pos++ = MOV_IMM8_2_RM8; /* restore 5th byte of the hook */
        *cur_local_pos++ = MOV_IMM_RM_ABS;
        IF_X64(ASSERT_NOT_IMPLEMENTED(false));
        INSERT_INT((int)(ptr_int_t)hook_location+4);
        *cur_local_pos++ = hook_buf[4];
        /* hook restored, restore protection */
        CHANGE_PROTECTION(hook_location, 5, PROT_IN_ECX);

        if (inject_location == INJECT_LOCATION_KiUserException) {
            /* Making the first page of the image unreadable triggers an exception
             * to early to use the loader, might try pointing the import table ptr
             * to bad memory instead TOTRY, whatever we do should fixup here */
            ASSERT_NOT_IMPLEMENTED(false);
        }
        
        /* call LdrLoadDll to load dr library */
        *cur_local_pos++ = PUSH_EAX; /* need slot for OUT hmodule*/
        MOV_ESP_TO_EAX();
        *cur_local_pos++ = PUSH_EAX; /* arg 4 OUT *hmodule */
        IF_X64(ASSERT_NOT_IMPLEMENTED(false));
        PUSH_IMMEDIATE((int)(ptr_int_t)mod_remote); /* our library name */
        PUSH_SHORT_IMMEDIATE(0x0); /* Flags OPTIONAL */
        PUSH_SHORT_IMMEDIATE(0x0); /* PathToFile OPTIONAL */
        CALL(LdrLoadDll); /* see signature at decleration above */

        /* stdcall so removed args so top of stack is now the slot containing the
         * returned handle.  Use LdrGetProcedureAddress to get the address of the
         * dr init and takeover function. Is ok to call even if LdrLoadDll failed,
         * so we check for errors afterwards. */
        *cur_local_pos++ = POP_ECX; /* dr module handle */
        *cur_local_pos++ = PUSH_ECX; /* need slot for out ProcedureAddress */
        MOV_ESP_TO_EAX();
        *cur_local_pos++ = PUSH_EAX; /* arg 4 OUT *ProcedureAddress */
        PUSH_SHORT_IMMEDIATE(0x0); /* Ordinal OPTIONAL */
        IF_X64(ASSERT_NOT_IMPLEMENTED(false));
        PUSH_IMMEDIATE((int)(ptr_int_t)func_remote); /* func name */
        *cur_local_pos++ = PUSH_ECX; /* module handle */
        CALL(LdrGetProcedureAddress); /* see signature at decleration above */

        /* Top of stack is now the dr init and takeover function (stdcall removed
         * args). Check for errors and bail (FIXME debug build report somehow?) */
        *cur_local_pos++ = CMP_EAX_IMM32;
        INSERT_INT(STATUS_SUCCESS);
        *cur_local_pos++ = POP_EAX; /* dr init_and_takeover function */
        *cur_local_pos++ = JNZ_REL8; /* FIXME - should check >= 0 instead? */
        jmp_fixup1 = cur_local_pos++; /* jmp to after call below */
        /* Xref case 8373, LdrGetProcedureAdderss sometimes returns an
         * address of 0xffbadd11 even though it returned STATUS_SUCCESS */
        *cur_local_pos++ = CMP_EAX_IMM32;
        INSERT_INT(GET_PROC_ADDR_BAD_ADDR);
        *cur_local_pos++ = JZ_REL8; /* JZ == JE */
        jmp_fixup2 = cur_local_pos++; /* jmp to after call below */
        IF_X64(ASSERT_NOT_IMPLEMENTED(false));
        PUSH_IMMEDIATE((int)(ptr_int_t)remote_code_buffer); /* arg to takeover func */
        PUSH_IMMEDIATE(inject_location); /* arg to takeover func */
        *cur_local_pos++ = CALL_RM32; /* call EAX */
        *cur_local_pos++ = CALL_EAX_RM;
        *cur_local_pos++ = POP_ECX; /* cdecl so pop arg */
        *cur_local_pos++ = POP_ECX; /* cdecl so pop arg */
        /* Now patch the jnz above (if error) to go to here */
        ASSERT_TRUNCATE(*jmp_fixup1, byte, cur_local_pos - (jmp_fixup1+1));
        *jmp_fixup1 = (byte)(cur_local_pos - (jmp_fixup1+1)); /* target of jnz */
        ASSERT_TRUNCATE(*jmp_fixup2, byte, cur_local_pos - (jmp_fixup2+1));
        *jmp_fixup2 = (byte)(cur_local_pos - (jmp_fixup2+1)); /* target of jz */
        *cur_local_pos++ = POPF;
        *cur_local_pos++ = POPA;
        if (inject_location != INJECT_LOCATION_KiUserException) {
            /* jmp back to the hook location to resume execution */
            *cur_local_pos++ = JMP_REL32;
            INSERT_REL32_ADDRESS(hook_location);
        } else {
            /* we triggered the exception, so do an NtContinue back */
            /* see callback.c, esp+4 holds CONTEXT ** */
            *cur_local_pos++ = POP_EAX;  /* EXCEPTION_RECORD ** */
            *cur_local_pos++ = POP_EAX;  /* CONTEXT ** */
            PUSH_SHORT_IMMEDIATE(FALSE); /* arg 2 TestAlert */
            *cur_local_pos++ = MOV_RM32_2_REG32;
            *cur_local_pos++ = MOV_derefEAX_2_EAX_RM; /* CONTEXT * -> EAX */
            *cur_local_pos++ = PUSH_EAX; /* push CONTEXT * (arg 1) */
            CALL(NtContinue);
            /* should never get here, will be zeroed memory so will crash if
             * we do happen to get here, good enough reporting */
        }

        /* Our emitted code above is much less then the sizeof local_buf,
         * but we'll add a check here (after the fact so not robust if really
         * overflowed) that we didn't even come close (someon adding large amounts
         * of code should hit this. FIXME - do better? */
        ASSERT_ROOM(cur_local_pos, local_buf, MAX_PATH);
        num_bytes_in = cur_local_pos - local_buf;
        if (!nt_write_virtual_memory(phandle, cur_remote_pos, local_buf,
                                     num_bytes_in, &num_bytes_out) ||
            num_bytes_out != num_bytes_in) {
            goto error;
        }
        cur_remote_pos += num_bytes_out;
        /* now make code page rx */
        res = nt_remote_protect_virtual_memory(phandle, remote_code_buffer, 
                                               PAGE_SIZE, PAGE_EXECUTE_READ,
                                               &old_prot);
        ASSERT(res);

#undef INSERT_INT
#undef PUSH_IMMEDIATE
#undef PUSH_SHORT_IMMEDIATE
#undef MOV_ESP_TO_EAX
#undef ADD_TO_EAX
#undef INSERT_REL32_ADDRESS
#undef CALL
#undef PROT_IN_ECX
#undef CHANGE_PROTECTION
    }

    /* place hook */
    ASSERT(sizeof(hook_buf) == 5); /* standard 5 byte jmp rel32 hook */
    hook_buf[0] = JMP_REL32;
    IF_X64(ASSERT_NOT_IMPLEMENTED(false));
    *(int *)(&hook_buf[1]) = (int)((byte *)hook_target - ((byte *)hook_location + 5));
    if (!nt_remote_protect_virtual_memory(phandle, hook_location,
                                          sizeof(hook_buf),
                                          PAGE_EXECUTE_READWRITE, &old_prot)) {
        goto error;
    }
    if (!nt_write_virtual_memory(phandle, hook_location, hook_buf,
                                 sizeof(hook_buf), &num_bytes_out) ||
        num_bytes_out != sizeof(hook_buf)) {
        goto error;
    }
    if (!nt_remote_protect_virtual_memory(phandle, hook_location,
                                          sizeof(hook_buf),
                                          old_prot, &old_prot)) {
        goto error;
    }

    return true;

    error:
    /* we do not recover any changes in the child's address space */
    return false;
}