0

The file from resources is passed to function Change which should XOR each byte value, but then I get write access violation error.

INT CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
PSTR lpCmdLine, INT nCmdShow)
{
    HRSRC hRes = FindResource(NULL, L"FILE", RT_RCDATA);

    if (hRes == NULL)
    {
        // print error
    }

    DWORD resSize = SizeofResource(NULL, hRes);
    HGLOBAL resData = LoadResource(NULL, hRes);
    byte *file = reinterpret_cast<byte*>(LockResource(resData));

    Change(file, resSize);

    return 0;
}

void Change(byte *data, int size)
{
    for (int i = 0; i < size; ++i)
    {
        data[i] ^= 2;
    }
}
3
  • Did you check the return value of LockResource to ensure that it wasn't null? Commented Apr 5, 2017 at 18:58
  • In memory window I can see that file variable has the bytes from my file. Commented Apr 5, 2017 at 19:11
  • 4
    Resources are in a read-only segment of the executable. You can't modify memory taken by the resource. Commented Apr 5, 2017 at 19:50

1 Answer 1

2

Resources exist in read-only memory, you cannot write to them directly.

The only way to modify the contents of a resource is to use UpdateResource() (unless you WriteFile() directly to the executable file on disk), but you can't use either of those on a resource that belongs to an active running process, as the executable is locked by the OS.

So, the only way to do what you are attempting is to allocate a separate copy of the resource data in writable memory, and then you can do whatever you want with that copy, eg:

INT CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR lpCmdLine, INT nCmdShow)
{
    HRSRC hRes = FindResource(NULL, L"FILE", RT_RCDATA);
    if (hRes == NULL)
    {
        // print error
    }
    else
    {
        DWORD resSize = SizeofResource(NULL, hRes);
        HGLOBAL resData = LoadResource(NULL, hRes);
        LPVOID resDataPtr = LockResource(resData);

        byte *copy = new byte[resSize];
        memcpy(copy, resDataPtr, resSize);
        Change(copy, resSize);
        delete[] copy;
    }

    return 0;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Actually I found a way to alter resource that seemed locked, but I don't know if that would work here. See here: stackoverflow.com/questions/56302660/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.