Note that the complete solution and download link is at the bottom. Modern Intel CPU’s have features such as Turbo Boost, which will vary the frequency of your CPU. Please note that (and I have seen this on multiple machines I own) you should disable the Hyper-V feature in Windows before trying out the code below, as Hyper-V seems to stop clock-variations from taking place on Intel CPU’s. In other words, it seems to stop Turbo Boost. To disable Hyper-V, go to Control Panel -> Uninstall a program -> Turn Windows features on or off (from the menu to the left of the window), and then deselect the Hyper-V check-box, and hit OK.

Before the introduction of Turbo Boost, functions such as QueryPerformanceFrequency in conjunction with some other methods provided an effective means of detecting a CPU’s clock speed. This is no longer the case. QueryPerformanceFrequency only seems to return the maximum frequency before clock-varying technologies start to kick in. However, this function is still going to be important (and still going to be used in our calculations). The actual formula for calculating CPU frequency is the maximum CPU frequency before clock-varying technologies multiplied by two Intel-specific registers which give you the ratio of actual performance over maximum performance (actualFrequency = maximumFrequencyWithoutClockSpeedVariations * APERF / MPERF). There registers are known as APERF and MPERF, and the ratio of APERF / MPERF is what we need to fetch.

To obtain the values of model-specific registers such as APERF or MPERF, we need to generate the rdmsr instruction using an Intrinsic Function known as __readmsr. Unfortunately, calling this function is not as simple as just, well…calling it. As the remark for it on MSDN goes, “This function is only available in kernel mode, and the routine is only available as an intrinsic.” When you write an application in Windows, like a WPF application or a Console Application, it runs as a user-mode application, meaning that it has some security restrictions in what you can do with it and that it runs in a ring of security called Ring 3, the least privileged security level. However, a kernel-mode application runs in Ring 0, the most privileged security level. Wikipedia has a great article on Protection Rings if you’d like to read more about them. As far as I know, the only way to get into kernel-mode is to write a kernel-mode driver. What this all means is that we need to have a user-mode application that talks to a kernel-mode driver in order to fetch the values of APERF and MPERF.

I started by downloading the Windows Driver Kit, which you will also need, so go ahead and grab it. I spent a lot of time trying to find examples of kernel-mode drivers that communicated with user-mode applications, and I came across a nice example on CodeProject. I noticed that the example in question uses driver source code that is only for WDM-based drivers, whereas most driver templates in the Windows Driver Kit are WDF-based. In fact, the latest Windows Driver Kit has no WDM driver with source code in it (only a blank template with absolutely no code). You can read about the differences between WDF and WDM on MSDN. WDM is clearly what we are after, as this article states, “The WDM model is closely tied to the operating system. Drivers interact directly with the operating system by calling system service routines and manipulating operating system structures. Because WDM drivers are trusted kernel-mode components, the system provides limited checks on driver input.” After spending some time looking through the Windows Driver Kit samples, I found the IOCTL sample driver which is a perfect sample skeleton driver that we can alter to fit our needs. Its description reads, “This sample driver is not a Plug and Play driver. This is a minimal driver meant to demonstrate a feature of the operating system. Neither this driver nor its sample programs are intended for use in a production environment. Instead, they are intended for educational purposes and as a skeleton driver.” I began modifying that driver to fit my actual needs. I also learned a few things along the way. For one, kernel drivers don’t like floating point arithmetic. I’m not even entirely sure that they will compile if you try to make use of a double or float type unless you find a means of explicitly including that type definition inside of your driver. Also, you’re limited because you cannot use the Windows header, and must use a special kernel-mode header known as the Ntddk header. I’ve modified the IOCTL sample skeleton as follows:

To have the user-mode application actually install this driver, you need to either:

Sign the driver with a Code Signing certificate you’ve obtained from some third party issuer. To sign the driver, right click the driver’s project file, go to Configuration Properties -> Driver Signing -> General, and change the Sign Mode, setting the Production Certificate to the Code Signing certificate you have installed into your machine from the third party issuer.

If you’ve completed the above steps, the code should run just fine (if you run it under Administrator credentials). Finally, you can download the complete source code of my implementation. Note that, you use this code at your own risk and are entirely liable for any problems that may arise out of it, whatsoever. I do ask that if you use my driver, you give me a little credit. Just throw my name in a comment somewhere. Here is the download link: FrequencyCalculator.zip.

Say you have a Release mode MSVC++ Win32 Console Application with the following code:

#include "stdafx.h"
#include <iostream>
using namespace std;
void CorruptTheHeap()
{
// Create a pointer to an integer.
int *reallyBadlyCodedIntegerAllocation;
// Allocate insufficient space for this memory space to store an actual integer.
cout << "The expected memory size of this type is " << sizeof(int) << " bytes, which is " << 8*sizeof(int) << " bits." << endl;
int sizeToAllocateForThisType = 0;
cout << "The actual size of this integer will be set to " << sizeToAllocateForThisType << " bytes." << endl;
reallyBadlyCodedIntegerAllocation = (int *)malloc(sizeToAllocateForThisType);
// Try to set the integer to an integer value (causing a memory leak at this point since we are writing over the bounds of the memory we actually own).
*reallyBadlyCodedIntegerAllocation = 0;
// Trying to free this integer would cause a heap corruption because it will try to free the size of the type, but we have allocated it to be nothing. In a Release build, this will cause a crash.
free(reallyBadlyCodedIntegerAllocation);
}
int _tmain(int argc, _TCHAR* argv[])
{
CorruptTheHeap();
cout << "Press any key to exit." << endl;
cin.get();
return 0;
}

