Results 1 to 1 of 1
  1. #1
    Dwar
    Dwar is offline
    Veteran Dwar's Avatar
    Join Date
    2010 Mar
    Posts
    2,222
    Thanks Thanks Given 
    211
    Thanks Thanks Received 
    2,230
    Thanked in
    292 Posts
    Rep Power
    10

    [C++] Memory-writing functions

    Snippets for writing bytes to specified memory address

    WriteMemory - write an byte-array to memory-address.
    WriteJump - both arguments are addresses, where to jump from and where to jump to.
    WriteNop - address and how many to write.
     #ifndef MEMUTILS_H
    #define MEMUTILS_H

    BOOL WriteMemory( DWORD dwAddress, const void* cpvPatch, DWORD dwSize )
    {
    DWORD dwProtect;

    if( VirtualProtect( (void*)dwAddress, dwSize, PAGE_READWRITE, &dwProtect ) ) //Unprotect the memory
    memcpy( (void*)dwAddress, cpvPatch, dwSize ); //Write our patch
    else
    return false; //Failed to unprotect, so return false..

    return VirtualProtect( (void*)dwAddress, dwSize, dwProtect, new DWORD ); //Reprotect the memory
    }

    BOOL WriteJump( DWORD From, DWORD To )
    {
    if( To < From + 128 && To > From - 128 ) //Short jump
    {
    BYTE bpJump[2] = { 0xEB, ( To - From ) - 2 }; //Calculate opcode

    return WriteMemory( From, bpJump, 2 );
    }
    else //Far jump
    {
    BYTE bpJump[5] = { 0xE9, 0x00, 0x00, 0x00, 0x00 };
    *(DWORD*)&bpJump[1] = ( To - From ) - 5; //Calculate jump

    return WriteMemory( From, bpJump, 5 );
    }

    return false; //If we end up here, something went horribly wrong
    }

    BOOL WriteNop( DWORD dwAddress, DWORD dwAmount )
    {
    BYTE bpNops[100]; //100 just incase I wanna do some gigantic NOPing
    memset( bpNops, 0x90, 100 ); //Fill byte-array with NOPs

    return WriteMemory( dwAddress, bpNops, dwAmount );
    }

    #endif
    Please, post your questions on forum, not by PM or mail

    I spend my time, so please pay a little bit of your time to keep world in equilibrium

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •