BluetoothAPIs.h Broken in Windows SDK

Summary

The Microsoft Windows SDK versions 7.0 and 7.1 appear to have broken BluetoothAPIs.h header files.

Details

So far, I have uncovered two types of errors in this header file:

  • The use of #pragma deprecate instead of #pragma deprecated, causing compiler warnings.
  • Several callback function pointer type definitions omit the CALLBACK (__stdcall) calling convention, causing a crash.

The first error simply results in compiler warnings.

warning C4068: unknown pragma

The second type of error results in dereferencing of an invalid memory location when using BluetoothRegisterForAuthenticationEx and BluetoothAuthenticateDeviceEx. This is because the standard calling convention (__cdecl) assumes that the caller will clean up the stack. Since the caller in this case is assuming that the callback function minded its own stack, it immediately pops ESI, placing zero into the register:

5EBCFFE2  mov         ecx,dword ptr [ebp-4]
5EBCFFE5  pop         esi
5EBCFFE6  xor         ecx,ebp
5EBCFFE8  pop         ebx
5EBCFFE9  call        @__security_check_cookie@4 (5EBDBBBBh)

Later, ntdll.dll dereferences memory at ESI + 4, triggering an access violation:

774A8301  test        byte ptr [esi+4],4

“Unhandled exception at 0x774a8301 (ntdll.dll) in [Application]: 0xC0000005: Access violation reading location 0×00000004.

Solution

To the compiler warnings, I replaced all instances of

#pragma deprecate

with

#pragma deprecated

To fix the crash bug, I added the CALLBACK calling convention keyword to PFN_AUTHENTICATION_CALLBACK and PFN_AUTHENTICATION_CALLBACK_EX. They now appear as follows:

typedef BOOL (CALLBACK *PFN_AUTHENTICATION_CALLBACK)(LPVOID pvParam, PBLUETOOTH_DEVICE_INFO pDevice);

typedef BOOL (CALLBACK *PFN_AUTHENTICATION_CALLBACK_EX)(__in_opt LPVOID pvParam, __in PBLUETOOTH_AUTHENTICATION_CALLBACK_PARAMS pAuthCallbackParams);

Interestingly, the function pointer type definitions for the attribute-enumeration and device-selection callbacks (PFN_BLUETOOTH_ENUM_ATTRIBUTES_CALLBACK and PFN_DEVICE_CALLBACK, respectively) are defined correctly, using CALLBACK or WINAPI. I suspect that the inconsistency is because someone at Microsoft was using the /Gz compiler switch, making __stdcall the default calling convention.

Posted in Technology, Win32, Windows | Leave a comment

The Demise of CAPICOM

CAPICOM, a COM-based wrapper for the CryptoAPI library, is deprecated and on its way out. However, Microsoft has no time line for phasing it out, nor have they provided sufficient documentation of alternatives.

Many CAPICOM pages contain a confusing, bright-red header along the lines of:

[The SignedCode object is available for use in the operating systems listed in the Requirements section. Instead, use Platform Invocation Services (PInvoke) to call the Win32 API SignerSignEx, SignerTimeStampEx, and WinVerifyTrust functions to sign content with an Authenticode digital signature. For information about PInvoke, see Platform Invoke Tutorial. The .NET and CryptoAPI via P/Invoke: Part 1 and .NET and CryptoAPI via P/Invoke: Part 2 subsections of Extending .NET Cryptography with CAPICOM and P/Invoke may also be helpful.]

Note that this alarming paragraph seems to begin by simply telling you that this API is supported on the operating systems listed later. It does not state that the API will not be available on later OSes, but why place this here otherwise? The next sentence, beginning with, “Instead, …” seems to be contrasting with something, yet makes absolutely no sense in this context.

Finally, this paragraph instructs us to investigate SignerSignEx, and SignerTimeStampEx, which are supplied by the mssign32.dll, have no header file, and absolutely no example code. This is what I find most irksome, they document each and every function and structure, yet each page says, “there is no header file, so copy and paste the declaration given here.” Well, why not simply provide an mssign.h file on blogs.msdn, or similar? And why, oh why, is there not a single line of sample code?

Follow-up

I have provided a basic header file for mssign32.dll, here.

Posted in Authenticode, COM, Cryptography, Technology, Win32 | Tagged , , | Leave a comment

GnuPG Plugin for vim Under Cygwin

GnuPG, GNU Privacy Guard, is a free system for encrypting files, emails, etc. The GnuPG plugin for vim provides automatic encryption and decryption of files within vim. If you attempt to edit a GnuPG-encrypted file with vim, it will prompt you for the password, and re-encrypt the file when you’re done editing.

Download the gnupg plugin for vim from here and copy it into your user directory directory under .vim/plugin. From the Cygwin bash prompt:

mkdir ~/.vim/plugin
copy gnupg.vim ~/.vim/plugin

Run vim, then use the :scriptnames command and verify that gnupg.vim appears in the list of sourced scripts:

  1: /cygdrive/c/Users/username/.vim/plugin/gnupg.vim
Posted in Cryptography, Technology, Win32 | Leave a comment

CoCreateInstance Fails With “Class Not Registered”

Recently, I had a problem unique to my test machine. Attempting to call CoCreateInstance on a COM class provided by one of our DLLs resulted in HRESULT 0×80040154, which corresponds to “Class not registered”.

This was a mystery since regsvr32 appeared to properly register our DLL, and all the obvious registry keys were intact!

After a bit of web searching, I experimented with using CLSCTX_ALL instead of CLSCTX_INPROC_SERVER. Now, the call succeeded! But why, since this is a DLL and, therefore, should be considered an in-process COM server?

MSDN documentation states that CLSCTX_ALL is defined as the combination of CLSCTX_INPROC_SERVER, CLSCTX_INPROC_HANDLER, and CLSCTX_LOCAL_SERVER. I began substituting each one in turn and found that the key was CLSCTX_LOCAL_SERVER.

Stepping through the code in the debugger revealed that the instant the CoCreateInstance call was made, a new instance of dllhost.exe appeared in the process list. This explained why CLSCTX_INPROC_SERVER would fail, since strictly speaking, the DLL was being hosted in dllhost’s process space.

Ultimately, the problem turned out to be an artifact from an old COM+ experiment. There was a COM+ entry corresponding to our COM server in the Component Services panel (Control Panel | Administrative Tools | Component Services, under Component Services | Computers | My Computer | COM+ Applications). The COM+ entry dictated that the COM server be hosted by proxy by dllhost.exe. Deleting this COM+ entry and re-running regsvr32 fixed the problem.

Component Services panel in Administrative Tools

Posted in COM, Technology, Win32, Windows | Leave a comment

SetThreadLocale and SetThreadUILanguage for Localization on Windows XP and Vista

Simple Localization

In classic Windows programming, the quickest way to handle localized resources is to put all languages into the same resource file, then use SetThreadLocale to tell Windows that it should return resources tagged with the specified language identifier. Subsequently, any attempt to load a resource by that thread will cause Windows to prefer resources corresponding to the specified language code.

Vista Complications

As of Windows Vista, calling SetThreadLocale will appear to work, but will have no effect. Your application will continue to use load resources using whatever language identifier is set as the user’s default.

Under Windows Vista, SetThreadUILanguage must be called instead of SetThreadLocale. This function is in Kernel32.dll. It appears in Vista, Windows 2008, and some versions of Windows XP. Under Windows XP, this function will not have the desired effect, and I have no idea what it does under Windows 2008.

Since the function isn’t available on all systems, you will probably want to use GetProcAddress to locate the function, and call it using a function pointer. However, since the function appears on Windows XP, but does not behave in the desired way, it’s important to only call it on Windows Vista.

Resource Storage

To use the SetThreadLocale or SetThreadUILanguage methods, the resource file must first be populated with all required languages. Each translated resource file should be appended to the .rc file, each one following an appropriate LANGUAGE statement and corresponding language identifier. (note that you could use separate .rc files and include them, in which case there are gotchas).

Is it Vista?

This function should reliably indicate whether the current OS is Windows Vista. I use GetVersionEx. Note that, even though we’re using an OSVERSIONINFOEX structure, we have to cast its pointer so that it appears as a OSVERSIONINFO pointer. No guarantee of future compatibility is implied:

