HRESULT exception not caught in VS 2008 - c++

I've got a stange situation in visual studio 2008 C++. I work on code that was originally written for visual studio 2003, where everything works well. Now, ported to VS 2008, the exception handling, which unfortuantely exists widely in the code, does not work anymore. standard code example:
try
{
HRESULT hr = S_OK;
// do stuff...
if( FAILED( hr ) )
throw hr;
}
catch( HRESULT hr )
{
// error handling, but we never get here
}
catch( ... )
{
// ... not even here
}
Under VS 2008, no exception is encountered, but I get a crash somewhere else, indicating that the stack pointer must be screwed up. Did anybody come across this behaviour? Any help is appreciated.

After starting the debugger, go to Debug / Exceptions, and select for which exceptions the debugger should stop when the exception is thrown.

I get a crash somewhere else, indicating that the stack pointer must be screwed up.
How so? The fact of a crash has nothing to do with the stack. The bigger issue here is that we don't know what "hr" was declared as. If it was declared anything other than HRESULT, the compiler does not need to catch there.
Specifically, I believe HRESULT's definition changed with VS2005 in order to support 64 bit windows. If hr is declared as something else that happened to be the same as HRESULT before, but is not after you installed the new Windows SDK, then that's a likely cause.
Can't say more without seeing more code.
EDIT: The following works correctly:
#include <iostream>
#include <iomanip>
#include <windows.h>
int main()
{
try
{
HRESULT hr = E_FAIL;
std::cout << "Inside try\r\n";
if( FAILED( hr ) )
throw hr;
}
catch( HRESULT hr )
{
std::cout << "Error:" << std::hex << (unsigned int)hr;
}
system("pause > nul");
}
We need to see more code.

Related

get_accChildCount returns 0 when it shouldn't