Make sure the application’s project settings build it so that its *.pdb file(s) is or are in the same folder as where you execute it. Now get WinDbg, which contains Global Flags. For this example, my application is built in Release (must be in Release) as an x64 architecture application, so the next step for me is to start Global Flags (X64). A simple Windows start screen search for Global Flags should uncover it, but for me it installed at C:\Program Files (x86)\Windows Kits\8.1\Debuggers\x64\gflags.exe. Open it up, go to the Image File tab. Type in the name of your Image file. For me, my Console Application compiles and runs as HeapCorruptor.exe, so I typed that in, and pressed the TAB key on my keyboard. You’ll notice that when running Global Flags, it seems to keep track of executables based on their name, so when you restart and go through the same process of typing in the executable’s name and press the TAB key, it loads your last configuration (I know, its kind of weird and takes a bit of getting used to).

Check off Debugger and set its path to the path of your WinDbg executable. For me, a default setup of the debugging tools installed WinDbg at “C:\Program Files (x86)\Windows Kits\8.1\Debuggers\x64\windbg.exe”. Then set up any other necessary flags, as I have in the screenshot below, hit Apply, and then OK to close it down.

Settings for detecting heap corruptions using Global Flags.

Now, run your executable. Global Flags will start up along with it. It starts paused, so type in g (for go) to get it to continue, or hit F5 in Global Flags. After you type in g and hit enter, you should see an error as the application starts up and runs:

This is great because it shows us some important bits of information, like the call-stack that caused our corruption. In particular, we can see that CorruptTheHeap() was called and that, while running it, Global Flags was then unable to verify a check-sum, so we can pinpoint the problem to be in that function…sometimes Global Flags may show you even more granular methods of underlying framework code that you are using to help you drill down to the actual function causing problems, but in a nutshell that’s essentially it. Make sure to follow the steps above and disable all check-boxes for the context of that executable’s name in Global Flags, or else it will always start with your executable.

Ildasm.exe (IL Disassembler) is an out-of-the box disassembler packaged with Visual Studio, and Ilasm.exe (IL Assembler) is an out-of-the-box assembler packaged with Visual Studio. Let’s try using Ildasm.exe and Ilasm.exe to disassemble and then re-assemble a portable executable from a C# Console Application. Take the following C# Console Application for example:

Build this code in Debug mode and run it. Figure out where the code was built and copy the path to your executable for this C# Console Application. Then do a search on your computer for the VS2012 x86 Native Tools Command Prompt and open it up (it will help us run the IL Assembler and Disassembler more easily). Try to change the directory somewhere where you have permissions…for me, the desktop is an alright place so the first command I ran was this:

cd "C:\Users\YourUserAccountName\Desktop"

Here comes the sweet stuff. To disassemble your executable, run this command on it (PrintSomething.exe is the name of the Console Application I’ve shown the code for above, but you can paste whatever path you have copied to your own executable):

You can inspect the assembly code in Disassembly.asm now by opening it up in your favourite text editor (you will find Disassembly.asm in your working directory, which I changed to be my desktop earlier):

You should see a new executable pop out of this file in your current working directory (for me, its the desktop as I’ve shown before): Disassembly.exe. Run it, and voila, you’ll see that the assembler compiled your assembly (and included any changes you’ve made). Pretty nice for touching up some very low-level code in Visual Studio applications, or even for dynamically changing your application’s manifest information.

This took me a little while to get the hang of because my source code didn’t maintain its formatting whenever I uploaded it to my blog. In order to get source code to format correctly, you need to use the “Text” tab in the “Add New Post” menu instead of the “Visual” tab in order for it to preserve tabs and spaces. It seems that, by default, the Visual tab’s behavior causes pastings of source code to remove or delete spaces and tabs. Here is a screenshot of where you should be when paste code in:

Where you want to be when you paste code in a WordPress blog.

Once you’ve pasted it with correct formatting, just wrap your code in [code language=”X”] and [/code] tags, where the value of X is any one of the following values (representative of the language your code is written in and thus, the language you want your code to be parsed as):

I wrote a C# class to decode VOX files into WAV files. It follows the Dialogic ADPCM specification strictly. If you read through that specification, the code below will become a lot clearer, otherwise you might think you’re reading another language altogether. The specification is really quite simple and nice once you boil it down. Note that the Dialogic ADPCM specification is different from the way NMS Communications libraries create VOX files as their file format is slightly different, and for files such as those, the code below will not work without some tweaks.

This article actually touches up on some advanced topics of C#, and some things that you may not have ever come across. MSDN has this to say about threads:

An operating-system ThreadId has no fixed relationship to a managed thread, because an unmanaged host can control the relationship between managed and unmanaged threads. Specifically, a sophisticated host can use the CLR Hosting API to schedule many managed threads against the same operating system thread, or to move a managed thread between different operating system threads.

What this is really trying to explain is thread affinity, and that you are not guaranteed to have a native thread map 1-to-1 to a managed thread depending on the CLR (Common Language Runtime) that is hosting your code. This is important to know when you P/Invoke into native functions that require calling back into your C# code after a period of time (such as NotifyServiceStatusChange). We want to maintain that 1-to-1 relationship using Thread.BeginThreadAffinity() because the marshaling layer needs to have a valid callback reference at all times.

Here is the code that you can use to P/Invoke NotifyServiceStatusChange in C# in order to wait for a service to stop:

Note that this is significantly different from the WaitForStatus method that is available to you out of the box in C#, because the WaitForStatus method polls every 250ms between status checks according to the remarks, whereas NotifyServiceStatusChange is event-driven and subscribes to that particular event (so its less overhead in terms of CPU usage).