bool IsOSVerWindowsVista()
{
    OSVERSIONINFOEX osver;
    ZeroMemory(&osver, sizeof(osver);
    osver.dwOSVersionInfoSize = sizeof(osver);

    if (!GetVersionEx((OSVERSIONINFO *)&osver))
        return false;

    // dwMajorVersion 6 and dwMinorVersion 0 means Vista or 2k8:
    if ( (osver.dwMajorVersion != 6) || (osver.dwMinorVersion != 0) )
        return false;

    // wProductType of NT_WORKSTATION means it's Vista:
    if (osver.wProductType != VER_NT_WORKSTATION)
        return false;

    return true;
}

Calling SetThreadUILanguage Dynamically

The trickiest part of using GetProcAddress to dynamically call a function at run-time is getting the function pointer declaration correct. This type definition should work for SetThreadUILanguage:

typedef LANGID (WINAPI *FP_SetThreadUILanguage)(LANGID LangId);

Now, you have a function pointer type called FP_SetThreadUILanguage which can be used like any other type.

This function pointer can be used to dynamically call any function within a loaded module (DLL). SetThreadUILanguage lives inside Kernel32.dll. Since Kernel32.dll is required by all Win32 processes, we can simply use GetModuleHandle to find it, we don’t have to use LoadLibrary. A pointer to SetThreadUILanguage can therefore be retrieved like this (unnecessarily verbose code):

HMODULE hKernel32 = GetModuleHandle(_T("Kernel32.dll"));
FARPROC pFn = GetProcAddress(hKernel32, "SetThreadUILanguage");

FP_SetThreadUILanguage pSetThreadUILanguage = (FP_SetThreadUILanguage)pFn

The function can now be called through the function pointer variable:

LANGID langid = pSetThreadUILanguage(myLangId);

SetThreadUILanguage returns the LANGID which has been set. If the call was successful, it will return the same LANGID that was specified.

Constructing a Language Identifier

Use the MAKELANGID macro from Winnt.h, and supply LANG_Xxx constants from same. For example, Simplified Chinese would require:

DWORD dwSimplifiedChinese =
   MAKELANGID( LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED );

Non-Vista Platforms

On non-Vista platforms, SetThreadLocale can be used. Instead of a language identifier, it accepts a locale identifier. To generate the locale identifier, simply pass your language identifier to the MAKELCID macro, and supply SORT_DEFAULT as the second parameter:

SetThreadLocale(MAKELCID(myLangId, SORT_DEFAULT));

This example unconditionally sets the thread locale to Simplified Chinese in a single line of code:

SetThreadLocale(
   MAKELCID(
      MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED),
      SORT_DEFAULT));

SetThreadLocale returns TRUE on success, FALSE on error.

Reference

Posted in Technology, Win32 | 1 Comment

Underlining Characters in a ToolTip

My product, a toolbar for Outlook Express, uses tooltips to display keyboard shortcuts. For some localization work, I needed to display an underlined character within a tooltip.

The only hint I could find was a reference to .Net tooltips.

Apparently, in both .Net and Win32 tooltips, a single ampersand will be stripped, a double ampersand will cause the next character to be underlined, and three ampersands will display a single ampersand.

Input     Displayed
&B B
&&B B
&&&B &B

Note that this will be affected if the TTS_NOPREFIX flag is set, which prevents ampersands from being stripped.

Posted in Technology, Win32 | Leave a comment

Windows Vista UAC Goofiness

Windows Vista UAC is not always a predictable beast.

Today I found out that if an executable doesn’t set level="asInvoker" in its manifest, UAC confirmation will kick in if any of the following substrings appear in the filename:

  • setup
  • install
  • update

A digital signature does not affect this behavior.

Besides adding “asInvoker” to the manifest, another workaround is to rename the executable to remove the trigger word. For example, renaming MyProductUpdater.exe to MyProductRenewal.exe will (for now) bypass the UAC logic.

Note that this in no way bypasses the protections of UAC. Functions which perform some task which requires UAC-approval will simply fail. This will only be useful if you have an update tool which only updates user-owned resources, since that doesn’t require UAC-approval.

Posted in Technology, Win32 | Tagged , , , , , , , | Leave a comment