I'm trying to enumerate tabs of IE from an extension and from a standalone application. For one of the MSAA nodes get_accChildCount returns 0 when called from extension, while it should return 1 according to inspect and a call from standalone application.
The problem was described previously at StackOverflow, yet it was solved via a hack that doesn't work for me. /clr and /MT are incompatible.
Also there was a topic on MSDN with the same issue. There's no single answer there.
If you run IE with administrator privileges, it works properly.
API Monitor shows several thousand calls in a minimal example, and it's unclear which of these are related. The minimal example is attached below.
What are the undocumented cases when get_accChildCount returns wrong child count?
What other method could I use to activate the tab by URL in most versions of IE?
#include <atlbase.h>
#include <atlcom.h>
#include <atlctl.h>
#include <atltypes.h>
#include <atlsafe.h>
#include <io.h>
#include <fcntl.h>
#include <windows.h>
#include <iostream>
#include <string>
#include <vector>
#include <boost/format.hpp>
#include <fstream>
using namespace std;
CComPtr<IAccessible> get_acc_by_hwnd(HWND hwnd) {
CComPtr<IAccessible> ret;
HRESULT hr = ::AccessibleObjectFromWindow(hwnd, OBJID_WINDOW, IID_IAccessible, (void**) &ret);
if (FAILED(hr) || !ret) {
wcout << L"Accessible::Accessible invalid hwnd" << endl;
}
return ret;
}
std::vector<CComPtr<IAccessible>> get_acc_children(CComPtr<IAccessible> acc) {
std::vector<CComPtr<IAccessible>> ret;
long count;
if (FAILED(acc->get_accChildCount(&count))) return ret;
long count_obtained = 0;
if (!count) return ret;
std::vector<CComVariant> accessors(count);
if (FAILED(::AccessibleChildren(acc, 0, count, &*accessors.begin(), &count_obtained))) return ret;
accessors.resize(count_obtained);
for (auto vtChild : accessors) {
if (vtChild.vt != VT_DISPATCH) continue;
CComQIPtr<IAccessible> pChild = vtChild.pdispVal;
if (pChild) ret.push_back(pChild);
}
return ret;
}
bool is_client(CComPtr<IAccessible> acc) {
CComVariant var;
HRESULT hr = acc->get_accRole(CComVariant(CHILDID_SELF), &var);
return SUCCEEDED(hr) && var.vt == VT_I4 && var.lVal == 0xA;
}
std::wstring get_descr(CComPtr<IAccessible> acc) {
CComBSTR str;
HRESULT hr = acc->get_accDescription(CComVariant(CHILDID_SELF), &str);
return SUCCEEDED(hr) && str ? std::wstring(str) : L"";
}
int main() {
::CoInitialize(nullptr);
_setmode(_fileno(stdout), _O_U16TEXT);
// put HWND of the window that contains tab labels
// it's hardcoded to minimize quantity of API calls
HWND hwnd = reinterpret_cast<HWND>(0x002D0696);
CComPtr<IAccessible> iaccessible;
HRESULT hr = ::AccessibleObjectFromWindow(hwnd, OBJID_WINDOW, IID_IAccessible, (void**) &iaccessible);
if (FAILED(hr) || !iaccessible) {
wcout << L"AccessibleBrowser::activate_tab " L"failed to get IAccessible for IE" << endl;
return EXIT_FAILURE;
}
wstring const sentinel = L"\r\n";
for (auto child : get_acc_children(iaccessible)) if (is_client(child)) {
for (auto child1 : get_acc_children(child)) { // fails here in extension
for (auto child2 : get_acc_children(child1)) {
std::wstring descr = get_descr(child2);
auto pos = descr.find(sentinel);
if (pos == string::npos) continue;
auto tab_url = descr.substr(pos + sentinel.size());
wcout << tab_url << endl;
}
}
}
}
I poked at your program for a while without having much to show for it. Perhaps I realized too late that it was not supposed to reproduce the problem :( I can only provide some possibly helpful hints to get you to look under the right kind of rock.
yet it was solved via a hack that doesn't work for me
These programmers made a simple mistake, they forgot to call CoInitialize/Ex(). A very common oversight. Using the /clr build option works around that mistake because it is now the CLR that calls it. You can easily repro this mishap, just comment out the CoInitialize() call. Unfortunately it works for a while without any loud errors being produced, but you do get 0 for certain accobjects. You'll notice your program no longer finds the tabs.
Not so sure I can cleanly explain this, certain COM-style object models don't actually use the COM infrastructure. DirectX is the best example, we can add UIAutomation to that list. I assume it will silently fail like this when the client app's component is COM-based. Unclear if it is, DirectUIHWnd is quite undocumented.
So stop looking for that as a workaround, you did not forget to call CoInitialize() and it will be taken care of by IE before it activates your extension.
If you run IE with administrator privileges, it works properly.
That's a better rock. Many programmers run VS elevated all the time, the roles might be reversed in the case of UIA. Do keep in mind that your extension runs in a sandbox inside IE. No real idea how elevating IE affects this. One thing you cannot do from code running in the low-integrity sandbox is poke at UI components owned by a code that runs in a higher integrity mode. Google "disable IE enhanced protected mode" and follow the guideline to see what effect that has on your addin.

What is the different between system and Administrator account when call SHGetSpecialFolderLocation() function?

I write two program, one is windows service run in system account(named xxService) and the other one is common application run in Administrator account(named xx);
They use the same code to get CSIDL_COMMON_DOCUMENTS directory. In most machine , they run well.
But some machine, the xxService can get the correct directory, the xx have failure in SHGetSpecialFolderLocation();
edit:
the program only run on Windows XP(sp3).
edit2:
Use SHGetFolderPathA() function to solve this problem.
My english is poor, everybody excuse me!
log:
[2964] [db](tid=1108)(pid=2964): SHGetSpecialFolderLocation() fail.hr=0x80070057, ierr=122
the detail error info:
//
// MessageId: E_INVALIDARG
//
// MessageText:
//
// One or more arguments are invalid
//
#define E_INVALIDARG _HRESULT_TYPEDEF_(0x80070057L)
ERROR_INSUFFICIENT_BUFFER
122 (0x7A)
The data area passed to a system call is too small.
code:
//C:\Users\Public\Documents
LPITEMIDLIST pidl;
LPMALLOC pShellMalloc;
HRESULT hr = S_FALSE;
hr = SHGetMalloc(&pShellMalloc);
if(SUCCEEDED(hr))
{
hr = SHGetSpecialFolderLocation(NULL,CSIDL_COMMON_DOCUMENTS,&pidl);
if(SUCCEEDED(hr))
{
if(!SHGetPathFromIDListW(pidl, strDbFilePath))
{
int ierr=GetLastError();
DebugMsgW((L"SHGetPathFromIDListW() fail., ierr=%d"), ierr);
}
DebugMsgW(L"DBpath=%s",strDbFilePath);
pShellMalloc->Free(pidl);
}
else
{
int ierr=GetLastError();
DebugMsgW((L"SHGetSpecialFolderLocation() fail.hr=0x%x, ierr=%d"), hr, ierr);
}
pShellMalloc->Release();
}
else
{
int ierr=GetLastError();
DebugMsgW((L"SHGetMalloc() fail.hr=0x%x, ierr=%d"), hr, ierr);
}
SHGetSpecialFolderLocation() (and any other function that returns an HRESULT) does not use GetLastError() to report error codes, since the HRESULT is the error code. Even SHGetPathFromIDList() is not documented as using GetLastError(), either. So the return value of GetLastError() is irrelevant in your example and needs to be removed to avoid confusion.
As for the E_INVALIDARG error, you are using a legacy function. CSIDL_COMMON_DOCUMENTS is known to fail in SHGetSpecialFolderLocation() on some systems. You need to use a newer function, such as SHGetFolderPath(), or SHGetKnownFolderPath() on Vista+.

0x80070002 when trying to set default browser

I'm trying to set the default browser on Windows. I did have it working, and then for some reason it stopped when I refactored my code and I can't work out why (and I can't get the old code back unfortunately).
Here is a test I wrote which I believe should work:
#include <windows.h>
#include <Shobjidl.h>
void test()
{
// Included because they aren't defined in mingw for some reason.
const GUID CLSID_ApplicationAssociationRegistration =
{ 0x591209c7, 0x767b, 0x42b2, {0x9f,0xba,0x44,0xee,0x46,0x15,0xf2,0xc7} };
const IID IID_ApplicationAssociationRegistration =
{ 0x4e530b0a, 0xe611, 0x4c77, {0xa3,0xac,0x90,0x31,0xd0,0x22,0x28,0x1b} };
CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
IApplicationAssociationRegistration* pAAR;
HRESULT hr = CoCreateInstance(CLSID_ApplicationAssociationRegistration,
NULL,
CLSCTX_INPROC,
IID_ApplicationAssociationRegistration,
(void**)&pAAR);
if (FAILED(hr))
{
qDebug() << "CoCreateInstance failed: " << hr;
return;
}
hr = pAAR->SetAppAsDefault(L"IE.HTTP", L"http", AT_URLPROTOCOL);
if (FAILED(hr))
{
qDebug() << "SetAppAsDefault failed: " << hr;
pAAR->Release();
return;
}
pAAR->Release();
qDebug() << "Success";
return;
}
I get "SetAppAsDefault failed: -2147024894" (0x80070002). Note that CoCreateInstance does work (or at least claims to).
Any ideas? I've tried changing COINT_APARTMENTTHREADED to various other values, and CLSCTX_INPROC too. None of them work. Please explain your answer as if I have never used COM before and have no desire to fill my brain with it! I.e. I have no idea what marshalling, apartments, etc. are.
I'm 80% sure something very similar to this did work...
Update: Sorry I previously said it was giving E_NOINTERFACE which was totally wrong - not sure why I thought that. 0x80070002 doesn't appear to be anything though...
Update 2: 0x80070002 means "The system cannot find the file specified." according to FormatMessage. I have no idea how that makes sense in this context though.
Follow Microsoft's guidelines when working with the default browser as you will encounter many issues on many os versions.
http://msdn.microsoft.com/en-us/library/windows/desktop/cc144154(v=vs.85).aspx#browser

Windows HOME - SHGet(Known)FolderPath

I'm trying to write a function to get the Windows-equivalent of HOME. My C skills are rusty, so don't mind that my example code does not compile. I'm trying to use SHGetKnownFolderPath on Windows Vista and newer, and SHGetFolderPath on Server 2003 and older. Since I expect to encounter users running Windows XP (as it is still the number one deployed version of Windows), I am going to avoid having a reference to SHGetKnownFolderPath in the symbol table (as this would lead to a binary that won't even load on XP). I know to LoadLibrary() shell32 and to GetProcAddress() from there, but my skills on doing function pointers are, well, crap, to say the least.
When I write features, and they are difficult to handle, I isolate them into an separate example file. The broken example I have so far is:
#include <windows.h>
#include <stdio.h>
// Pointerizing this Vista-and-later call for XP/2000 compat, etc.
typedef HRESULT (WINAPI* lpSHGetKnownFolderPath)(
REFKNOWNFOLDERID rfid,
DWORD dwFlags,
HANDLE hToken,
PWSTR *ppszPath
) lpSHGetKnownFolderPath;
int main(int argc, char *argv[])
{
// SHGet(Known)FolderPath() method.
HMODULE hndl_shell32;
lpSHGetKnownFolderPath pSHGetKnownFolderPath;
hndl_shell32 = LoadLibrary("shell32");
pSHGetKnownFolderPath = GetProcAddress(hndl_shell32, "SHGetKnownFolderPathW");
if(pSHGetKnownFolderPath != NULL) {
} else {
}
}
My question is this: Knowing that I'm doing this wrong, how would I go about doing this right? And an explanation as to how to do it right in the future would be appreciated. Thanks.
Here is a small application that shows how to use LoadLibrary() and GetProcAddress() with advice provided in comments:
#include <windows.h>
#include <stdio.h>
#include <shlobj.h>
/* The name of the function pointer type is
'lpSHGetKnownFolderPath', no need for
additional token after ')'. */
typedef HRESULT (WINAPI* lpSHGetKnownFolderPath)(
REFKNOWNFOLDERID rfid,
DWORD dwFlags,
HANDLE hToken,
PWSTR *ppszPath
);
int main()
{
HMODULE hndl_shell32;
lpSHGetKnownFolderPath pSHGetKnownFolderPath;
/* Always check the return value of LoadLibrary. */
hndl_shell32 = LoadLibrary("shell32");
if (NULL != hndl_shell32)
{
/* There is no 'SHGetKnownFolderPathW()'.
You need to cast return value of 'GetProcAddress()'. */
pSHGetKnownFolderPath = (lpSHGetKnownFolderPath)
GetProcAddress(hndl_shell32, "SHGetKnownFolderPath");
if(pSHGetKnownFolderPath != NULL)
{
PWSTR user_dir = 0;
if (SUCCEEDED(pSHGetKnownFolderPath(
FOLDERID_Profile,
0,
NULL,
&user_dir)))
{
/* Use 'user_dir' - remember to:
CoTaskMemFree(user_dir);
when no longer required.
*/
}
}
else
{
fprintf(stderr, "Failed to locate function: %d\n",
GetLastError());
}
/* Always match LoadLibrary with FreeLibrary.
If FreeLibrary() results in the shell32.dll
being unloaded 'pSHGetKnownFolderPath' is
no longer valid.
*/
FreeLibrary(hndl_shell32);
}
else
{
fprintf(stderr, "Failed to load shell32.dll: %d\n", GetLastError());
}
return 0;
}
This was compiled on Windows XP.
Output on Windows XP:
Failed to locate function: 127
where 127 means The specified procedure could not be found.
Output on Windows Vista:
C:\Users\admin
You can always use getenv("HOMEDRIVE") and getenv("HOMEPATH") and concatenate the results.
std::string home = std::string(getenv("HOMEDRIVE")) + getenv("HOMEPATH");
The Windows equivalent of HOME is USERPROFILE. It is an ordinary environment variable just like in Linux. You can make the following call to retrieve it:
char *profilepath = getenv("USERPROFILE");

GetLastError called in a catch block yields incorrect value

Fun exploring some legacy code today. Ran into this little number:
function Func1()
{
DWORD dwError;
try
{
dwError = 1;
throw "Hey!";
} catch (LPCTSTR szError)
{
Log("Log1: %d", dwError);
SetLastError(dwError);
throw szError;
}
}
function Func2()
{
try {
Func1();
}
catch (LPCTSTR szError)
{
DWORD dwLastError = GetLastError();
Log("Log2: %d", dwLastError); ///OMG is 0!
}
}
GetLastError() returns 0! Why is that? The functions are actually a bit more complicated than this. They do include a few things on the stack (DWORDs, CString, BYTE[]). What should I be looking for?
Logs look like:
Log1: 1
Log2: 0
C++ exceptions in the MSVC compiler and runtime are built on top of native Windows SEH. Stack unwinding is actually performed by Windows. Using Windows api functions is going to affect the value stored for GetLastError(). More details about the connection with SEH in this answer.