64-Bit Made Easy
The scariest aspect of porting your ancient 32-bit code to 64-bit is pointer truncation bugs. Any places where you store a pointer in an ‘int’ or a ‘long’ can come back to bite you when you move to 64-bit.
The problem is, these bugs can take a while to show up. Memory allocations on Windows default to starting at low addresses, so it takes a while for allocations to work their way up high enough for there to be anything in the top 32 bits to truncate.
Just as with time-math it is really tedious to deal with bugs that may take hours to show up.
Update, July 2015: On Windows 8+ you can specify /HIGHENTROPYVA and your heap addresses will generally, or perhaps always, be above 4 GB – simple and effective.
At Valve (where I used to work) I introduced a simple technique to solve this problem. We make sure that our allocations start above the 4 GB line. If every allocation has some bits in the high 32 bits then pointer truncation bugs tend to cause warm fuzzy crashes immediately, and 64-bit cleanliness is easy.
Here’s some code:
/*
Copyright 2012 Bruce Dawson. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
void ReserveBottomMemory()
{
#ifdef _WIN64
static bool s_initialized = false;
if ( s_initialized )
return;
s_initialized = true;
// Start by reserving large blocks of address space, and then
// gradually reduce the size in order to capture all of the
// fragments. Technically we should continue down to 64 KB but
// stopping at 1 MB is sufficient to keep most allocators out.
const size_t LOW_MEM_LINE = 0x100000000LL;
size_t totalReservation = 0;
size_t numVAllocs = 0;
size_t numHeapAllocs = 0;
size_t oneMB = 1024 * 1024;
for (size_t size = 256 * oneMB; size >= oneMB; size /= 2)
{
for (;;)
{
void* p = VirtualAlloc(0, size, MEM_RESERVE, PAGE_NOACCESS);
if (!p)
break;
if ((size_t)p >= LOW_MEM_LINE)
{
// We don't need this memory, so release it completely.
VirtualFree(p, 0, MEM_RELEASE);
break;
}
totalReservation += size;
++numVAllocs;
}
}
// Now repeat the same process but making heap allocations, to use up
// the already reserved heap blocks that are below the 4 GB line.
HANDLE heap = GetProcessHeap();
for (size_t blockSize = 64 * 1024; blockSize >= 16; blockSize /= 2)
{
for (;;)
{
void* p = HeapAlloc(heap, 0, blockSize);
if (!p)
break;
if ((size_t)p >= LOW_MEM_LINE)
{
// We don't need this memory, so release it completely.
HeapFree(heap, 0, p);
break;
}
totalReservation += blockSize;
++numHeapAllocs;
}
}
// Perversely enough the CRT doesn't use the process heap. Suck up
// the memory the CRT heap has already reserved.
for (size_t blockSize = 64 * 1024; blockSize >= 16; blockSize /= 2)
{
for (;;)
{
void* p = malloc(blockSize);
if (!p)
break;
if ((size_t)p >= LOW_MEM_LINE)
{
// We don't need this memory, so release it completely.
free(p);
break;
}
totalReservation += blockSize;
++numHeapAllocs;
}
}
// Print diagnostics showing how many allocations we had to make in
// order to reserve all of low memory, typically less than 200.
char buffer[1000];
sprintf_s(buffer, "Reserved %1.3f MB (%d vallocs,"
"%d heap allocs) of low-memory.\n",
totalReservation / (1024 * 1024.0),
(int)numVAllocs, (int)numHeapAllocs);
OutputDebugStringA(buffer);
#endif
}Cool, eh?
The code is a bit messy but actually fairly simple. Call this as soon as possible when your 64-bit process starts up and you will be able to find and fix your pointer truncation bugs in no time at all.
The code is a bit verbose because it first reserves all of the low-memory address space and then tries to soak up address space that was previously reserved by the CRT and process heaps. Other heaps in your process may still be holding on to low memory, but in practice it shouldn’t be enough to matter.
It’s cheap
The VirtualAlloc calls reserve only address space, which means that the cost of this is very low. The code doesn’t reserve 4 GB of RAM, it just reserves some space and then never uses it. Cheap like borscht.
(App) Verify this
This is such a simple and obvious technique that I’m quite surprised that Application Verifier doesn’t offer it as an option*. In fact, Application Verifier has a bug that renders it almost incompatible with this technique: if you are using this technique at the same time that you use Application Verifier then it somehow ends up committing 4 GB of RAM! The first time we hit this was when a colleague was running a dozen copies of our asset conversion tool while Application Verifier was enabled for it. The 48 GB of extra RAM consumption did bad things to his computer’s performance.
I hacked around this problem by detecting Application Verifier (just check to see if one of its DLLs is loaded) and disabling the reservation in that case. Another alternative is to make the address space reservation optional, but this won’t find as many bugs.
It’s a darned good start
Pointer truncation bugs aren’t the only problem in porting to 64-bit. Indices and offsets can also truncate or wrap, so looking at compiler warnings and auditing likely problem areas is a good idea. It turns out that most integer loop variables should probably be ‘size_t’ or ‘ptrdiff_t’ rather than ‘int’.
I’m here all week, try the steak
Porting to 64-bit needn’t be scary, and this technique helps make the process more reliable and predictable. By using this technique at Valve I was able to flush out all the critical pointer truncation bugs in a large code base in very little time. This then made it easier to use Application Verifier to check for other memory bugs, and also lets our processes address vast amounts of memory.
* If Microsoft had added pointer truncation detection to Application Verifier then they might have caught this bug in their audio APIs. If you use the MIXER_OBJECTF_HWAVEOUT flag to pass a (64-bit) HWAVEOUT to mixerOpen then you find that the uMxId parameter is a (32-bit) UINT. Oops. Try it yourself, before and after calling ReserveBottomMemory(). Bug reported.
void TestAudio()
{
WAVEFORMATEX w = {};
w.wFormatTag = WAVE_FORMAT_PCM;
w.nChannels = 1;
w.nSamplesPerSec = 44100;
w.wBitsPerSample = 16;
w.nBlockAlign = w.nChannels * (w.wBitsPerSample/8);
w.nAvgBytesPerSec = w.nSamplesPerSec * w.nBlockAlign;
HWAVEOUT hWave;
MMRESULT mmr = waveOutOpen(&hWave, WAVE_MAPPER, &w,
NULL, 0, CALLBACK_NULL);
if (mmr == MMSYSERR_NOERROR)
{
HMIXER hMixer = NULL;
// Map the device onto an HMIXER. The flags parameter tells the API
// to interpret the second parameter as an HWAVEOUT. The
// mandatory cast truncates the pointer.
mmr = mixerOpen(&hMixer, UINT(hWave), 0, 0,
MIXER_OBJECTF_HWAVEOUT);
}
}