Phil Booth
Phil Booth

Reputation: 4897

Why are LoadResource/LockResource sometimes returning concatenated resource data?

I'm working with a Visual Studio C++ project that contains a number of HTML resources. They are loaded by a method that looks like this:

LPCTSTR loadHTML(HMODULE hModule, LPCTSTR sResourceName)
{
    HRSRC hResource = FindResource(hModule, sResourceName, RT_HTML);
    if(!hResource)
        return 0;

    HGLOBAL hResourceData = LoadResource(hModule, hResource);
    if(!hResourceData)
        return 0;

    return reinterpret_cast<LPCTSTR>(LockResource(hResourceData));
}

Most of the time, this works fine. Some times, though, it returns a resource concatenated with another resource. When this happens, it is a persistent problem in that build. I can "fix" it by adding a few blank lines to the resource in question and then rebuilding the project. It happens periodically, even when the resources haven't changed.

I am keen to get to the bottom of why it is happening. Has anyone else come across it? Could there be something peculiar about my resources that is causing the problem? Is my code wrong?

Sadly, I'm reluctant to post an example resource here; they're pretty long and this is proprietary software.

Upvotes: 5

Views: 2873

Answers (2)

Chris Becke
Chris Becke

Reputation: 36121

Whats peculiar about your resources is you are expecting them to be zero terminated. iirc resource sections are aligned on 16 byte boundries, which means that whenever a "blob" is a multiple of 16 bytes long there won't be any separating byte's between the resource and the next.

Either ensure that the resources are saved with a terminating zero character, or use SizeofResource to determine where the resource ends.

Upvotes: 7

Anders
Anders

Reputation: 101756

How do you determine the end of a resource? Do your resource files end in a (double for unicode) NULL? I don't think there is any guarantee that a resource is NULL terminated in the PE file and you seem to be treating it as a string.

Upvotes: 4

Related Questions