From 10ebf674da5df9224e4eddd3545518434c5b455b Mon Sep 17 00:00:00 2001 From: Sean Hall Date: Tue, 2 Mar 2021 14:19:14 -0600 Subject: Update rest of dutil to use their own source with the Exit* macros. Fix some CA warnings. --- src/dutil/acl2util.cpp | 30 ++++-- src/dutil/aclutil.cpp | 126 ++++++++++++---------- src/dutil/apputil.cpp | 21 +++- src/dutil/apuputil.cpp | 116 ++++++++++++--------- src/dutil/atomutil.cpp | 233 +++++++++++++++++++++-------------------- src/dutil/buffutil.cpp | 99 ++++++++++-------- src/dutil/cabcutil.cpp | 218 ++++++++++++++++++++------------------ src/dutil/cabutil.cpp | 96 ++++++++++------- src/dutil/certutil.cpp | 59 +++++++---- src/dutil/conutil.cpp | 77 ++++++++------ src/dutil/cryputil.cpp | 63 ++++++----- src/dutil/deputil.cpp | 145 ++++++++++++++------------ src/dutil/dictutil.cpp | 111 +++++++++++--------- src/dutil/dirutil.cpp | 61 +++++++---- src/dutil/dlutil.cpp | 89 +++++++++------- src/dutil/dutil.cpp | 29 ++++-- src/dutil/eseutil.cpp | 101 ++++++++++-------- src/dutil/fileutil.cpp | 265 +++++++++++++++++++++++++---------------------- src/dutil/gdiputil.cpp | 35 +++++-- src/dutil/guidutil.cpp | 23 +++- src/dutil/iis7util.cpp | 57 ++++++---- src/dutil/inc/atomutil.h | 2 +- src/dutil/inc/buffutil.h | 14 +-- src/dutil/inc/conutil.h | 4 +- src/dutil/inc/deputil.h | 2 +- src/dutil/inc/dutil.h | 2 +- src/dutil/inc/eseutil.h | 2 +- src/dutil/inc/fileutil.h | 2 +- src/dutil/inc/inetutil.h | 2 +- src/dutil/inc/iniutil.h | 2 +- src/dutil/inc/memutil.h | 6 +- src/dutil/inc/pathutil.h | 6 +- src/dutil/inc/regutil.h | 8 +- src/dutil/inc/shelutil.h | 6 +- src/dutil/inc/strutil.h | 4 +- src/dutil/inc/thmutil.h | 2 +- src/dutil/inc/uriutil.h | 2 +- src/dutil/inc/wiutil.h | 2 +- src/dutil/inetutil.cpp | 37 +++++-- src/dutil/iniutil.cpp | 107 +++++++++++-------- src/dutil/jsonutil.cpp | 79 ++++++++------ src/dutil/locutil.cpp | 125 ++++++++++++---------- src/dutil/logutil.cpp | 67 +++++++----- src/dutil/memutil.cpp | 51 +++++---- src/dutil/metautil.cpp | 37 +++++-- src/dutil/monutil.cpp | 205 +++++++++++++++++++----------------- src/dutil/osutil.cpp | 29 ++++-- src/dutil/path2utl.cpp | 21 +++- src/dutil/pathutil.cpp | 175 +++++++++++++++++-------------- src/dutil/perfutil.cpp | 15 +++ src/dutil/polcutil.cpp | 27 +++-- src/dutil/proc2utl.cpp | 21 +++- src/dutil/proc3utl.cpp | 27 +++-- src/dutil/procutil.cpp | 57 ++++++---- src/dutil/regutil.cpp | 137 +++++++++++++----------- src/dutil/resrutil.cpp | 45 +++++--- src/dutil/reswutil.cpp | 65 +++++++----- src/dutil/rexutil.cpp | 59 +++++++---- src/dutil/rmutil.cpp | 63 ++++++----- src/dutil/rssutil.cpp | 125 ++++++++++++---------- src/dutil/shelutil.cpp | 69 +++++++----- src/dutil/sqlutil.cpp | 119 +++++++++++---------- src/dutil/srputil.cpp | 43 +++++--- src/dutil/strutil.cpp | 215 ++++++++++++++++++++------------------ src/dutil/svcutil.cpp | 21 +++- src/dutil/thmutil.cpp | 8 +- src/dutil/timeutil.cpp | 37 +++++-- src/dutil/uncutil.cpp | 25 ++++- src/dutil/uriutil.cpp | 93 ++++++++++------- src/dutil/userutil.cpp | 61 +++++++---- src/dutil/wiutil.cpp | 121 ++++++++++++---------- src/dutil/wuautil.cpp | 31 ++++-- src/dutil/xmlutil.cpp | 193 ++++++++++++++++++---------------- 73 files changed, 2779 insertions(+), 1953 deletions(-) (limited to 'src') diff --git a/src/dutil/acl2util.cpp b/src/dutil/acl2util.cpp index 2261abe3..5aba60f0 100644 --- a/src/dutil/acl2util.cpp +++ b/src/dutil/acl2util.cpp @@ -2,6 +2,20 @@ #include "precomp.h" +// Exit macros +#define AclExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_ACLUTIL, x, s, __VA_ARGS__) +#define AclExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_ACLUTIL, x, s, __VA_ARGS__) +#define AclExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_ACLUTIL, x, s, __VA_ARGS__) +#define AclExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_ACLUTIL, x, s, __VA_ARGS__) +#define AclExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_ACLUTIL, x, s, __VA_ARGS__) +#define AclExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_ACLUTIL, x, s, __VA_ARGS__) +#define AclExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_ACLUTIL, p, x, e, s, __VA_ARGS__) +#define AclExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_ACLUTIL, p, x, s, __VA_ARGS__) +#define AclExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_ACLUTIL, p, x, e, s, __VA_ARGS__) +#define AclExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_ACLUTIL, p, x, s, __VA_ARGS__) +#define AclExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_ACLUTIL, e, x, s, __VA_ARGS__) +#define AclExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_ACLUTIL, g, x, s, __VA_ARGS__) + /******************************************************************** AclCalculateServiceSidString - gets the SID string for the given service name @@ -26,17 +40,17 @@ extern "C" HRESULT DAPI AclCalculateServiceSidString( if (0 == cchServiceName) { hr = ::StringCchLengthW(wzServiceName, INT_MAX, reinterpret_cast(&cchServiceName)); - ExitOnFailure(hr, "Failed to get the length of the service name."); + AclExitOnFailure(hr, "Failed to get the length of the service name."); } hr = StrAllocStringToUpperInvariant(&sczUpperServiceName, wzServiceName, cchServiceName); - ExitOnFailure(hr, "Failed to upper case the service name."); + AclExitOnFailure(hr, "Failed to upper case the service name."); pbHash = reinterpret_cast(MemAlloc(cbHash, TRUE)); - ExitOnNull(pbHash, hr, E_OUTOFMEMORY, "Failed to allocate hash byte array."); + AclExitOnNull(pbHash, hr, E_OUTOFMEMORY, "Failed to allocate hash byte array."); hr = CrypHashBuffer(reinterpret_cast(sczUpperServiceName), cchServiceName * 2, PROV_RSA_FULL, CALG_SHA1, pbHash, cbHash); - ExitOnNull(pbHash, hr, E_OUTOFMEMORY, "Failed to hash the service name."); + AclExitOnNull(pbHash, hr, E_OUTOFMEMORY, "Failed to hash the service name."); hr = StrAllocFormatted(psczSid, L"S-1-5-80-%u-%u-%u-%u-%u", MAKEDWORD(MAKEWORD(pbHash[0], pbHash[1]), MAKEWORD(pbHash[2], pbHash[3])), @@ -80,7 +94,7 @@ extern "C" HRESULT DAPI AclGetAccountSidStringEx( if (!::ConvertSidToStringSidW(psid, &pwz)) { - ExitWithLastError(hr, "Failed to convert SID to string for Account: %ls", wzAccount); + AclExitWithLastError(hr, "Failed to convert SID to string for Account: %ls", wzAccount); } hr = StrAllocString(psczSid, pwz, 0); @@ -90,20 +104,20 @@ extern "C" HRESULT DAPI AclGetAccountSidStringEx( if (HRESULT_FROM_WIN32(ERROR_NONE_MAPPED) == hr) { HRESULT hrLength = ::StringCchLengthW(wzAccount, INT_MAX, reinterpret_cast(&cchAccount)); - ExitOnFailure(hrLength, "Failed to get the length of the account name."); + AclExitOnFailure(hrLength, "Failed to get the length of the account name."); if (11 < cchAccount && CSTR_EQUAL == CompareStringW(LOCALE_NEUTRAL, NORM_IGNORECASE, L"NT SERVICE\\", 11, wzAccount, 11)) { // If the service is not installed then LookupAccountName doesn't resolve the SID, but we can calculate it. LPCWSTR wzServiceName = &wzAccount[11]; hr = AclCalculateServiceSidString(wzServiceName, cchAccount - 11, &sczSid); - ExitOnFailure(hr, "Failed to calculate the service SID for %ls", wzServiceName); + AclExitOnFailure(hr, "Failed to calculate the service SID for %ls", wzServiceName); *psczSid = sczSid; sczSid = NULL; } } - ExitOnFailure(hr, "Failed to get SID for account: %ls", wzAccount); + AclExitOnFailure(hr, "Failed to get SID for account: %ls", wzAccount); } LExit: diff --git a/src/dutil/aclutil.cpp b/src/dutil/aclutil.cpp index fc01ecc8..c9733033 100644 --- a/src/dutil/aclutil.cpp +++ b/src/dutil/aclutil.cpp @@ -2,6 +2,20 @@ #include "precomp.h" +// Exit macros +#define AclExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_ACLUTIL, x, s, __VA_ARGS__) +#define AclExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_ACLUTIL, x, s, __VA_ARGS__) +#define AclExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_ACLUTIL, x, s, __VA_ARGS__) +#define AclExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_ACLUTIL, x, s, __VA_ARGS__) +#define AclExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_ACLUTIL, x, s, __VA_ARGS__) +#define AclExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_ACLUTIL, x, s, __VA_ARGS__) +#define AclExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_ACLUTIL, p, x, e, s, __VA_ARGS__) +#define AclExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_ACLUTIL, p, x, s, __VA_ARGS__) +#define AclExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_ACLUTIL, p, x, e, s, __VA_ARGS__) +#define AclExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_ACLUTIL, p, x, s, __VA_ARGS__) +#define AclExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_ACLUTIL, e, x, s, __VA_ARGS__) +#define AclExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_ACLUTIL, g, x, s, __VA_ARGS__) + /******************************************************************** AclCheckAccess - determines if token has appropriate privileges @@ -18,25 +32,25 @@ extern "C" HRESULT DAPI AclCheckAccess( PSID psid = NULL; BOOL fIsMember = FALSE; - ExitOnNull(paa, hr, E_INVALIDARG, "Failed to check ACL access, because no acl access provided to check"); + AclExitOnNull(paa, hr, E_INVALIDARG, "Failed to check ACL access, because no acl access provided to check"); Assert(0 == paa->fDenyAccess && 0 == paa->dwAccessMask); if (paa->pwzAccountName) { hr = AclGetAccountSid(NULL, paa->pwzAccountName, &psid); - ExitOnFailure(hr, "failed to get SID for account: %ls", paa->pwzAccountName); + AclExitOnFailure(hr, "failed to get SID for account: %ls", paa->pwzAccountName); } else { if (!::AllocateAndInitializeSid(&paa->sia, paa->nSubAuthorityCount, paa->nSubAuthority[0], paa->nSubAuthority[1], paa->nSubAuthority[2], paa->nSubAuthority[3], paa->nSubAuthority[4], paa->nSubAuthority[5], paa->nSubAuthority[6], paa->nSubAuthority[7], &psid)) { - ExitWithLastError(hr, "failed to initialize SID"); + AclExitWithLastError(hr, "failed to initialize SID"); } } if (!::CheckTokenMembership(hToken, psid, &fIsMember)) { - ExitWithLastError(hr, "failed to check membership"); + AclExitWithLastError(hr, "failed to check membership"); } fIsMember ? hr = S_OK : hr = S_FALSE; @@ -123,7 +137,7 @@ extern "C" HRESULT DAPI AclGetWellKnownSid( // allocate memory for the SID and get it // psid = static_cast(MemAlloc(cbSid, TRUE)); - ExitOnNull(psid, hr, E_OUTOFMEMORY, "failed allocate memory for well known SID"); + AclExitOnNull(psid, hr, E_OUTOFMEMORY, "failed allocate memory for well known SID"); #if(_WIN32_WINNT < 0x0501) switch (wkst) @@ -160,19 +174,19 @@ extern "C" HRESULT DAPI AclGetWellKnownSid( break; default: hr = E_INVALIDARG; - ExitOnFailure(hr, "unknown well known SID: %d", wkst); + AclExitOnFailure(hr, "unknown well known SID: %d", wkst); } if (!fSuccess) - ExitOnLastError(hr, "failed to allocate well known SID: %d", wkst); + AclExitOnLastError(hr, "failed to allocate well known SID: %d", wkst); if (!::CopySid(cbSid, psid, psidTemp)) - ExitOnLastError(hr, "failed to create well known SID: %d", wkst); + AclExitOnLastError(hr, "failed to create well known SID: %d", wkst); #else Assert(NULL == psidTemp); if (!::CreateWellKnownSid(wkst, NULL, psid, &cbSid)) { - ExitWithLastError(hr, "failed to create well known SID: %d", wkst); + AclExitWithLastError(hr, "failed to create well known SID: %d", wkst); } #endif @@ -216,9 +230,9 @@ extern "C" HRESULT DAPI AclGetAccountSid( // allocate memory for the SID and domain name // psid = static_cast(MemAlloc(cbSid, TRUE)); - ExitOnNull(psid, hr, E_OUTOFMEMORY, "failed to allocate memory for SID"); + AclExitOnNull(psid, hr, E_OUTOFMEMORY, "failed to allocate memory for SID"); hr = StrAlloc(&pwzDomainName, cbDomainName); - ExitOnFailure(hr, "failed to allocate string for domain name"); + AclExitOnFailure(hr, "failed to allocate string for domain name"); // // try to lookup the account now @@ -232,24 +246,24 @@ extern "C" HRESULT DAPI AclGetAccountSid( if (SECURITY_MAX_SID_SIZE < cbSid) { PSID psidNew = static_cast(MemReAlloc(psid, cbSid, TRUE)); - ExitOnNullWithLastError(psidNew, hr, "failed to allocate memory for account: %ls", wzAccount); + AclExitOnNullWithLastError(psidNew, hr, "failed to allocate memory for account: %ls", wzAccount); psid = psidNew; } if (255 < cbDomainName) { hr = StrAlloc(&pwzDomainName, cbDomainName); - ExitOnFailure(hr, "failed to allocate string for domain name"); + AclExitOnFailure(hr, "failed to allocate string for domain name"); } if (!::LookupAccountNameW(wzSystem, wzAccount, psid, &cbSid, pwzDomainName, &cbDomainName, &peUse)) { - ExitWithLastError(hr, "failed to lookup account: %ls", wzAccount); + AclExitWithLastError(hr, "failed to lookup account: %ls", wzAccount); } } else { - ExitOnWin32Error(er, hr, "failed to lookup account: %ls", wzAccount); + AclExitOnWin32Error(er, hr, "failed to lookup account: %ls", wzAccount); } } @@ -284,12 +298,12 @@ extern "C" HRESULT DAPI AclGetAccountSidString( *ppwzSid = NULL; hr = AclGetAccountSid(wzSystem, wzAccount, &psid); - ExitOnFailure(hr, "failed to get SID for account: %ls", wzAccount); + AclExitOnFailure(hr, "failed to get SID for account: %ls", wzAccount); Assert(::IsValidSid(psid)); if (!::ConvertSidToStringSidW(psid, &pwz)) { - ExitWithLastError(hr, "failed to convert SID to string for Account: %ls", wzAccount); + AclExitWithLastError(hr, "failed to convert SID to string for Account: %ls", wzAccount); } hr = StrAllocString(ppwzSid, pwz, 0); @@ -347,14 +361,14 @@ extern "C" HRESULT DAPI AclCreateDacl( } pAcl = static_cast(MemAlloc(cbAcl, TRUE)); - ExitOnNull(pAcl, hr, E_OUTOFMEMORY, "failed to allocate ACL"); + AclExitOnNull(pAcl, hr, E_OUTOFMEMORY, "failed to allocate ACL"); #pragma prefast(push) #pragma prefast(disable:25029) if (!::InitializeAcl(pAcl, cbAcl, ACL_REVISION)) #pragma prefast(pop) { - ExitWithLastError(hr, "failed to initialize ACL"); + AclExitWithLastError(hr, "failed to initialize ACL"); } // add in the ACEs (denied first) @@ -365,7 +379,7 @@ extern "C" HRESULT DAPI AclCreateDacl( if (!::AddAccessDeniedAceEx(pAcl, ACL_REVISION, rgaaDeny[i].dwFlags, rgaaDeny[i].dwMask, rgaaDeny[i].psid)) #pragma prefast(pop) { - ExitWithLastError(hr, "failed to add access denied ACE #%d to ACL", i); + AclExitWithLastError(hr, "failed to add access denied ACE #%d to ACL", i); } } for (i = 0; i < cAllow; ++i) @@ -375,7 +389,7 @@ extern "C" HRESULT DAPI AclCreateDacl( if (!::AddAccessAllowedAceEx(pAcl, ACL_REVISION, rgaaAllow[i].dwFlags, rgaaAllow[i].dwMask, rgaaAllow[i].psid)) #pragma prefast(pop) { - ExitWithLastError(hr, "failed to add access allowed ACE #$d to ACL", i); + AclExitWithLastError(hr, "failed to add access allowed ACE #%d to ACL", i); } } @@ -422,7 +436,7 @@ extern "C" HRESULT DAPI AclAddToDacl( // allocate memory for all the new ACEs (NOTE: this over calculates the memory necessary, but that's okay) if (!::GetAclInformation(pAcl, &asi, sizeof(asi), AclSizeInformation)) { - ExitWithLastError(hr, "failed to get information about original ACL"); + AclExitWithLastError(hr, "failed to get information about original ACL"); } if ((asi.AceCount + cDeny) < asi.AceCount || // check for overflow @@ -430,29 +444,29 @@ extern "C" HRESULT DAPI AclAddToDacl( (asi.AceCount + cDeny) >= MAXSIZE_T / sizeof(ACL_ACE)) { hr = E_OUTOFMEMORY; - ExitOnFailure(hr, "Not enough memory to allocate %d ACEs", (asi.AceCount + cDeny)); + AclExitOnFailure(hr, "Not enough memory to allocate %d ACEs", (asi.AceCount + cDeny)); } paaNewDeny = static_cast(MemAlloc(sizeof(ACL_ACE) * (asi.AceCount + cDeny), TRUE)); - ExitOnNull(paaNewDeny, hr, E_OUTOFMEMORY, "failed to allocate memory for new deny ACEs"); + AclExitOnNull(paaNewDeny, hr, E_OUTOFMEMORY, "failed to allocate memory for new deny ACEs"); if ((asi.AceCount + cAllow) < asi.AceCount || // check for overflow (asi.AceCount + cAllow) < cAllow || // check for overflow (asi.AceCount + cAllow) >= MAXSIZE_T / sizeof(ACL_ACE)) { hr = E_OUTOFMEMORY; - ExitOnFailure(hr, "Not enough memory to allocate %d ACEs", (asi.AceCount + cAllow)); + AclExitOnFailure(hr, "Not enough memory to allocate %d ACEs", (asi.AceCount + cAllow)); } paaNewAllow = static_cast(MemAlloc(sizeof(ACL_ACE) * (asi.AceCount + cAllow), TRUE)); - ExitOnNull(paaNewAllow, hr, E_OUTOFMEMORY, "failed to allocate memory for new allow ACEs"); + AclExitOnNull(paaNewAllow, hr, E_OUTOFMEMORY, "failed to allocate memory for new allow ACEs"); // fill in the new structures with old data then new data (denied first) for (i = 0; i < asi.AceCount; ++i) { if (!::GetAce(pAcl, i, reinterpret_cast(&pada))) { - ExitWithLastError(hr, "failed to get ACE #%d from ACL", i); + AclExitWithLastError(hr, "failed to get ACE #%d from ACL", i); } if (ACCESS_DENIED_ACE_TYPE != pada->Header.AceType) @@ -474,7 +488,7 @@ extern "C" HRESULT DAPI AclAddToDacl( { if (!::GetAce(pAcl, i, reinterpret_cast(&paaa))) { - ExitWithLastError(hr, "failed to get ACE #%d from ACL", i); + AclExitWithLastError(hr, "failed to get ACE #%d from ACL", i); } if (ACCESS_ALLOWED_ACE_TYPE != paaa->Header.AceType) @@ -493,7 +507,7 @@ extern "C" HRESULT DAPI AclAddToDacl( // create the dacl with the new hr = AclCreateDacl(paaNewDeny, cNewDeny, paaNewAllow, cNewAllow, ppAclNew); - ExitOnFailure(hr, "failed to create new ACL from existing ACL"); + AclExitOnFailure(hr, "failed to create new ACL from existing ACL"); AssertSz(::IsValidAcl(*ppAclNew), "AclAddToDacl() - created invalid ACL"); Assert(S_OK == hr); @@ -551,9 +565,9 @@ extern "C" HRESULT DAPI AclCreateDaclOld( // create the SIDs and calculate the space for the ACL // pdwAccessMask = static_cast(MemAlloc(sizeof(DWORD) * cAclAccesses, TRUE)); - ExitOnNull(pdwAccessMask, hr, E_OUTOFMEMORY, "failed allocate memory for access mask"); + AclExitOnNull(pdwAccessMask, hr, E_OUTOFMEMORY, "failed allocate memory for access mask"); ppsid = static_cast(MemAlloc(sizeof(PSID) * cAclAccesses, TRUE)); - ExitOnNull(ppsid, hr, E_OUTOFMEMORY, "failed allocate memory for sid"); + AclExitOnNull(ppsid, hr, E_OUTOFMEMORY, "failed allocate memory for sid"); cbAcl = sizeof (ACL); // start with the size of the header for (i = 0; i < cAclAccesses; ++i) @@ -561,7 +575,7 @@ extern "C" HRESULT DAPI AclCreateDaclOld( if (paa[i].pwzAccountName) { hr = AclGetAccountSid(NULL, paa[i].pwzAccountName, ppsid + i); - ExitOnFailure(hr, "failed to get SID for account: %ls", paa[i].pwzAccountName); + AclExitOnFailure(hr, "failed to get SID for account: %ls", paa[i].pwzAccountName); } else { @@ -572,7 +586,7 @@ extern "C" HRESULT DAPI AclCreateDaclOld( paa[i].nSubAuthority[6], paa[i].nSubAuthority[7], (void**)(ppsid + i)))) { - ExitWithLastError(hr, "failed to initialize SIDs #%u", i); + AclExitWithLastError(hr, "failed to initialize SIDs #%u", i); } } @@ -594,14 +608,14 @@ extern "C" HRESULT DAPI AclCreateDaclOld( // allocate the ACL and set the appropriate ACEs // *ppACL = static_cast(MemAlloc(cbAcl, FALSE)); - ExitOnNull(*ppACL, hr, E_OUTOFMEMORY, "failed allocate memory for ACL"); + AclExitOnNull(*ppACL, hr, E_OUTOFMEMORY, "failed allocate memory for ACL"); #pragma prefast(push) #pragma prefast(disable:25029) if (!::InitializeAcl(*ppACL, cbAcl, ACL_REVISION)) #pragma prefast(pop) { - ExitWithLastError(hr, "failed to initialize ACLs"); + AclExitWithLastError(hr, "failed to initialize ACLs"); } // add an access-allowed ACE for each of the SIDs @@ -614,7 +628,7 @@ extern "C" HRESULT DAPI AclCreateDaclOld( if (!::AddAccessDeniedAceEx(*ppACL, ACL_REVISION, CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE, pdwAccessMask[i], *(ppsid + i))) #pragma prefast(pop) { - ExitWithLastError(hr, "failed to add access denied for ACE"); + AclExitWithLastError(hr, "failed to add access denied for ACE"); } } else @@ -624,7 +638,7 @@ extern "C" HRESULT DAPI AclCreateDaclOld( if (!::AddAccessAllowedAceEx(*ppACL, ACL_REVISION, CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE, pdwAccessMask[i], *(ppsid + i))) #pragma prefast(pop) { - ExitWithLastError(hr, "failed to add access allowed for ACE"); + AclExitWithLastError(hr, "failed to add access allowed for ACE"); } } } @@ -669,8 +683,8 @@ extern "C" HRESULT DAPI AclCreateSecurityDescriptorFromDacl( SECURITY_DESCRIPTOR sd; DWORD cbSD; - ExitOnNull(pACL, hr, E_INVALIDARG, "Failed to create security descriptor from DACL, because no DACL was provided"); - ExitOnNull(ppsd, hr, E_INVALIDARG, "Failed to create security descriptor from DACL, because no output object was provided"); + AclExitOnNull(pACL, hr, E_INVALIDARG, "Failed to create security descriptor from DACL, because no DACL was provided"); + AclExitOnNull(ppsd, hr, E_INVALIDARG, "Failed to create security descriptor from DACL, because no output object was provided"); *ppsd = NULL; @@ -687,7 +701,7 @@ extern "C" HRESULT DAPI AclCreateSecurityDescriptorFromDacl( (!::SetSecurityDescriptorOwner(&sd, NULL, FALSE))) #pragma prefast(pop) { - ExitWithLastError(hr, "failed to initialize security descriptor"); + AclExitWithLastError(hr, "failed to initialize security descriptor"); } // @@ -695,7 +709,7 @@ extern "C" HRESULT DAPI AclCreateSecurityDescriptorFromDacl( // cbSD = ::GetSecurityDescriptorLength(&sd); *ppsd = static_cast(MemAlloc(cbSD, FALSE)); - ExitOnNull(*ppsd, hr, E_OUTOFMEMORY, "failed allocate memory for security descriptor"); + AclExitOnNull(*ppsd, hr, E_OUTOFMEMORY, "failed allocate memory for security descriptor"); ::MakeSelfRelativeSD(&sd, (BYTE*)*ppsd, &cbSD); Assert(::IsValidSecurityDescriptor(*ppsd)); @@ -734,7 +748,7 @@ extern "C" HRESULT DAPI AclCreateSecurityDescriptor( // create the DACL // hr = AclCreateDaclOld(paa, cAclAccesses, &pACL); - ExitOnFailure(hr, "failed to create DACL for security descriptor"); + AclExitOnFailure(hr, "failed to create DACL for security descriptor"); // // create self-relative security descriptor @@ -770,15 +784,15 @@ extern "C" HRESULT DAPI AclCreateSecurityDescriptorFromString( va_start(args, wzSddlFormat); hr = StrAllocFormattedArgs(&pwzSddl, wzSddlFormat, args); va_end(args); - ExitOnFailure(hr, "failed to create SDDL string for format: %ls", wzSddlFormat); + AclExitOnFailure(hr, "failed to create SDDL string for format: %ls", wzSddlFormat); if (!::ConvertStringSecurityDescriptorToSecurityDescriptorW(pwzSddl, SDDL_REVISION_1, &psd, &cbSD)) { - ExitWithLastError(hr, "failed to create security descriptor from SDDL: %ls", pwzSddl); + AclExitWithLastError(hr, "failed to create security descriptor from SDDL: %ls", pwzSddl); } *ppsd = static_cast(MemAlloc(cbSD, FALSE)); - ExitOnNull(*ppsd, hr, E_OUTOFMEMORY, "failed to allocate memory for security descriptor"); + AclExitOnNull(*ppsd, hr, E_OUTOFMEMORY, "failed to allocate memory for security descriptor"); memcpy(*ppsd, psd, cbSD); Assert(::IsValidSecurityDescriptor(*ppsd)); @@ -815,7 +829,7 @@ extern "C" HRESULT DAPI AclDuplicateSecurityDescriptor( HRESULT hr = S_OK; DWORD cbSD; - ExitOnNull(ppsd, hr, E_INVALIDARG, "Failed to get duplicate ACL security descriptor because no place to output was provided"); + AclExitOnNull(ppsd, hr, E_INVALIDARG, "Failed to get duplicate ACL security descriptor because no place to output was provided"); *ppsd = NULL; // @@ -823,7 +837,7 @@ extern "C" HRESULT DAPI AclDuplicateSecurityDescriptor( // cbSD = ::GetSecurityDescriptorLength(psd); *ppsd = static_cast(MemAlloc(cbSD, 0)); - ExitOnNull(*ppsd, hr, E_OUTOFMEMORY, "failed allocate memory for security descriptor"); + AclExitOnNull(*ppsd, hr, E_OUTOFMEMORY, "failed allocate memory for security descriptor"); memcpy(*ppsd, psd, cbSD); Assert(::IsValidSecurityDescriptor(*ppsd)); @@ -856,18 +870,18 @@ extern "C" HRESULT DAPI AclGetSecurityDescriptor( PSECURITY_DESCRIPTOR psd = NULL; DWORD cbSD; - ExitOnNull(ppsd, hr, E_INVALIDARG, "Failed to get ACL Security Descriptor because no place to output was provided"); + AclExitOnNull(ppsd, hr, E_INVALIDARG, "Failed to get ACL Security Descriptor because no place to output was provided"); *ppsd = NULL; // get the security descriptor for the object er = ::GetNamedSecurityInfoW(const_cast(wzObject), sot, securityInformation, NULL, NULL, NULL, NULL, &psd); - ExitOnWin32Error(er, hr, "failed to get security info from object: %ls", wzObject); + AclExitOnWin32Error(er, hr, "failed to get security info from object: %ls", wzObject); Assert(::IsValidSecurityDescriptor(psd)); // copy the self-relative security descriptor cbSD = ::GetSecurityDescriptorLength(psd); *ppsd = static_cast(MemAlloc(cbSD, 0)); - ExitOnNull(*ppsd, hr, E_OUTOFMEMORY, "failed allocate memory for security descriptor"); + AclExitOnNull(*ppsd, hr, E_OUTOFMEMORY, "failed allocate memory for security descriptor"); memcpy(*ppsd, psd, cbSD); Assert(::IsValidSecurityDescriptor(*ppsd)); @@ -905,7 +919,7 @@ extern "C" HRESULT DAPI AclSetSecurityWithRetry( DWORD i = 0; hr = StrAllocString(&sczObject, wzObject, 0); - ExitOnFailure(hr, "Failed to copy object to secure."); + AclExitOnFailure(hr, "Failed to copy object to secure."); hr = E_FAIL; for (i = 0; FAILED(hr) && i <= cRetry; ++i) @@ -918,7 +932,7 @@ extern "C" HRESULT DAPI AclSetSecurityWithRetry( DWORD er = ::SetNamedSecurityInfoW(sczObject, sot, securityInformation, psidOwner, psidGroup, pDacl, pSacl); hr = HRESULT_FROM_WIN32(er); } - ExitOnRootFailure(hr, "Failed to set security on object '%ls' after %u retries.", wzObject, i); + AclExitOnRootFailure(hr, "Failed to set security on object '%ls' after %u retries.", wzObject, i); LExit: ReleaseStr(sczObject); @@ -996,20 +1010,20 @@ extern "C" HRESULT DAPI AclAddAdminToSecurityDescriptor( if (!::GetSecurityDescriptorDacl(pSecurity, &fValid, &pAcl, &fDaclDefaulted) || !fValid) { - ExitOnLastError(hr, "Failed to get acl from security descriptor"); + AclExitOnLastError(hr, "Failed to get acl from security descriptor"); } hr = AclGetWellKnownSid(WinBuiltinAdministratorsSid, &ace[0].psid); - ExitOnFailure(hr, "failed to get sid for Administrators group"); + AclExitOnFailure(hr, "failed to get sid for Administrators group"); ace[0].dwFlags = NO_PROPAGATE_INHERIT_ACE; ace[0].dwMask = GENERIC_ALL; hr = AclAddToDacl(pAcl, NULL, 0, ace, 1, &pAclNew); - ExitOnFailure(hr, "failed to add Administrators ACE to ACL"); + AclExitOnFailure(hr, "failed to add Administrators ACE to ACL"); hr = AclCreateSecurityDescriptorFromDacl(pAclNew, &pSecurityNew); - ExitOnLastError(hr, "Failed to create new security descriptor"); + AclExitOnLastError(hr, "Failed to create new security descriptor"); // The DACL is referenced by, not copied into, the security descriptor. Make sure not to free it. pAclNew = NULL; diff --git a/src/dutil/apputil.cpp b/src/dutil/apputil.cpp index 8562a47a..589a09dd 100644 --- a/src/dutil/apputil.cpp +++ b/src/dutil/apputil.cpp @@ -2,6 +2,20 @@ #include "precomp.h" +// Exit macros +#define AppExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_APPUTIL, x, s, __VA_ARGS__) +#define AppExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_APPUTIL, x, s, __VA_ARGS__) +#define AppExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_APPUTIL, x, s, __VA_ARGS__) +#define AppExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_APPUTIL, x, s, __VA_ARGS__) +#define AppExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_APPUTIL, x, s, __VA_ARGS__) +#define AppExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_APPUTIL, x, s, __VA_ARGS__) +#define AppExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_APPUTIL, p, x, e, s, __VA_ARGS__) +#define AppExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_APPUTIL, p, x, s, __VA_ARGS__) +#define AppExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_APPUTIL, p, x, e, s, __VA_ARGS__) +#define AppExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_APPUTIL, p, x, s, __VA_ARGS__) +#define AppExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_APPUTIL, e, x, s, __VA_ARGS__) +#define AppExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_APPUTIL, g, x, s, __VA_ARGS__) + const DWORD PRIVATE_LOAD_LIBRARY_SEARCH_SYSTEM32 = 0x00000800; typedef BOOL(WINAPI *LPFN_SETDEFAULTDLLDIRECTORIES)(DWORD); typedef BOOL(WINAPI *LPFN_SETDLLDIRECTORYW)(LPCWSTR); @@ -33,6 +47,7 @@ extern "C" void DAPI AppInitialize( // Best effort call to initialize default DLL directories to system only. HMODULE hKernel32 = ::GetModuleHandleW(L"kernel32"); + Assert(hKernel32); LPFN_SETDEFAULTDLLDIRECTORIES pfnSetDefaultDllDirectories = (LPFN_SETDEFAULTDLLDIRECTORIES)::GetProcAddress(hKernel32, "SetDefaultDllDirectories"); if (pfnSetDefaultDllDirectories) { @@ -90,13 +105,13 @@ extern "C" DAPI_(HRESULT) AppParseCommandLine( // which fails pretty miserably if your first argument is something like // FOO="C:\Program Files\My Company". So give it something harmless to play with. hr = StrAllocConcat(&sczCommandLine, L"ignored ", 0); - ExitOnFailure(hr, "Failed to initialize command line."); + AppExitOnFailure(hr, "Failed to initialize command line."); hr = StrAllocConcat(&sczCommandLine, wzCommandLine, 0); - ExitOnFailure(hr, "Failed to copy command line."); + AppExitOnFailure(hr, "Failed to copy command line."); argv = ::CommandLineToArgvW(sczCommandLine, &argc); - ExitOnNullWithLastError(argv, hr, "Failed to parse command line."); + AppExitOnNullWithLastError(argv, hr, "Failed to parse command line."); // Skip "ignored" argument/hack. *pArgv = argv + 1; diff --git a/src/dutil/apuputil.cpp b/src/dutil/apuputil.cpp index bf655ecc..07d591a7 100644 --- a/src/dutil/apuputil.cpp +++ b/src/dutil/apuputil.cpp @@ -2,6 +2,20 @@ #include "precomp.h" +// Exit macros +#define ApupExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_APUPUTIL, x, s, __VA_ARGS__) +#define ApupExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_APUPUTIL, x, s, __VA_ARGS__) +#define ApupExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_APUPUTIL, x, s, __VA_ARGS__) +#define ApupExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_APUPUTIL, x, s, __VA_ARGS__) +#define ApupExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_APUPUTIL, x, s, __VA_ARGS__) +#define ApupExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_APUPUTIL, x, s, __VA_ARGS__) +#define ApupExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_APUPUTIL, p, x, e, s, __VA_ARGS__) +#define ApupExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_APUPUTIL, p, x, s, __VA_ARGS__) +#define ApupExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_APUPUTIL, p, x, e, s, __VA_ARGS__) +#define ApupExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_APUPUTIL, p, x, s, __VA_ARGS__) +#define ApupExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_APUPUTIL, e, x, s, __VA_ARGS__) +#define ApupExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_APUPUTIL, g, x, s, __VA_ARGS__) + // prototypes static HRESULT ProcessEntry( __in ATOM_ENTRY* pAtomEntry, @@ -61,14 +75,14 @@ extern "C" HRESULT DAPI ApupAllocChainFromAtom( if (CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, 0, pElement->wzElement, -1, L"application", -1)) { hr = StrAllocString(&pChain->wzDefaultApplicationId, pElement->wzValue, 0); - ExitOnFailure(hr, "Failed to allocate default application id."); + ApupExitOnFailure(hr, "Failed to allocate default application id."); for (ATOM_UNKNOWN_ATTRIBUTE* pAttribute = pElement->pAttributes; pAttribute; pAttribute = pAttribute->pNext) { if (CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, 0, pAttribute->wzAttribute, -1, L"type", -1)) { hr = StrAllocString(&pChain->wzDefaultApplicationType, pAttribute->wzValue, 0); - ExitOnFailure(hr, "Failed to allocate default application type."); + ApupExitOnFailure(hr, "Failed to allocate default application type."); } } } @@ -79,13 +93,13 @@ extern "C" HRESULT DAPI ApupAllocChainFromAtom( if (pFeed->cEntries) { pChain->rgEntries = static_cast(MemAlloc(sizeof(APPLICATION_UPDATE_ENTRY) * pFeed->cEntries, TRUE)); - ExitOnNull(pChain->rgEntries, hr, E_OUTOFMEMORY, "Failed to allocate memory for update entries."); + ApupExitOnNull(pChain->rgEntries, hr, E_OUTOFMEMORY, "Failed to allocate memory for update entries."); // Process each entry, building up the chain. for (DWORD i = 0; i < pFeed->cEntries; ++i) { hr = ProcessEntry(pFeed->rgEntries + i, pChain->wzDefaultApplicationId, pChain->rgEntries + pChain->cEntries); - ExitOnFailure(hr, "Failed to process ATOM entry."); + ApupExitOnFailure(hr, "Failed to process ATOM entry."); if (S_FALSE != hr) { @@ -103,7 +117,7 @@ extern "C" HRESULT DAPI ApupAllocChainFromAtom( if (pChain->cEntries > 0) { pChain->rgEntries = static_cast(MemReAlloc(pChain->rgEntries, sizeof(APPLICATION_UPDATE_ENTRY) * pChain->cEntries, FALSE)); - ExitOnNull(pChain->rgEntries, hr, E_OUTOFMEMORY, "Failed to reallocate memory for update entries."); + ApupExitOnNull(pChain->rgEntries, hr, E_OUTOFMEMORY, "Failed to reallocate memory for update entries."); } else { @@ -136,21 +150,21 @@ HRESULT DAPI ApupFilterChain( DWORD cEntries = NULL; pNewChain = static_cast(MemAlloc(sizeof(APPLICATION_UPDATE_CHAIN), TRUE)); - ExitOnNull(pNewChain, hr, E_OUTOFMEMORY, "Failed to allocate filtered chain."); + ApupExitOnNull(pNewChain, hr, E_OUTOFMEMORY, "Failed to allocate filtered chain."); hr = FilterEntries(pChain->rgEntries, pChain->cEntries, pVersion, &prgEntries, &cEntries); - ExitOnFailure(hr, "Failed to filter entries by version."); + ApupExitOnFailure(hr, "Failed to filter entries by version."); if (pChain->wzDefaultApplicationId) { hr = StrAllocString(&pNewChain->wzDefaultApplicationId, pChain->wzDefaultApplicationId, 0); - ExitOnFailure(hr, "Failed to copy default application id."); + ApupExitOnFailure(hr, "Failed to copy default application id."); } if (pChain->wzDefaultApplicationType) { hr = StrAllocString(&pNewChain->wzDefaultApplicationType, pChain->wzDefaultApplicationType, 0); - ExitOnFailure(hr, "Failed to copy default application type."); + ApupExitOnFailure(hr, "Failed to copy default application type."); } pNewChain->rgEntries = prgEntries; @@ -205,28 +219,28 @@ static HRESULT ProcessEntry( if (CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, 0, pElement->wzElement, -1, L"application", -1)) { hr = StrAllocString(&pApupEntry->wzApplicationId, pElement->wzValue, 0); - ExitOnFailure(hr, "Failed to allocate application identity."); + ApupExitOnFailure(hr, "Failed to allocate application identity."); for (ATOM_UNKNOWN_ATTRIBUTE* pAttribute = pElement->pAttributes; pAttribute; pAttribute = pAttribute->pNext) { if (CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, 0, pAttribute->wzAttribute, -1, L"type", -1)) { hr = StrAllocString(&pApupEntry->wzApplicationType, pAttribute->wzValue, 0); - ExitOnFailure(hr, "Failed to allocate application type."); + ApupExitOnFailure(hr, "Failed to allocate application type."); } } } else if (CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, 0, pElement->wzElement, -1, L"upgrade", -1)) { hr = StrAllocString(&pApupEntry->wzUpgradeId, pElement->wzValue, 0); - ExitOnFailure(hr, "Failed to allocate upgrade id."); + ApupExitOnFailure(hr, "Failed to allocate upgrade id."); for (ATOM_UNKNOWN_ATTRIBUTE* pAttribute = pElement->pAttributes; pAttribute; pAttribute = pAttribute->pNext) { if (CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, 0, pAttribute->wzAttribute, -1, L"version", -1)) { hr = VerParseVersion(pAttribute->wzValue, 0, FALSE, &pApupEntry->pUpgradeVersion); - ExitOnFailure(hr, "Failed to parse upgrade version string '%ls' from ATOM entry.", pAttribute->wzValue); + ApupExitOnFailure(hr, "Failed to parse upgrade version string '%ls' from ATOM entry.", pAttribute->wzValue); } else if (CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, 0, pAttribute->wzAttribute, -1, L"exclusive", -1)) { @@ -240,7 +254,7 @@ static HRESULT ProcessEntry( else if (CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, 0, pElement->wzElement, -1, L"version", -1)) { hr = VerParseVersion(pElement->wzValue, 0, FALSE, &pApupEntry->pVersion); - ExitOnFailure(hr, "Failed to parse version string '%ls' from ATOM entry.", pElement->wzValue); + ApupExitOnFailure(hr, "Failed to parse version string '%ls' from ATOM entry.", pElement->wzValue); fVersionFound = TRUE; } @@ -254,24 +268,24 @@ static HRESULT ProcessEntry( } hr = VerCompareParsedVersions(pApupEntry->pUpgradeVersion, pApupEntry->pVersion, &nCompareResult); - ExitOnFailure(hr, "Failed to compare version to upgrade version."); + ApupExitOnFailure(hr, "Failed to compare version to upgrade version."); if (nCompareResult >= 0) { hr = HRESULT_FROM_WIN32(ERROR_INVALID_DATA); - ExitOnRootFailure(hr, "Upgrade version is greater than or equal to application version."); + ApupExitOnRootFailure(hr, "Upgrade version is greater than or equal to application version."); } if (pAtomEntry->wzTitle) { hr = StrAllocString(&pApupEntry->wzTitle, pAtomEntry->wzTitle, 0); - ExitOnFailure(hr, "Failed to allocate application title."); + ApupExitOnFailure(hr, "Failed to allocate application title."); } if (pAtomEntry->wzSummary) { hr = StrAllocString(&pApupEntry->wzSummary, pAtomEntry->wzSummary, 0); - ExitOnFailure(hr, "Failed to allocate application summary."); + ApupExitOnFailure(hr, "Failed to allocate application summary."); } if (pAtomEntry->pContent) @@ -279,18 +293,18 @@ static HRESULT ProcessEntry( if (pAtomEntry->pContent->wzType) { hr = StrAllocString(&pApupEntry->wzContentType, pAtomEntry->pContent->wzType, 0); - ExitOnFailure(hr, "Failed to allocate content type."); + ApupExitOnFailure(hr, "Failed to allocate content type."); } if (pAtomEntry->pContent->wzValue) { hr = StrAllocString(&pApupEntry->wzContent, pAtomEntry->pContent->wzValue, 0); - ExitOnFailure(hr, "Failed to allocate content."); + ApupExitOnFailure(hr, "Failed to allocate content."); } } // Now process the enclosures. Assume every link in the ATOM entry is an enclosure. pApupEntry->rgEnclosures = static_cast(MemAlloc(sizeof(APPLICATION_UPDATE_ENCLOSURE) * pAtomEntry->cLinks, TRUE)); - ExitOnNull(pApupEntry->rgEnclosures, hr, E_OUTOFMEMORY, "Failed to allocate enclosures for application update entry."); + ApupExitOnNull(pApupEntry->rgEnclosures, hr, E_OUTOFMEMORY, "Failed to allocate enclosures for application update entry."); for (DWORD i = 0; i < pAtomEntry->cLinks; ++i) { @@ -298,7 +312,7 @@ static HRESULT ProcessEntry( if (CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, 0, pLink->wzRel, -1, L"enclosure", -1)) { hr = ParseEnclosure(pLink, pApupEntry->rgEnclosures + pApupEntry->cEnclosures); - ExitOnFailure(hr, "Failed to parse enclosure."); + ApupExitOnFailure(hr, "Failed to parse enclosure."); pApupEntry->dw64TotalSize += pApupEntry->rgEnclosures[pApupEntry->cEnclosures].dw64Size; // total up the size of the enclosures @@ -369,25 +383,25 @@ static HRESULT ParseEnclosure( dwDigestStringLength = 2 * dwDigestLength; hr = ::StringCchLengthW(pElement->wzValue, STRSAFE_MAX_CCH, &cchDigestString); - ExitOnFailure(hr, "Failed to get string length of digest value."); + ApupExitOnFailure(hr, "Failed to get string length of digest value."); if (dwDigestStringLength != cchDigestString) { hr = HRESULT_FROM_WIN32(ERROR_INVALID_DATA); - ExitOnRootFailure(hr, "Invalid digest length (%zu) for digest algorithm (%u).", cchDigestString, dwDigestStringLength); + ApupExitOnRootFailure(hr, "Invalid digest length (%zu) for digest algorithm (%u).", cchDigestString, dwDigestStringLength); } pEnclosure->cbDigest = sizeof(BYTE) * dwDigestLength; pEnclosure->rgbDigest = static_cast(MemAlloc(pEnclosure->cbDigest, TRUE)); - ExitOnNull(pEnclosure->rgbDigest, hr, E_OUTOFMEMORY, "Failed to allocate memory for digest."); + ApupExitOnNull(pEnclosure->rgbDigest, hr, E_OUTOFMEMORY, "Failed to allocate memory for digest."); hr = StrHexDecode(pElement->wzValue, pEnclosure->rgbDigest, pEnclosure->cbDigest); - ExitOnFailure(hr, "Failed to decode digest value."); + ApupExitOnFailure(hr, "Failed to decode digest value."); } else { hr = HRESULT_FROM_WIN32(ERROR_INVALID_DATA); - ExitOnRootFailure(hr, "Unknown algorithm type for digest."); + ApupExitOnRootFailure(hr, "Unknown algorithm type for digest."); } break; @@ -395,7 +409,7 @@ static HRESULT ParseEnclosure( else if (CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, 0, L"name", -1, pElement->wzElement, -1)) { hr = StrAllocString(&pEnclosure->wzLocalName, pElement->wzValue, 0); - ExitOnFailure(hr, "Failed to copy local name."); + ApupExitOnFailure(hr, "Failed to copy local name."); } } } @@ -403,7 +417,7 @@ static HRESULT ParseEnclosure( pEnclosure->dw64Size = pLink->dw64Length; hr = StrAllocString(&pEnclosure->wzUrl, pLink->wzUrl, 0); - ExitOnFailure(hr, "Failed to allocate enclosure URL."); + ApupExitOnFailure(hr, "Failed to allocate enclosure URL."); pEnclosure->fInstaller = FALSE; pEnclosure->wzLocalName = NULL; @@ -459,7 +473,7 @@ static HRESULT FilterEntries( const APPLICATION_UPDATE_ENTRY* pEntry = rgEntries + i; hr = VerCompareParsedVersions(pCurrentVersion, pEntry->pVersion, &nCompareResult); - ExitOnFailure(hr, "Failed to compare versions."); + ApupExitOnFailure(hr, "Failed to compare versions."); if (nCompareResult >= 0) { @@ -467,7 +481,7 @@ static HRESULT FilterEntries( } hr = VerCompareParsedVersions(pCurrentVersion, pEntry->pUpgradeVersion, &nCompareResult); - ExitOnFailure(hr, "Failed to compare upgrade versions."); + ApupExitOnFailure(hr, "Failed to compare upgrade versions."); if (nCompareResult > 0 || (!pEntry->fUpgradeExclusive && nCompareResult == 0)) { @@ -481,17 +495,17 @@ static HRESULT FilterEntries( DWORD cNewFilteredEntries = *pcFilteredEntries + 1; hr = ::SizeTMult(sizeof(APPLICATION_UPDATE_ENTRY), cNewFilteredEntries, &cbAllocSize); - ExitOnFailure(hr, "Overflow while calculating alloc size for more entries - number of entries: %u", cNewFilteredEntries); + ApupExitOnFailure(hr, "Overflow while calculating alloc size for more entries - number of entries: %u", cNewFilteredEntries); if (*prgFilteredEntries) { pv = MemReAlloc(*prgFilteredEntries, cbAllocSize, FALSE); - ExitOnNull(pv, hr, E_OUTOFMEMORY, "Failed to reallocate memory for more entries."); + ApupExitOnNull(pv, hr, E_OUTOFMEMORY, "Failed to reallocate memory for more entries."); } else { pv = MemAlloc(cbAllocSize, TRUE); - ExitOnNull(pv, hr, E_OUTOFMEMORY, "Failed to allocate memory for entries."); + ApupExitOnNull(pv, hr, E_OUTOFMEMORY, "Failed to allocate memory for entries."); } *pcFilteredEntries = cNewFilteredEntries; @@ -499,10 +513,10 @@ static HRESULT FilterEntries( pv = NULL; hr = CopyEntry(pRequired, *prgFilteredEntries + *pcFilteredEntries - 1); - ExitOnFailure(hr, "Failed to deep copy entry."); + ApupExitOnFailure(hr, "Failed to deep copy entry."); hr = VerCompareParsedVersions(pRequired->pVersion, rgEntries[0].pVersion, &nCompareResult); - ExitOnFailure(hr, "Failed to compare required version."); + ApupExitOnFailure(hr, "Failed to compare required version."); if (nCompareResult < 0) { @@ -530,67 +544,67 @@ static HRESULT CopyEntry( if (pSrc->wzApplicationId) { hr = StrAllocString(&pDest->wzApplicationId, pSrc->wzApplicationId, 0); - ExitOnFailure(hr, "Failed to copy application id."); + ApupExitOnFailure(hr, "Failed to copy application id."); } if (pSrc->wzApplicationType) { hr = StrAllocString(&pDest->wzApplicationType, pSrc->wzApplicationType, 0); - ExitOnFailure(hr, "Failed to copy application type."); + ApupExitOnFailure(hr, "Failed to copy application type."); } if (pSrc->wzUpgradeId) { hr = StrAllocString(&pDest->wzUpgradeId, pSrc->wzUpgradeId, 0); - ExitOnFailure(hr, "Failed to copy upgrade id."); + ApupExitOnFailure(hr, "Failed to copy upgrade id."); } if (pSrc->wzTitle) { hr = StrAllocString(&pDest->wzTitle, pSrc->wzTitle, 0); - ExitOnFailure(hr, "Failed to copy title."); + ApupExitOnFailure(hr, "Failed to copy title."); } if (pSrc->wzSummary) { hr = StrAllocString(&pDest->wzSummary, pSrc->wzSummary, 0); - ExitOnFailure(hr, "Failed to copy summary."); + ApupExitOnFailure(hr, "Failed to copy summary."); } if (pSrc->wzContentType) { hr = StrAllocString(&pDest->wzContentType, pSrc->wzContentType, 0); - ExitOnFailure(hr, "Failed to copy content type."); + ApupExitOnFailure(hr, "Failed to copy content type."); } if (pSrc->wzContent) { hr = StrAllocString(&pDest->wzContent, pSrc->wzContent, 0); - ExitOnFailure(hr, "Failed to copy content."); + ApupExitOnFailure(hr, "Failed to copy content."); } pDest->dw64TotalSize = pSrc->dw64TotalSize; hr = VerCopyVersion(pSrc->pUpgradeVersion, &pDest->pUpgradeVersion); - ExitOnFailure(hr, "Failed to copy upgrade version."); + ApupExitOnFailure(hr, "Failed to copy upgrade version."); hr = VerCopyVersion(pSrc->pVersion, &pDest->pVersion); - ExitOnFailure(hr, "Failed to copy version."); + ApupExitOnFailure(hr, "Failed to copy version."); pDest->fUpgradeExclusive = pSrc->fUpgradeExclusive; hr = ::SizeTMult(sizeof(APPLICATION_UPDATE_ENCLOSURE), pSrc->cEnclosures, &cbAllocSize); - ExitOnRootFailure(hr, "Overflow while calculating memory allocation size"); + ApupExitOnRootFailure(hr, "Overflow while calculating memory allocation size"); pDest->rgEnclosures = static_cast(MemAlloc(cbAllocSize, TRUE)); - ExitOnNull(pDest->rgEnclosures, hr, E_OUTOFMEMORY, "Failed to allocate copy of enclosures."); + ApupExitOnNull(pDest->rgEnclosures, hr, E_OUTOFMEMORY, "Failed to allocate copy of enclosures."); pDest->cEnclosures = pSrc->cEnclosures; for (DWORD i = 0; i < pDest->cEnclosures; ++i) { hr = CopyEnclosure(pSrc->rgEnclosures + i, pDest->rgEnclosures + i); - ExitOnFailure(hr, "Failed to copy enclosure."); + ApupExitOnFailure(hr, "Failed to copy enclosure."); } LExit: @@ -615,17 +629,17 @@ static HRESULT CopyEnclosure( if (pSrc->wzUrl) { hr = StrAllocString(&pDest->wzUrl, pSrc->wzUrl, 0); - ExitOnFailure(hr, "Failed copy url."); + ApupExitOnFailure(hr, "Failed copy url."); } if (pSrc->wzLocalName) { hr = StrAllocString(&pDest->wzLocalName, pSrc->wzLocalName, 0); - ExitOnFailure(hr, "Failed copy url."); + ApupExitOnFailure(hr, "Failed copy url."); } pDest->rgbDigest = static_cast(MemAlloc(sizeof(BYTE) * pSrc->cbDigest, FALSE)); - ExitOnNull(pDest->rgbDigest, hr, E_OUTOFMEMORY, "Failed to allocate memory for copy of digest."); + ApupExitOnNull(pDest->rgbDigest, hr, E_OUTOFMEMORY, "Failed to allocate memory for copy of digest."); pDest->cbDigest = pSrc->cbDigest; diff --git a/src/dutil/atomutil.cpp b/src/dutil/atomutil.cpp index 4a12fb80..c7c7975a 100644 --- a/src/dutil/atomutil.cpp +++ b/src/dutil/atomutil.cpp @@ -2,6 +2,19 @@ #include "precomp.h" +// Exit macros +#define AtomExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_ATOMUTIL, x, s, __VA_ARGS__) +#define AtomExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_ATOMUTIL, x, s, __VA_ARGS__) +#define AtomExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_ATOMUTIL, x, s, __VA_ARGS__) +#define AtomExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_ATOMUTIL, x, s, __VA_ARGS__) +#define AtomExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_ATOMUTIL, x, s, __VA_ARGS__) +#define AtomExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_ATOMUTIL, x, s, __VA_ARGS__) +#define AtomExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_ATOMUTIL, p, x, e, s, __VA_ARGS__) +#define AtomExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_ATOMUTIL, p, x, s, __VA_ARGS__) +#define AtomExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_ATOMUTIL, p, x, e, s, __VA_ARGS__) +#define AtomExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_ATOMUTIL, p, x, s, __VA_ARGS__) +#define AtomExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_ATOMUTIL, e, x, s, __VA_ARGS__) +#define AtomExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_ATOMUTIL, g, x, s, __VA_ARGS__) static HRESULT ParseAtomDocument( __in IXMLDOMDocument *pixd, @@ -98,7 +111,7 @@ extern "C" void DAPI AtomUninitialize() *********************************************************************/ extern "C" HRESULT DAPI AtomParseFromString( - __in LPCWSTR wzAtomString, + __in_z LPCWSTR wzAtomString, __out ATOM_FEED **ppFeed ) { @@ -110,10 +123,10 @@ extern "C" HRESULT DAPI AtomParseFromString( IXMLDOMDocument *pixdAtom = NULL; hr = XmlLoadDocument(wzAtomString, &pixdAtom); - ExitOnFailure(hr, "Failed to load ATOM string as XML document."); + AtomExitOnFailure(hr, "Failed to load ATOM string as XML document."); hr = ParseAtomDocument(pixdAtom, &pNewFeed); - ExitOnFailure(hr, "Failed to parse ATOM document."); + AtomExitOnFailure(hr, "Failed to parse ATOM document."); *ppFeed = pNewFeed; pNewFeed = NULL; @@ -131,7 +144,7 @@ LExit: *********************************************************************/ extern "C" HRESULT DAPI AtomParseFromFile( - __in LPCWSTR wzAtomFile, + __in_z LPCWSTR wzAtomFile, __out ATOM_FEED **ppFeed ) { @@ -143,10 +156,10 @@ extern "C" HRESULT DAPI AtomParseFromFile( IXMLDOMDocument *pixdAtom = NULL; hr = XmlLoadDocumentFromFile(wzAtomFile, &pixdAtom); - ExitOnFailure(hr, "Failed to load ATOM string as XML document."); + AtomExitOnFailure(hr, "Failed to load ATOM string as XML document."); hr = ParseAtomDocument(pixdAtom, &pNewFeed); - ExitOnFailure(hr, "Failed to parse ATOM document."); + AtomExitOnFailure(hr, "Failed to parse ATOM document."); *ppFeed = pNewFeed; pNewFeed = NULL; @@ -175,7 +188,7 @@ extern "C" HRESULT DAPI AtomParseFromDocument( ATOM_FEED *pNewFeed = NULL; hr = ParseAtomDocument(pixdDocument, &pNewFeed); - ExitOnFailure(hr, "Failed to parse ATOM document."); + AtomExitOnFailure(hr, "Failed to parse ATOM document."); *ppFeed = pNewFeed; pNewFeed = NULL; @@ -192,7 +205,7 @@ LExit: *********************************************************************/ extern "C" void DAPI AtomFreeFeed( - __in_xcount(pFeed->cItems) ATOM_FEED *pFeed + __in_xcount(pFeed->cItems) ATOM_FEED* pFeed ) { if (pFeed) @@ -257,10 +270,10 @@ static HRESULT ParseAtomDocument( // Get the document element and start processing feeds. // hr = pixd->get_documentElement(&pFeedElement); - ExitOnFailure(hr, "failed get_documentElement in ParseAtomDocument"); + AtomExitOnFailure(hr, "failed get_documentElement in ParseAtomDocument"); hr = ParseAtomFeed(pFeedElement, &pNewFeed); - ExitOnFailure(hr, "Failed to parse ATOM feed."); + AtomExitOnFailure(hr, "Failed to parse ATOM feed."); if (S_FALSE == hr) { @@ -305,96 +318,96 @@ static HRESULT ParseAtomFeed( // First, allocate the new feed and all the possible sub elements. pNewFeed = (ATOM_FEED*)MemAlloc(sizeof(ATOM_FEED), TRUE); - ExitOnNull(pNewFeed, hr, E_OUTOFMEMORY, "Failed to allocate ATOM feed structure."); + AtomExitOnNull(pNewFeed, hr, E_OUTOFMEMORY, "Failed to allocate ATOM feed structure."); pNewFeed->pixn = pixnFeed; pNewFeed->pixn->AddRef(); hr = AllocateAtomType(pixnFeed, L"author", &pNewFeed->rgAuthors, &pNewFeed->cAuthors); - ExitOnFailure(hr, "Failed to allocate ATOM feed authors."); + AtomExitOnFailure(hr, "Failed to allocate ATOM feed authors."); hr = AllocateAtomType(pixnFeed, L"category", &pNewFeed->rgCategories, &pNewFeed->cCategories); - ExitOnFailure(hr, "Failed to allocate ATOM feed categories."); + AtomExitOnFailure(hr, "Failed to allocate ATOM feed categories."); hr = AllocateAtomType(pixnFeed, L"entry", &pNewFeed->rgEntries, &pNewFeed->cEntries); - ExitOnFailure(hr, "Failed to allocate ATOM feed entries."); + AtomExitOnFailure(hr, "Failed to allocate ATOM feed entries."); hr = AllocateAtomType(pixnFeed, L"link", &pNewFeed->rgLinks, &pNewFeed->cLinks); - ExitOnFailure(hr, "Failed to allocate ATOM feed links."); + AtomExitOnFailure(hr, "Failed to allocate ATOM feed links."); // Second, process the elements under a feed. hr = pixnFeed->get_childNodes(&pNodeList); - ExitOnFailure(hr, "Failed to get child nodes of ATOM feed element."); + AtomExitOnFailure(hr, "Failed to get child nodes of ATOM feed element."); while (S_OK == (hr = XmlNextElement(pNodeList, &pNode, &bstrNodeName))) { if (CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, 0, bstrNodeName, -1, L"generator", -1)) { hr = AssignString(&pNewFeed->wzGenerator, pNode); - ExitOnFailure(hr, "Failed to allocate ATOM feed generator."); + AtomExitOnFailure(hr, "Failed to allocate ATOM feed generator."); } else if (CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, 0, bstrNodeName, -1, L"icon", -1)) { hr = AssignString(&pNewFeed->wzIcon, pNode); - ExitOnFailure(hr, "Failed to allocate ATOM feed icon."); + AtomExitOnFailure(hr, "Failed to allocate ATOM feed icon."); } else if (CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, 0, bstrNodeName, -1, L"id", -1)) { hr = AssignString(&pNewFeed->wzId, pNode); - ExitOnFailure(hr, "Failed to allocate ATOM feed id."); + AtomExitOnFailure(hr, "Failed to allocate ATOM feed id."); } else if (CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, 0, bstrNodeName, -1, L"logo", -1)) { hr = AssignString(&pNewFeed->wzLogo, pNode); - ExitOnFailure(hr, "Failed to allocate ATOM feed logo."); + AtomExitOnFailure(hr, "Failed to allocate ATOM feed logo."); } else if (CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, 0, bstrNodeName, -1, L"subtitle", -1)) { hr = AssignString(&pNewFeed->wzSubtitle, pNode); - ExitOnFailure(hr, "Failed to allocate ATOM feed subtitle."); + AtomExitOnFailure(hr, "Failed to allocate ATOM feed subtitle."); } else if (CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, 0, bstrNodeName, -1, L"title", -1)) { hr = AssignString(&pNewFeed->wzTitle, pNode); - ExitOnFailure(hr, "Failed to allocate ATOM feed title."); + AtomExitOnFailure(hr, "Failed to allocate ATOM feed title."); } else if (CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, 0, bstrNodeName, -1, L"updated", -1)) { hr = AssignDateTime(&pNewFeed->ftUpdated, pNode); - ExitOnFailure(hr, "Failed to allocate ATOM feed updated."); + AtomExitOnFailure(hr, "Failed to allocate ATOM feed updated."); } else if (CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, 0, bstrNodeName, -1, L"author", -1)) { hr = ParseAtomAuthor(pNode, &pNewFeed->rgAuthors[cAuthors]); - ExitOnFailure(hr, "Failed to parse ATOM author."); + AtomExitOnFailure(hr, "Failed to parse ATOM author."); ++cAuthors; } else if (CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, 0, bstrNodeName, -1, L"category", -1)) { hr = ParseAtomCategory(pNode, &pNewFeed->rgCategories[cCategories]); - ExitOnFailure(hr, "Failed to parse ATOM category."); + AtomExitOnFailure(hr, "Failed to parse ATOM category."); ++cCategories; } else if (CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, 0, bstrNodeName, -1, L"entry", -1)) { hr = ParseAtomEntry(pNode, &pNewFeed->rgEntries[cEntries]); - ExitOnFailure(hr, "Failed to parse ATOM entry."); + AtomExitOnFailure(hr, "Failed to parse ATOM entry."); ++cEntries; } else if (CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, 0, bstrNodeName, -1, L"link", -1)) { hr = ParseAtomLink(pNode, &pNewFeed->rgLinks[cLinks]); - ExitOnFailure(hr, "Failed to parse ATOM link."); + AtomExitOnFailure(hr, "Failed to parse ATOM link."); ++cLinks; } else { hr = ParseAtomUnknownElement(pNode, &pNewFeed->pUnknownElements); - ExitOnFailure(hr, "Failed to parse unknown ATOM feed element: %ls", bstrNodeName); + AtomExitOnFailure(hr, "Failed to parse unknown ATOM feed element: %ls", bstrNodeName); } ReleaseNullBSTR(bstrNodeName); @@ -404,17 +417,17 @@ static HRESULT ParseAtomFeed( if (!pNewFeed->wzId || !*pNewFeed->wzId) { hr = HRESULT_FROM_WIN32(ERROR_INVALID_DATA); - ExitOnRootFailure(hr, "Failed to find required feed/id element."); + AtomExitOnRootFailure(hr, "Failed to find required feed/id element."); } else if (!pNewFeed->wzTitle || !*pNewFeed->wzTitle) { hr = HRESULT_FROM_WIN32(ERROR_INVALID_DATA); - ExitOnRootFailure(hr, "Failed to find required feed/title element."); + AtomExitOnRootFailure(hr, "Failed to find required feed/title element."); } else if (0 == pNewFeed->ftUpdated.dwHighDateTime && 0 == pNewFeed->ftUpdated.dwLowDateTime) { hr = HRESULT_FROM_WIN32(ERROR_INVALID_DATA); - ExitOnRootFailure(hr, "Failed to find required feed/updated element."); + AtomExitOnRootFailure(hr, "Failed to find required feed/updated element."); } *ppFeed = pNewFeed; @@ -450,12 +463,12 @@ template static HRESULT AllocateAtomType( T* prgT = NULL; hr = XmlSelectNodes(pixnParent, wzT, &pNodeList); - ExitOnFailure(hr, "Failed to select all ATOM %ls.", wzT); + AtomExitOnFailure(hr, "Failed to select all ATOM %ls.", wzT); if (S_OK == hr) { hr = pNodeList->get_length(&cT); - ExitOnFailure(hr, "Failed to count the number of ATOM %ls.", wzT); + AtomExitOnFailure(hr, "Failed to count the number of ATOM %ls.", wzT); if (cT == 0) { @@ -463,7 +476,7 @@ template static HRESULT AllocateAtomType( } prgT = static_cast(MemAlloc(sizeof(T) * cT, TRUE)); - ExitOnNull(prgT, hr, E_OUTOFMEMORY, "Failed to allocate ATOM."); + AtomExitOnNull(prgT, hr, E_OUTOFMEMORY, "Failed to allocate ATOM."); *pcT = cT; *pprgT = prgT; @@ -499,30 +512,30 @@ static HRESULT ParseAtomAuthor( BSTR bstrNodeName = NULL; hr = pixnAuthor->get_childNodes(&pNodeList); - ExitOnFailure(hr, "Failed to get child nodes of ATOM author element."); + AtomExitOnFailure(hr, "Failed to get child nodes of ATOM author element."); while (S_OK == (hr = XmlNextElement(pNodeList, &pNode, &bstrNodeName))) { if (CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, 0, bstrNodeName, -1, L"name", -1)) { hr = AssignString(&pAuthor->wzName, pNode); - ExitOnFailure(hr, "Failed to allocate ATOM author name."); + AtomExitOnFailure(hr, "Failed to allocate ATOM author name."); } else if (CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, 0, bstrNodeName, -1, L"email", -1)) { hr = AssignString(&pAuthor->wzEmail, pNode); - ExitOnFailure(hr, "Failed to allocate ATOM author email."); + AtomExitOnFailure(hr, "Failed to allocate ATOM author email."); } else if (CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, 0, bstrNodeName, -1, L"uri", -1)) { hr = AssignString(&pAuthor->wzUrl, pNode); - ExitOnFailure(hr, "Failed to allocate ATOM author uri."); + AtomExitOnFailure(hr, "Failed to allocate ATOM author uri."); } ReleaseNullBSTR(bstrNodeName); ReleaseNullObject(pNode); } - ExitOnFailure(hr, "Failed to process all ATOM author elements."); + AtomExitOnFailure(hr, "Failed to process all ATOM author elements."); hr = S_OK; @@ -553,44 +566,44 @@ static HRESULT ParseAtomCategory( // Process attributes first. hr = pixnCategory->get_attributes(&pixnnmAttributes); - ExitOnFailure(hr, "Failed get attributes on ATOM unknown element."); + AtomExitOnFailure(hr, "Failed get attributes on ATOM unknown element."); while (S_OK == (hr = XmlNextAttribute(pixnnmAttributes, &pNode, &bstrNodeName))) { if (CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, 0, bstrNodeName, -1, L"label", -1)) { hr = AssignString(&pCategory->wzLabel, pNode); - ExitOnFailure(hr, "Failed to allocate ATOM category label."); + AtomExitOnFailure(hr, "Failed to allocate ATOM category label."); } else if (CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, 0, bstrNodeName, -1, L"scheme", -1)) { hr = AssignString(&pCategory->wzScheme, pNode); - ExitOnFailure(hr, "Failed to allocate ATOM category scheme."); + AtomExitOnFailure(hr, "Failed to allocate ATOM category scheme."); } else if (CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, 0, bstrNodeName, -1, L"term", -1)) { hr = AssignString(&pCategory->wzTerm, pNode); - ExitOnFailure(hr, "Failed to allocate ATOM category term."); + AtomExitOnFailure(hr, "Failed to allocate ATOM category term."); } ReleaseNullBSTR(bstrNodeName); ReleaseNullObject(pNode); } - ExitOnFailure(hr, "Failed to process all ATOM category attributes."); + AtomExitOnFailure(hr, "Failed to process all ATOM category attributes."); // Process elements second. hr = pixnCategory->get_childNodes(&pNodeList); - ExitOnFailure(hr, "Failed to get child nodes of ATOM category element."); + AtomExitOnFailure(hr, "Failed to get child nodes of ATOM category element."); while (S_OK == (hr = XmlNextElement(pNodeList, &pNode, &bstrNodeName))) { hr = ParseAtomUnknownElement(pNode, &pCategory->pUnknownElements); - ExitOnFailure(hr, "Failed to parse unknown ATOM category element: %ls", bstrNodeName); + AtomExitOnFailure(hr, "Failed to parse unknown ATOM category element: %ls", bstrNodeName); ReleaseNullBSTR(bstrNodeName); ReleaseNullObject(pNode); } - ExitOnFailure(hr, "Failed to process all ATOM category elements."); + AtomExitOnFailure(hr, "Failed to process all ATOM category elements."); hr = S_OK; @@ -622,42 +635,42 @@ static HRESULT ParseAtomContent( // Process attributes first. hr = pixnContent->get_attributes(&pixnnmAttributes); - ExitOnFailure(hr, "Failed get attributes on ATOM unknown element."); + AtomExitOnFailure(hr, "Failed get attributes on ATOM unknown element."); while (S_OK == (hr = XmlNextAttribute(pixnnmAttributes, &pNode, &bstrNodeName))) { if (CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, 0, bstrNodeName, -1, L"type", -1)) { hr = AssignString(&pContent->wzType, pNode); - ExitOnFailure(hr, "Failed to allocate ATOM content type."); + AtomExitOnFailure(hr, "Failed to allocate ATOM content type."); } else if (CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, 0, bstrNodeName, -1, L"url", -1)) { hr = AssignString(&pContent->wzUrl, pNode); - ExitOnFailure(hr, "Failed to allocate ATOM content scheme."); + AtomExitOnFailure(hr, "Failed to allocate ATOM content scheme."); } ReleaseNullBSTR(bstrNodeName); ReleaseNullObject(pNode); } - ExitOnFailure(hr, "Failed to process all ATOM content attributes."); + AtomExitOnFailure(hr, "Failed to process all ATOM content attributes."); // Process elements second. hr = pixnContent->get_childNodes(&pNodeList); - ExitOnFailure(hr, "Failed to get child nodes of ATOM content element."); + AtomExitOnFailure(hr, "Failed to get child nodes of ATOM content element."); while (S_OK == (hr = XmlNextElement(pNodeList, &pNode, &bstrNodeName))) { hr = ParseAtomUnknownElement(pNode, &pContent->pUnknownElements); - ExitOnFailure(hr, "Failed to parse unknown ATOM content element: %ls", bstrNodeName); + AtomExitOnFailure(hr, "Failed to parse unknown ATOM content element: %ls", bstrNodeName); ReleaseNullBSTR(bstrNodeName); ReleaseNullObject(pNode); } - ExitOnFailure(hr, "Failed to process all ATOM content elements."); + AtomExitOnFailure(hr, "Failed to process all ATOM content elements."); hr = AssignString(&pContent->wzValue, pixnContent); - ExitOnFailure(hr, "Failed to allocate ATOM content value."); + AtomExitOnFailure(hr, "Failed to allocate ATOM content value."); LExit: ReleaseBSTR(bstrNodeName); @@ -694,56 +707,56 @@ static HRESULT ParseAtomEntry( // First, allocate all the possible sub elements. hr = AllocateAtomType(pixnEntry, L"author", &pEntry->rgAuthors, &pEntry->cAuthors); - ExitOnFailure(hr, "Failed to allocate ATOM entry authors."); + AtomExitOnFailure(hr, "Failed to allocate ATOM entry authors."); hr = AllocateAtomType(pixnEntry, L"category", &pEntry->rgCategories, &pEntry->cCategories); - ExitOnFailure(hr, "Failed to allocate ATOM entry categories."); + AtomExitOnFailure(hr, "Failed to allocate ATOM entry categories."); hr = AllocateAtomType(pixnEntry, L"link", &pEntry->rgLinks, &pEntry->cLinks); - ExitOnFailure(hr, "Failed to allocate ATOM entry links."); + AtomExitOnFailure(hr, "Failed to allocate ATOM entry links."); // Second, process elements. hr = pixnEntry->get_childNodes(&pNodeList); - ExitOnFailure(hr, "Failed to get child nodes of ATOM entry element."); + AtomExitOnFailure(hr, "Failed to get child nodes of ATOM entry element."); while (S_OK == (hr = XmlNextElement(pNodeList, &pNode, &bstrNodeName))) { if (CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, 0, bstrNodeName, -1, L"id", -1)) { hr = AssignString(&pEntry->wzId, pNode); - ExitOnFailure(hr, "Failed to allocate ATOM entry id."); + AtomExitOnFailure(hr, "Failed to allocate ATOM entry id."); } else if (CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, 0, bstrNodeName, -1, L"summary", -1)) { hr = AssignString(&pEntry->wzSummary, pNode); - ExitOnFailure(hr, "Failed to allocate ATOM entry summary."); + AtomExitOnFailure(hr, "Failed to allocate ATOM entry summary."); } else if (CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, 0, bstrNodeName, -1, L"title", -1)) { hr = AssignString(&pEntry->wzTitle, pNode); - ExitOnFailure(hr, "Failed to allocate ATOM entry title."); + AtomExitOnFailure(hr, "Failed to allocate ATOM entry title."); } else if (CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, 0, bstrNodeName, -1, L"published", -1)) { hr = AssignDateTime(&pEntry->ftPublished, pNode); - ExitOnFailure(hr, "Failed to allocate ATOM entry published."); + AtomExitOnFailure(hr, "Failed to allocate ATOM entry published."); } else if (CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, 0, bstrNodeName, -1, L"updated", -1)) { hr = AssignDateTime(&pEntry->ftUpdated, pNode); - ExitOnFailure(hr, "Failed to allocate ATOM entry updated."); + AtomExitOnFailure(hr, "Failed to allocate ATOM entry updated."); } else if (CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, 0, bstrNodeName, -1, L"author", -1)) { hr = ParseAtomAuthor(pNode, &pEntry->rgAuthors[cAuthors]); - ExitOnFailure(hr, "Failed to parse ATOM entry author."); + AtomExitOnFailure(hr, "Failed to parse ATOM entry author."); ++cAuthors; } else if (CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, 0, bstrNodeName, -1, L"category", -1)) { hr = ParseAtomCategory(pNode, &pEntry->rgCategories[cCategories]); - ExitOnFailure(hr, "Failed to parse ATOM entry category."); + AtomExitOnFailure(hr, "Failed to parse ATOM entry category."); ++cCategories; } @@ -752,47 +765,47 @@ static HRESULT ParseAtomEntry( if (NULL != pEntry->pContent) { hr = E_UNEXPECTED; - ExitOnFailure(hr, "Cannot have two content elements in ATOM entry."); + AtomExitOnFailure(hr, "Cannot have two content elements in ATOM entry."); } pEntry->pContent = static_cast(MemAlloc(sizeof(ATOM_CONTENT), TRUE)); - ExitOnNull(pEntry->pContent, hr, E_OUTOFMEMORY, "Failed to allocate ATOM entry content."); + AtomExitOnNull(pEntry->pContent, hr, E_OUTOFMEMORY, "Failed to allocate ATOM entry content."); hr = ParseAtomContent(pNode, pEntry->pContent); - ExitOnFailure(hr, "Failed to parse ATOM entry content."); + AtomExitOnFailure(hr, "Failed to parse ATOM entry content."); } else if (CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, 0, bstrNodeName, -1, L"link", -1)) { hr = ParseAtomLink(pNode, &pEntry->rgLinks[cLinks]); - ExitOnFailure(hr, "Failed to parse ATOM entry link."); + AtomExitOnFailure(hr, "Failed to parse ATOM entry link."); ++cLinks; } else { hr = ParseAtomUnknownElement(pNode, &pEntry->pUnknownElements); - ExitOnFailure(hr, "Failed to parse unknown ATOM entry element: %ls", bstrNodeName); + AtomExitOnFailure(hr, "Failed to parse unknown ATOM entry element: %ls", bstrNodeName); } ReleaseNullBSTR(bstrNodeName); ReleaseNullObject(pNode); } - ExitOnFailure(hr, "Failed to process all ATOM entry elements."); + AtomExitOnFailure(hr, "Failed to process all ATOM entry elements."); if (!pEntry->wzId || !*pEntry->wzId) { hr = HRESULT_FROM_WIN32(ERROR_INVALID_DATA); - ExitOnRootFailure(hr, "Failed to find required feed/entry/id element."); + AtomExitOnRootFailure(hr, "Failed to find required feed/entry/id element."); } else if (!pEntry->wzTitle || !*pEntry->wzTitle) { hr = HRESULT_FROM_WIN32(ERROR_INVALID_DATA); - ExitOnRootFailure(hr, "Failed to find required feed/entry/title element."); + AtomExitOnRootFailure(hr, "Failed to find required feed/entry/title element."); } else if (0 == pEntry->ftUpdated.dwHighDateTime && 0 == pEntry->ftUpdated.dwLowDateTime) { hr = HRESULT_FROM_WIN32(ERROR_INVALID_DATA); - ExitOnRootFailure(hr, "Failed to find required feed/entry/updated element."); + AtomExitOnRootFailure(hr, "Failed to find required feed/entry/updated element."); } hr = S_OK; @@ -825,19 +838,19 @@ static HRESULT ParseAtomLink( // Process attributes first. hr = pixnLink->get_attributes(&pixnnmAttributes); - ExitOnFailure(hr, "Failed get attributes for ATOM link."); + AtomExitOnFailure(hr, "Failed get attributes for ATOM link."); while (S_OK == (hr = XmlNextAttribute(pixnnmAttributes, &pNode, &bstrNodeName))) { if (CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, 0, bstrNodeName, -1, L"rel", -1)) { hr = AssignString(&pLink->wzRel, pNode); - ExitOnFailure(hr, "Failed to allocate ATOM link rel."); + AtomExitOnFailure(hr, "Failed to allocate ATOM link rel."); } else if (CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, 0, bstrNodeName, -1, L"href", -1)) { hr = AssignString(&pLink->wzUrl, pNode); - ExitOnFailure(hr, "Failed to allocate ATOM link href."); + AtomExitOnFailure(hr, "Failed to allocate ATOM link href."); } else if (CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, 0, bstrNodeName, -1, L"length", -1)) { @@ -846,45 +859,45 @@ static HRESULT ParseAtomLink( { hr = HRESULT_FROM_WIN32(ERROR_INVALID_DATA); } - ExitOnFailure(hr, "Failed to parse ATOM link length."); + AtomExitOnFailure(hr, "Failed to parse ATOM link length."); } else if (CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, 0, bstrNodeName, -1, L"title", -1)) { hr = AssignString(&pLink->wzTitle, pNode); - ExitOnFailure(hr, "Failed to allocate ATOM link title."); + AtomExitOnFailure(hr, "Failed to allocate ATOM link title."); } else if (CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, 0, bstrNodeName, -1, L"type", -1)) { hr = AssignString(&pLink->wzType, pNode); - ExitOnFailure(hr, "Failed to allocate ATOM link type."); + AtomExitOnFailure(hr, "Failed to allocate ATOM link type."); } else { hr = ParseAtomUnknownAttribute(pNode, &pLink->pUnknownAttributes); - ExitOnFailure(hr, "Failed to parse unknown ATOM link attribute: %ls", bstrNodeName); + AtomExitOnFailure(hr, "Failed to parse unknown ATOM link attribute: %ls", bstrNodeName); } ReleaseNullBSTR(bstrNodeName); ReleaseNullObject(pNode); } - ExitOnFailure(hr, "Failed to process all ATOM link attributes."); + AtomExitOnFailure(hr, "Failed to process all ATOM link attributes."); // Process elements second. hr = pixnLink->get_childNodes(&pNodeList); - ExitOnFailure(hr, "Failed to get child nodes of ATOM link element."); + AtomExitOnFailure(hr, "Failed to get child nodes of ATOM link element."); while (S_OK == (hr = XmlNextElement(pNodeList, &pNode, &bstrNodeName))) { hr = ParseAtomUnknownElement(pNode, &pLink->pUnknownElements); - ExitOnFailure(hr, "Failed to parse unknown ATOM link element: %ls", bstrNodeName); + AtomExitOnFailure(hr, "Failed to parse unknown ATOM link element: %ls", bstrNodeName); ReleaseNullBSTR(bstrNodeName); ReleaseNullObject(pNode); } - ExitOnFailure(hr, "Failed to process all ATOM link elements."); + AtomExitOnFailure(hr, "Failed to process all ATOM link elements."); hr = AssignString(&pLink->wzValue, pixnLink); - ExitOnFailure(hr, "Failed to allocate ATOM link value."); + AtomExitOnFailure(hr, "Failed to allocate ATOM link value."); LExit: ReleaseBSTR(bstrNodeName); @@ -916,39 +929,39 @@ static HRESULT ParseAtomUnknownElement( ATOM_UNKNOWN_ELEMENT* pNewUnknownElement; pNewUnknownElement = (ATOM_UNKNOWN_ELEMENT*)MemAlloc(sizeof(ATOM_UNKNOWN_ELEMENT), TRUE); - ExitOnNull(pNewUnknownElement, hr, E_OUTOFMEMORY, "Failed to allocate unknown element."); + AtomExitOnNull(pNewUnknownElement, hr, E_OUTOFMEMORY, "Failed to allocate unknown element."); hr = pNode->get_namespaceURI(&bstrNodeNamespace); if (S_OK == hr) { hr = StrAllocString(&pNewUnknownElement->wzNamespace, bstrNodeNamespace, 0); - ExitOnFailure(hr, "Failed to allocate ATOM unknown element namespace."); + AtomExitOnFailure(hr, "Failed to allocate ATOM unknown element namespace."); } else if (S_FALSE == hr) { hr = S_OK; } - ExitOnFailure(hr, "Failed to get unknown element namespace."); + AtomExitOnFailure(hr, "Failed to get unknown element namespace."); hr = pNode->get_baseName(&bstrNodeName); - ExitOnFailure(hr, "Failed to get unknown element name."); + AtomExitOnFailure(hr, "Failed to get unknown element name."); hr = StrAllocString(&pNewUnknownElement->wzElement, bstrNodeName, 0); - ExitOnFailure(hr, "Failed to allocate ATOM unknown element name."); + AtomExitOnFailure(hr, "Failed to allocate ATOM unknown element name."); hr = XmlGetText(pNode, &bstrNodeValue); - ExitOnFailure(hr, "Failed to get unknown element value."); + AtomExitOnFailure(hr, "Failed to get unknown element value."); hr = StrAllocString(&pNewUnknownElement->wzValue, bstrNodeValue, 0); - ExitOnFailure(hr, "Failed to allocate ATOM unknown element value."); + AtomExitOnFailure(hr, "Failed to allocate ATOM unknown element value."); hr = pNode->get_attributes(&pixnnmAttributes); - ExitOnFailure(hr, "Failed get attributes on ATOM unknown element."); + AtomExitOnFailure(hr, "Failed get attributes on ATOM unknown element."); while (S_OK == (hr = pixnnmAttributes->nextNode(&pixnAttribute))) { hr = ParseAtomUnknownAttribute(pixnAttribute, &pNewUnknownElement->pAttributes); - ExitOnFailure(hr, "Failed to parse attribute on ATOM unknown element."); + AtomExitOnFailure(hr, "Failed to parse attribute on ATOM unknown element."); ReleaseNullObject(pixnAttribute); } @@ -957,7 +970,7 @@ static HRESULT ParseAtomUnknownElement( { hr = S_OK; } - ExitOnFailure(hr, "Failed to enumerate all attributes on ATOM unknown element."); + AtomExitOnFailure(hr, "Failed to enumerate all attributes on ATOM unknown element."); ATOM_UNKNOWN_ELEMENT** ppTail = ppUnknownElement; while (*ppTail) @@ -999,31 +1012,31 @@ static HRESULT ParseAtomUnknownAttribute( ATOM_UNKNOWN_ATTRIBUTE* pNewUnknownAttribute; pNewUnknownAttribute = (ATOM_UNKNOWN_ATTRIBUTE*)MemAlloc(sizeof(ATOM_UNKNOWN_ATTRIBUTE), TRUE); - ExitOnNull(pNewUnknownAttribute, hr, E_OUTOFMEMORY, "Failed to allocate unknown attribute."); + AtomExitOnNull(pNewUnknownAttribute, hr, E_OUTOFMEMORY, "Failed to allocate unknown attribute."); hr = pNode->get_namespaceURI(&bstrNodeNamespace); if (S_OK == hr) { hr = StrAllocString(&pNewUnknownAttribute->wzNamespace, bstrNodeNamespace, 0); - ExitOnFailure(hr, "Failed to allocate ATOM unknown attribute namespace."); + AtomExitOnFailure(hr, "Failed to allocate ATOM unknown attribute namespace."); } else if (S_FALSE == hr) { hr = S_OK; } - ExitOnFailure(hr, "Failed to get unknown attribute namespace."); + AtomExitOnFailure(hr, "Failed to get unknown attribute namespace."); hr = pNode->get_baseName(&bstrNodeName); - ExitOnFailure(hr, "Failed to get unknown attribute name."); + AtomExitOnFailure(hr, "Failed to get unknown attribute name."); hr = StrAllocString(&pNewUnknownAttribute->wzAttribute, bstrNodeName, 0); - ExitOnFailure(hr, "Failed to allocate ATOM unknown attribute name."); + AtomExitOnFailure(hr, "Failed to allocate ATOM unknown attribute name."); hr = XmlGetText(pNode, &bstrNodeValue); - ExitOnFailure(hr, "Failed to get unknown attribute value."); + AtomExitOnFailure(hr, "Failed to get unknown attribute value."); hr = StrAllocString(&pNewUnknownAttribute->wzValue, bstrNodeValue, 0); - ExitOnFailure(hr, "Failed to allocate ATOM unknown attribute value."); + AtomExitOnFailure(hr, "Failed to allocate ATOM unknown attribute value."); ATOM_UNKNOWN_ATTRIBUTE** ppTail = ppUnknownAttribute; while (*ppTail) @@ -1060,16 +1073,16 @@ static HRESULT AssignDateTime( if (0 != pft->dwHighDateTime || 0 != pft->dwLowDateTime) { hr = HRESULT_FROM_WIN32(ERROR_INVALID_DATA); - ExitOnRootFailure(hr, "Already process this datetime value."); + AtomExitOnRootFailure(hr, "Already process this datetime value."); } hr = XmlGetText(pNode, &bstrValue); - ExitOnFailure(hr, "Failed to get value."); + AtomExitOnFailure(hr, "Failed to get value."); if (S_OK == hr) { hr = TimeFromString3339(bstrValue, pft); - ExitOnFailure(hr, "Failed to convert value to time."); + AtomExitOnFailure(hr, "Failed to convert value to time."); } else { @@ -1099,16 +1112,16 @@ static HRESULT AssignString( if (pwzValue && *pwzValue) { hr = HRESULT_FROM_WIN32(ERROR_INVALID_DATA); - ExitOnRootFailure(hr, "Already processed this value."); + AtomExitOnRootFailure(hr, "Already processed this value."); } hr = XmlGetText(pNode, &bstrValue); - ExitOnFailure(hr, "Failed to get value."); + AtomExitOnFailure(hr, "Failed to get value."); if (S_OK == hr) { hr = StrAllocString(pwzValue, bstrValue, 0); - ExitOnFailure(hr, "Failed to allocate value."); + AtomExitOnFailure(hr, "Failed to allocate value."); } else { diff --git a/src/dutil/buffutil.cpp b/src/dutil/buffutil.cpp index a70aaa81..a6d3ac90 100644 --- a/src/dutil/buffutil.cpp +++ b/src/dutil/buffutil.cpp @@ -3,6 +3,21 @@ #include "precomp.h" +// Exit macros +#define BuffExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_BUFFUTIL, x, s, __VA_ARGS__) +#define BuffExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_BUFFUTIL, x, s, __VA_ARGS__) +#define BuffExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_BUFFUTIL, x, s, __VA_ARGS__) +#define BuffExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_BUFFUTIL, x, s, __VA_ARGS__) +#define BuffExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_BUFFUTIL, x, s, __VA_ARGS__) +#define BuffExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_BUFFUTIL, x, s, __VA_ARGS__) +#define BuffExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_BUFFUTIL, p, x, e, s, __VA_ARGS__) +#define BuffExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_BUFFUTIL, p, x, s, __VA_ARGS__) +#define BuffExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_BUFFUTIL, p, x, e, s, __VA_ARGS__) +#define BuffExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_BUFFUTIL, p, x, s, __VA_ARGS__) +#define BuffExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_BUFFUTIL, e, x, s, __VA_ARGS__) +#define BuffExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_BUFFUTIL, g, x, s, __VA_ARGS__) + + // constants #define BUFFER_INCREMENT 128 @@ -11,7 +26,7 @@ // helper function declarations static HRESULT EnsureBufferSize( - __deref_out_bcount(cbSize) BYTE** ppbBuffer, + __deref_inout_bcount(cbSize) BYTE** ppbBuffer, __in SIZE_T cbSize ); @@ -34,13 +49,13 @@ extern "C" HRESULT BuffReadNumber( // get availiable data size hr = ::SIZETSub(cbBuffer, *piBuffer, &cbAvailable); - ExitOnRootFailure(hr, "Failed to calculate available data size."); + BuffExitOnRootFailure(hr, "Failed to calculate available data size."); // verify buffer size if (sizeof(DWORD) > cbAvailable) { hr = E_INVALIDARG; - ExitOnRootFailure(hr, "Buffer too small."); + BuffExitOnRootFailure(hr, "Buffer too small."); } *pdw = *(const DWORD*)(pbBuffer + *piBuffer); @@ -66,13 +81,13 @@ extern "C" HRESULT BuffReadNumber64( // get availiable data size hr = ::SIZETSub(cbBuffer, *piBuffer, &cbAvailable); - ExitOnRootFailure(hr, "Failed to calculate available data size."); + BuffExitOnRootFailure(hr, "Failed to calculate available data size."); // verify buffer size if (sizeof(DWORD64) > cbAvailable) { hr = E_INVALIDARG; - ExitOnRootFailure(hr, "Buffer too small."); + BuffExitOnRootFailure(hr, "Buffer too small."); } *pdw64 = *(const DWORD64*)(pbBuffer + *piBuffer); @@ -98,13 +113,13 @@ extern "C" HRESULT BuffReadPointer( // get availiable data size hr = ::SIZETSub(cbBuffer, *piBuffer, &cbAvailable); - ExitOnRootFailure(hr, "Failed to calculate available data size."); + BuffExitOnRootFailure(hr, "Failed to calculate available data size."); // verify buffer size if (sizeof(DWORD_PTR) > cbAvailable) { hr = E_INVALIDARG; - ExitOnRootFailure(hr, "Buffer too small."); + BuffExitOnRootFailure(hr, "Buffer too small."); } *pdw64 = *(const DWORD_PTR*)(pbBuffer + *piBuffer); @@ -132,38 +147,38 @@ extern "C" HRESULT BuffReadString( // get availiable data size hr = ::SIZETSub(cbBuffer, *piBuffer, &cbAvailable); - ExitOnRootFailure(hr, "Failed to calculate available data size for character count."); + BuffExitOnRootFailure(hr, "Failed to calculate available data size for character count."); // verify buffer size if (sizeof(DWORD) > cbAvailable) { hr = E_INVALIDARG; - ExitOnRootFailure(hr, "Buffer too small."); + BuffExitOnRootFailure(hr, "Buffer too small."); } // read character count cch = *(const DWORD*)(pbBuffer + *piBuffer); hr = ::DWordMult(cch, static_cast(sizeof(WCHAR)), &cb); - ExitOnRootFailure(hr, "Overflow while multiplying to calculate buffer size"); + BuffExitOnRootFailure(hr, "Overflow while multiplying to calculate buffer size"); hr = ::SIZETAdd(*piBuffer, sizeof(DWORD), piBuffer); - ExitOnRootFailure(hr, "Overflow while adding to calculate buffer size"); + BuffExitOnRootFailure(hr, "Overflow while adding to calculate buffer size"); // get availiable data size hr = ::SIZETSub(cbBuffer, *piBuffer, &cbAvailable); - ExitOnRootFailure(hr, "Failed to calculate available data size for character buffer."); + BuffExitOnRootFailure(hr, "Failed to calculate available data size for character buffer."); // verify buffer size if (cb > cbAvailable) { hr = E_INVALIDARG; - ExitOnRootFailure(hr, "Buffer too small to hold character data."); + BuffExitOnRootFailure(hr, "Buffer too small to hold character data."); } // copy character data hr = StrAllocString(pscz, cch ? (LPCWSTR)(pbBuffer + *piBuffer) : L"", cch); - ExitOnFailure(hr, "Failed to copy character data."); + BuffExitOnFailure(hr, "Failed to copy character data."); *piBuffer += cb; @@ -189,38 +204,38 @@ extern "C" HRESULT BuffReadStringAnsi( // get availiable data size hr = ::SIZETSub(cbBuffer, *piBuffer, &cbAvailable); - ExitOnRootFailure(hr, "Failed to calculate available data size for character count."); + BuffExitOnRootFailure(hr, "Failed to calculate available data size for character count."); // verify buffer size if (sizeof(DWORD) > cbAvailable) { hr = E_INVALIDARG; - ExitOnRootFailure(hr, "Buffer too small."); + BuffExitOnRootFailure(hr, "Buffer too small."); } // read character count cch = *(const DWORD*)(pbBuffer + *piBuffer); hr = ::DWordMult(cch, static_cast(sizeof(CHAR)), &cb); - ExitOnRootFailure(hr, "Overflow while multiplying to calculate buffer size"); + BuffExitOnRootFailure(hr, "Overflow while multiplying to calculate buffer size"); hr = ::SIZETAdd(*piBuffer, sizeof(DWORD), piBuffer); - ExitOnRootFailure(hr, "Overflow while adding to calculate buffer size"); + BuffExitOnRootFailure(hr, "Overflow while adding to calculate buffer size"); // get availiable data size hr = ::SIZETSub(cbBuffer, *piBuffer, &cbAvailable); - ExitOnRootFailure(hr, "Failed to calculate available data size for character buffer."); + BuffExitOnRootFailure(hr, "Failed to calculate available data size for character buffer."); // verify buffer size if (cb > cbAvailable) { hr = E_INVALIDARG; - ExitOnRootFailure(hr, "Buffer too small to hold character count."); + BuffExitOnRootFailure(hr, "Buffer too small to hold character count."); } // copy character data hr = StrAnsiAllocStringAnsi(pscz, cch ? (LPCSTR)(pbBuffer + *piBuffer) : "", cch); - ExitOnFailure(hr, "Failed to copy character data."); + BuffExitOnFailure(hr, "Failed to copy character data."); *piBuffer += cb; @@ -232,7 +247,7 @@ extern "C" HRESULT BuffReadStream( __in_bcount(cbBuffer) const BYTE* pbBuffer, __in SIZE_T cbBuffer, __inout SIZE_T* piBuffer, - __deref_out_bcount(*pcbStream) BYTE** ppbStream, + __deref_inout_bcount(*pcbStream) BYTE** ppbStream, __out SIZE_T* pcbStream ) { @@ -247,13 +262,13 @@ extern "C" HRESULT BuffReadStream( // get availiable data size hr = ::SIZETSub(cbBuffer, *piBuffer, &cbAvailable); - ExitOnRootFailure(hr, "Failed to calculate available data size for stream size."); + BuffExitOnRootFailure(hr, "Failed to calculate available data size for stream size."); // verify buffer size if (sizeof(DWORD64) > cbAvailable) { hr = E_INVALIDARG; - ExitOnRootFailure(hr, "Buffer too small."); + BuffExitOnRootFailure(hr, "Buffer too small."); } // read stream size @@ -262,18 +277,18 @@ extern "C" HRESULT BuffReadStream( // get availiable data size hr = ::SIZETSub(cbBuffer, *piBuffer, &cbAvailable); - ExitOnRootFailure(hr, "Failed to calculate available data size for stream buffer."); + BuffExitOnRootFailure(hr, "Failed to calculate available data size for stream buffer."); // verify buffer size if (cb > cbAvailable) { hr = E_INVALIDARG; - ExitOnRootFailure(hr, "Buffer too small to hold byte count."); + BuffExitOnRootFailure(hr, "Buffer too small to hold byte count."); } // allocate buffer *ppbStream = (BYTE*)MemAlloc((SIZE_T)cb, TRUE); - ExitOnNull(*ppbStream, hr, E_OUTOFMEMORY, "Failed to allocate stream."); + BuffExitOnNull(*ppbStream, hr, E_OUTOFMEMORY, "Failed to allocate stream."); // read stream data memcpy_s(*ppbStream, cbBuffer - *piBuffer, pbBuffer + *piBuffer, (SIZE_T)cb); @@ -287,7 +302,7 @@ LExit: } extern "C" HRESULT BuffWriteNumber( - __deref_out_bcount(*piBuffer) BYTE** ppbBuffer, + __deref_inout_bcount(*piBuffer) BYTE** ppbBuffer, __inout SIZE_T* piBuffer, __in DWORD_PTR dw ) @@ -299,7 +314,7 @@ extern "C" HRESULT BuffWriteNumber( // make sure we have a buffer with sufficient space hr = EnsureBufferSize(ppbBuffer, *piBuffer + sizeof(DWORD)); - ExitOnFailure(hr, "Failed to ensure buffer size."); + BuffExitOnFailure(hr, "Failed to ensure buffer size."); // copy data to buffer *(DWORD_PTR*)(*ppbBuffer + *piBuffer) = dw; @@ -310,7 +325,7 @@ LExit: } extern "C" HRESULT BuffWriteNumber64( - __deref_out_bcount(*piBuffer) BYTE** ppbBuffer, + __deref_inout_bcount(*piBuffer) BYTE** ppbBuffer, __inout SIZE_T* piBuffer, __in DWORD64 dw64 ) @@ -322,7 +337,7 @@ extern "C" HRESULT BuffWriteNumber64( // make sure we have a buffer with sufficient space hr = EnsureBufferSize(ppbBuffer, *piBuffer + sizeof(DWORD64)); - ExitOnFailure(hr, "Failed to ensure buffer size."); + BuffExitOnFailure(hr, "Failed to ensure buffer size."); // copy data to buffer *(DWORD64*)(*ppbBuffer + *piBuffer) = dw64; @@ -333,7 +348,7 @@ LExit: } extern "C" HRESULT BuffWritePointer( - __deref_out_bcount(*piBuffer) BYTE** ppbBuffer, + __deref_inout_bcount(*piBuffer) BYTE** ppbBuffer, __inout SIZE_T* piBuffer, __in DWORD_PTR dw ) @@ -345,7 +360,7 @@ extern "C" HRESULT BuffWritePointer( // make sure we have a buffer with sufficient space hr = EnsureBufferSize(ppbBuffer, *piBuffer + sizeof(DWORD_PTR)); - ExitOnFailure(hr, "Failed to ensure buffer size."); + BuffExitOnFailure(hr, "Failed to ensure buffer size."); // copy data to buffer *(DWORD_PTR*)(*ppbBuffer + *piBuffer) = dw; @@ -356,7 +371,7 @@ LExit: } extern "C" HRESULT BuffWriteString( - __deref_out_bcount(*piBuffer) BYTE** ppbBuffer, + __deref_inout_bcount(*piBuffer) BYTE** ppbBuffer, __inout SIZE_T* piBuffer, __in_z_opt LPCWSTR scz ) @@ -370,7 +385,7 @@ extern "C" HRESULT BuffWriteString( // make sure we have a buffer with sufficient space hr = EnsureBufferSize(ppbBuffer, *piBuffer + (sizeof(DWORD) + cb)); - ExitOnFailure(hr, "Failed to ensure buffer size."); + BuffExitOnFailure(hr, "Failed to ensure buffer size."); // copy character count to buffer *(DWORD*)(*ppbBuffer + *piBuffer) = cch; @@ -385,7 +400,7 @@ LExit: } extern "C" HRESULT BuffWriteStringAnsi( - __deref_out_bcount(*piBuffer) BYTE** ppbBuffer, + __deref_inout_bcount(*piBuffer) BYTE** ppbBuffer, __inout SIZE_T* piBuffer, __in_z_opt LPCSTR scz ) @@ -399,7 +414,7 @@ extern "C" HRESULT BuffWriteStringAnsi( // make sure we have a buffer with sufficient space hr = EnsureBufferSize(ppbBuffer, *piBuffer + (sizeof(DWORD) + cb)); - ExitOnFailure(hr, "Failed to ensure buffer size."); + BuffExitOnFailure(hr, "Failed to ensure buffer size."); // copy character count to buffer *(DWORD*)(*ppbBuffer + *piBuffer) = cch; @@ -414,7 +429,7 @@ LExit: } extern "C" HRESULT BuffWriteStream( - __deref_out_bcount(*piBuffer) BYTE** ppbBuffer, + __deref_inout_bcount(*piBuffer) BYTE** ppbBuffer, __inout SIZE_T* piBuffer, __in_bcount(cbStream) const BYTE* pbStream, __in SIZE_T cbStream @@ -429,7 +444,7 @@ extern "C" HRESULT BuffWriteStream( // make sure we have a buffer with sufficient space hr = EnsureBufferSize(ppbBuffer, *piBuffer + cbStream + sizeof(DWORD64)); - ExitOnFailure(hr, "Failed to ensure buffer size."); + BuffExitOnFailure(hr, "Failed to ensure buffer size."); // copy byte count to buffer *(DWORD64*)(*ppbBuffer + *piBuffer) = cb; @@ -447,7 +462,7 @@ LExit: // helper functions static HRESULT EnsureBufferSize( - __deref_out_bcount(cbSize) BYTE** ppbBuffer, + __deref_inout_bcount(cbSize) BYTE** ppbBuffer, __in SIZE_T cbSize ) { @@ -459,14 +474,14 @@ static HRESULT EnsureBufferSize( if (MemSize(*ppbBuffer) < cbTarget) { LPVOID pv = MemReAlloc(*ppbBuffer, cbTarget, TRUE); - ExitOnNull(pv, hr, E_OUTOFMEMORY, "Failed to reallocate buffer."); + BuffExitOnNull(pv, hr, E_OUTOFMEMORY, "Failed to reallocate buffer."); *ppbBuffer = (BYTE*)pv; } } else { *ppbBuffer = (BYTE*)MemAlloc(cbTarget, TRUE); - ExitOnNull(*ppbBuffer, hr, E_OUTOFMEMORY, "Failed to allocate buffer."); + BuffExitOnNull(*ppbBuffer, hr, E_OUTOFMEMORY, "Failed to allocate buffer."); } LExit: diff --git a/src/dutil/cabcutil.cpp b/src/dutil/cabcutil.cpp index 8619822d..93a9b7e1 100644 --- a/src/dutil/cabcutil.cpp +++ b/src/dutil/cabcutil.cpp @@ -2,6 +2,22 @@ #include "precomp.h" + +// Exit macros +#define CabcExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_CABCUTIL, x, s, __VA_ARGS__) +#define CabcExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_CABCUTIL, x, s, __VA_ARGS__) +#define CabcExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_CABCUTIL, x, s, __VA_ARGS__) +#define CabcExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_CABCUTIL, x, s, __VA_ARGS__) +#define CabcExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_CABCUTIL, x, s, __VA_ARGS__) +#define CabcExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_CABCUTIL, x, s, __VA_ARGS__) +#define CabcExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_CABCUTIL, p, x, e, s, __VA_ARGS__) +#define CabcExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_CABCUTIL, p, x, s, __VA_ARGS__) +#define CabcExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_CABCUTIL, p, x, e, s, __VA_ARGS__) +#define CabcExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_CABCUTIL, p, x, s, __VA_ARGS__) +#define CabcExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_CABCUTIL, e, x, s, __VA_ARGS__) +#define CabcExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_CABCUTIL, g, x, s, __VA_ARGS__) + + static const WCHAR CABC_MAGIC_UNICODE_STRING_MARKER = '?'; static const DWORD MAX_CABINET_HEADER_SIZE = 16 * 1024 * 1024; @@ -144,19 +160,19 @@ static HRESULT UtcFileTimeToLocalDosDateTime( __out USHORT* pTime ); -static __callback int DIAMONDAPI CabCFilePlaced(__in PCCAB pccab, __in_z PSTR szFile, __in long cbFile, __in BOOL fContinuation, __out_bcount(CABC_HANDLE_BYTES) void *pv); +static __callback int DIAMONDAPI CabCFilePlaced(__in PCCAB pccab, __in_z PSTR szFile, __in long cbFile, __in BOOL fContinuation, __inout_bcount(CABC_HANDLE_BYTES) void *pv); static __callback void * DIAMONDAPI CabCAlloc(__in ULONG cb); static __callback void DIAMONDAPI CabCFree(__out_bcount(CABC_HANDLE_BYTES) void *pv); -static __callback INT_PTR DIAMONDAPI CabCOpen(__in_z PSTR pszFile, __in int oflag, __in int pmode, __out int *err, __out_bcount(CABC_HANDLE_BYTES) void *pv); -static __callback UINT FAR DIAMONDAPI CabCRead(__in INT_PTR hf, __out_bcount(cb) void FAR *memory, __in UINT cb, __out int *err, __out_bcount(CABC_HANDLE_BYTES) void *pv); -static __callback UINT FAR DIAMONDAPI CabCWrite(__in INT_PTR hf, __in_bcount(cb) void FAR *memory, __in UINT cb, __out int *err, __out_bcount(CABC_HANDLE_BYTES) void *pv); -static __callback long FAR DIAMONDAPI CabCSeek(__in INT_PTR hf, __in long dist, __in int seektype, __out int *err, __out_bcount(CABC_HANDLE_BYTES) void *pv); -static __callback int FAR DIAMONDAPI CabCClose(__in INT_PTR hf, __out int *err, __out_bcount(CABC_HANDLE_BYTES) void *pv); -static __callback int DIAMONDAPI CabCDelete(__in_z PSTR szFile, __out int *err, __out_bcount(CABC_HANDLE_BYTES) void *pv); -__success(return != FALSE) static __callback BOOL DIAMONDAPI CabCGetTempFile(__out_bcount_z(cbFile) char *szFile, __in int cbFile, __out_bcount(CABC_HANDLE_BYTES) void *pv); +static __callback INT_PTR DIAMONDAPI CabCOpen(__in_z PSTR pszFile, __in int oflag, __in int pmode, __out int *err, __inout_bcount(CABC_HANDLE_BYTES) void *pv); +static __callback UINT FAR DIAMONDAPI CabCRead(__in INT_PTR hf, __out_bcount(cb) void FAR *memory, __in UINT cb, __out int *err, __inout_bcount(CABC_HANDLE_BYTES) void *pv); +static __callback UINT FAR DIAMONDAPI CabCWrite(__in INT_PTR hf, __in_bcount(cb) void FAR *memory, __in UINT cb, __out int *err, __inout_bcount(CABC_HANDLE_BYTES) void *pv); +static __callback long FAR DIAMONDAPI CabCSeek(__in INT_PTR hf, __in long dist, __in int seektype, __out int *err, __inout_bcount(CABC_HANDLE_BYTES) void *pv); +static __callback int FAR DIAMONDAPI CabCClose(__in INT_PTR hf, __out int *err, __inout_bcount(CABC_HANDLE_BYTES) void *pv); +static __callback int DIAMONDAPI CabCDelete(__in_z PSTR szFile, __out int *err, __inout_bcount(CABC_HANDLE_BYTES) void *pv); +__success(return != FALSE) static __callback BOOL DIAMONDAPI CabCGetTempFile(__out_bcount_z(cbFile) char *szFile, __in int cbFile, __inout_bcount(CABC_HANDLE_BYTES) void *pv); __success(return != FALSE) static __callback BOOL DIAMONDAPI CabCGetNextCabinet(__in PCCAB pccab, __in ULONG ul, __out_bcount(CABC_HANDLE_BYTES) void *pv); static __callback INT_PTR DIAMONDAPI CabCGetOpenInfo(__in_z PSTR pszName, __out USHORT *pdate, __out USHORT *ptime, __out USHORT *pattribs, __out int *err, __out_bcount(CABC_HANDLE_BYTES) void *pv); -static __callback long DIAMONDAPI CabCStatus(__in UINT uiTypeStatus, __in ULONG cb1, __in ULONG cb2, __out_bcount(CABC_HANDLE_BYTES) void *pv); +static __callback long DIAMONDAPI CabCStatus(__in UINT uiTypeStatus, __in ULONG cb1, __in ULONG cb2, __inout_bcount(CABC_HANDLE_BYTES) void *pv); /******************************************************************** @@ -174,7 +190,7 @@ extern "C" HRESULT DAPI CabCBegin( __in DWORD dwMaxSize, __in DWORD dwMaxThresh, __in COMPRESSION_TYPE ct, - __out HANDLE *phContext + __out_bcount(CABC_HANDLE_BYTES) HANDLE *phContext ) { Assert(wzCab && *wzCab && phContext); @@ -190,28 +206,28 @@ extern "C" HRESULT DAPI CabCBegin( if (wzCabDir) { hr = ::StringCchLengthW(wzCabDir, MAX_PATH, &cchPathBuffer); - ExitOnFailure(hr, "Failed to get length of cab directory"); + CabcExitOnFailure(hr, "Failed to get length of cab directory"); // Need room to terminate with L'\\' and L'\0' if((MAX_PATH - 1) <= cchPathBuffer || 0 == cchPathBuffer) { hr = E_INVALIDARG; - ExitOnFailure(hr, "Cab directory had invalid length: %u", cchPathBuffer); + CabcExitOnFailure(hr, "Cab directory had invalid length: %u", cchPathBuffer); } hr = ::StringCchCopyW(wzPathBuffer, countof(wzPathBuffer), wzCabDir); - ExitOnFailure(hr, "Failed to copy cab directory to buffer"); + CabcExitOnFailure(hr, "Failed to copy cab directory to buffer"); if (L'\\' != wzPathBuffer[cchPathBuffer - 1]) { hr = ::StringCchCatW(wzPathBuffer, countof(wzPathBuffer), L"\\"); - ExitOnFailure(hr, "Failed to cat \\ to end of buffer"); + CabcExitOnFailure(hr, "Failed to cat \\ to end of buffer"); ++cchPathBuffer; } } pcd = static_cast(MemAlloc(sizeof(CABC_DATA), TRUE)); - ExitOnNull(pcd, hr, E_OUTOFMEMORY, "failed to allocate cab creation data structure"); + CabcExitOnNull(pcd, hr, E_OUTOFMEMORY, "failed to allocate cab creation data structure"); pcd->hrLastError = S_OK; pcd->fGoodCab = TRUE; @@ -266,35 +282,35 @@ extern "C" HRESULT DAPI CabCBegin( else { hr = E_INVALIDARG; - ExitOnFailure(hr, "Invalid compression type specified."); + CabcExitOnFailure(hr, "Invalid compression type specified."); } if (0 == ::WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, wzCab, -1, pcd->ccab.szCab, sizeof(pcd->ccab.szCab), NULL, NULL)) { - ExitWithLastError(hr, "failed to convert cab name to multi-byte"); + CabcExitWithLastError(hr, "failed to convert cab name to multi-byte"); } if (0 == ::WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, wzPathBuffer, -1, pcd->ccab.szCabPath, sizeof(pcd->ccab.szCab), NULL, NULL)) { - ExitWithLastError(hr, "failed to convert cab dir to multi-byte"); + CabcExitWithLastError(hr, "failed to convert cab dir to multi-byte"); } // Remember the path to the cabinet. hr= ::StringCchCopyW(pcd->wzCabinetPath, countof(pcd->wzCabinetPath), wzPathBuffer); - ExitOnFailure(hr, "Failed to copy cabinet path from path: %ls", wzPathBuffer); + CabcExitOnFailure(hr, "Failed to copy cabinet path from path: %ls", wzPathBuffer); hr = ::StringCchCatW(pcd->wzCabinetPath, countof(pcd->wzCabinetPath), wzCab); - ExitOnFailure(hr, "Failed to concat to cabinet path cabinet name: %ls", wzCab); + CabcExitOnFailure(hr, "Failed to concat to cabinet path cabinet name: %ls", wzCab); // Get the empty file to use as the blank marker for duplicates. if (!::GetTempPathW(countof(wzTempPath), wzTempPath)) { - ExitWithLastError(hr, "Failed to get temp path."); + CabcExitWithLastError(hr, "Failed to get temp path."); } if (!::GetTempFileNameW(wzTempPath, L"WSC", 0, pcd->wzEmptyFile)) { - ExitWithLastError(hr, "Failed to create a temp file name."); + CabcExitWithLastError(hr, "Failed to create a temp file name."); } // Try to open the newly created empty file (remember, GetTempFileName() is kind enough to create a file for us) @@ -303,7 +319,7 @@ extern "C" HRESULT DAPI CabCBegin( pcd->hEmptyFile = ::CreateFileW(pcd->wzEmptyFile, 0, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE, NULL); hr = DictCreateWithEmbeddedKey(&pcd->shDictHandle, dwMaxFiles, reinterpret_cast(&pcd->prgFiles), offsetof(CABC_FILE, pwzSourcePath), DICT_FLAG_CASEINSENSITIVE); - ExitOnFailure(hr, "Failed to create dictionary to keep track of duplicate files"); + CabcExitOnFailure(hr, "Failed to create dictionary to keep track of duplicate files"); // Make sure to allocate at least some space, or we won't be able to realloc later if they "lied" about having zero files if (1 > dwMaxFiles) @@ -315,10 +331,10 @@ extern "C" HRESULT DAPI CabCBegin( size_t cbFileAllocSize = 0; hr = ::SizeTMult(pcd->cMaxFilePaths, sizeof(CABC_FILE), &(cbFileAllocSize)); - ExitOnFailure(hr, "Maximum allocation exceeded on initialization."); + CabcExitOnFailure(hr, "Maximum allocation exceeded on initialization."); pcd->prgFiles = static_cast(MemAlloc(cbFileAllocSize, TRUE)); - ExitOnNull(pcd->prgFiles, hr, E_OUTOFMEMORY, "Failed to allocate memory for files."); + CabcExitOnNull(pcd->prgFiles, hr, E_OUTOFMEMORY, "Failed to allocate memory for files."); // Tell cabinet API about our configuration. pcd->hfci = ::FCICreate(&(pcd->erf), CabCFilePlaced, CabCAlloc, CabCFree, CabCOpen, CabCRead, CabCWrite, CabCClose, CabCSeek, CabCDelete, CabCGetTempFile, &(pcd->ccab), pcd); @@ -331,12 +347,12 @@ extern "C" HRESULT DAPI CabCBegin( } else { - ExitWithLastError(hr, "failed to create FCI object Oper: 0x%x Type: 0x%x", pcd->erf.erfOper, pcd->erf.erfType); + CabcExitWithLastError(hr, "failed to create FCI object Oper: 0x%x Type: 0x%x", pcd->erf.erfOper, pcd->erf.erfType); } pcd->fGoodCab = FALSE; - ExitOnFailure(hr, "failed to create FCI object Oper: 0x%x Type: 0x%x", pcd->erf.erfOper, pcd->erf.erfType); // TODO: can these be converted to HRESULTS? + CabcExitOnFailure(hr, "failed to create FCI object Oper: 0x%x Type: 0x%x", pcd->erf.erfOper, pcd->erf.erfType); // TODO: can these be converted to HRESULTS? } *phContext = pcd; @@ -392,25 +408,25 @@ extern "C" HRESULT DAPI CabCAddFile( { // Store file size, primarily used to determine which files to hash for duplicates hr = FileSize(wzFile, &llFileSize); - ExitOnFailure(hr, "Failed to check size of file %ls", wzFile); + CabcExitOnFailure(hr, "Failed to check size of file %ls", wzFile); hr = CheckForDuplicateFile(pcd, &pcfDuplicate, wzFile, &pmfLocalHash, llFileSize); - ExitOnFailure(hr, "Failed while checking for duplicate of file: %ls", wzFile); + CabcExitOnFailure(hr, "Failed while checking for duplicate of file: %ls", wzFile); } if (pcfDuplicate) // This will be null for smart cabbing case { DWORD index; hr = ::PtrdiffTToDWord(pcfDuplicate - pcd->prgFiles, &index); - ExitOnFailure(hr, "Failed to calculate index of file name: %ls", pcfDuplicate->pwzSourcePath); + CabcExitOnFailure(hr, "Failed to calculate index of file name: %ls", pcfDuplicate->pwzSourcePath); hr = AddDuplicateFile(pcd, index, wzFile, wzToken, pcd->dwLastFileIndex); - ExitOnFailure(hr, "Failed to add duplicate of file name: %ls", pcfDuplicate->pwzSourcePath); + CabcExitOnFailure(hr, "Failed to add duplicate of file name: %ls", pcfDuplicate->pwzSourcePath); } else { hr = AddNonDuplicateFile(pcd, wzFile, wzToken, pmfLocalHash, llFileSize, pcd->dwLastFileIndex); - ExitOnFailure(hr, "Failed to add non-duplicated file: %ls", wzFile); + CabcExitOnFailure(hr, "Failed to add non-duplicated file: %ls", wzFile); } ++pcd->dwLastFileIndex; @@ -483,13 +499,13 @@ extern "C" HRESULT DAPI CabCFinish( { LPCWSTR pwzTemp = pcd->prgFiles[dwArrayFileIndex].pwzToken; hr = StrAnsiAllocString(&pszFileToken, pwzTemp, 0, CP_ACP); - ExitOnFailure(hr, "failed to convert file token to ANSI: %ls", pwzTemp); + CabcExitOnFailure(hr, "failed to convert file token to ANSI: %ls", pwzTemp); } else { LPCWSTR pwzTemp = FileFromPath(fileInfo.wzSourcePath); hr = StrAnsiAllocString(&pszFileToken, pwzTemp, 0, CP_ACP); - ExitOnFailure(hr, "failed to convert file name to ANSI: %ls", pwzTemp); + CabcExitOnFailure(hr, "failed to convert file name to ANSI: %ls", pwzTemp); } if (pcd->prgFiles[dwArrayFileIndex].fHasDuplicates) @@ -518,13 +534,13 @@ extern "C" HRESULT DAPI CabCFinish( { LPCWSTR pwzTemp = pcd->prgDuplicates[dwDupeArrayFileIndex].pwzToken; hr = StrAnsiAllocString(&pszFileToken, pwzTemp, 0, CP_ACP); - ExitOnFailure(hr, "failed to convert duplicate file token to ANSI: %ls", pwzTemp); + CabcExitOnFailure(hr, "failed to convert duplicate file token to ANSI: %ls", pwzTemp); } else { LPCWSTR pwzTemp = FileFromPath(fileInfo.wzSourcePath); hr = StrAnsiAllocString(&pszFileToken, pwzTemp, 0, CP_ACP); - ExitOnFailure(hr, "failed to convert duplicate file name to ANSI: %ls", pwzTemp); + CabcExitOnFailure(hr, "failed to convert duplicate file name to ANSI: %ls", pwzTemp); } // Flush afterward only if this isn't a duplicate of the previous file, and at least one non-duplicate file remains to be added to the cab @@ -543,14 +559,14 @@ extern "C" HRESULT DAPI CabCFinish( else // If it's neither duplicate nor non-duplicate, throw an error { hr = HRESULT_FROM_WIN32(ERROR_EA_LIST_INCONSISTENT); - ExitOnRootFailure(hr, "Internal inconsistency in data structures while creating CAB file - a non-standard, non-duplicate file was encountered"); + CabcExitOnRootFailure(hr, "Internal inconsistency in data structures while creating CAB file - a non-standard, non-duplicate file was encountered"); } if (fFlushBefore && pcd->llBytesSinceLastFlush > pcd->llFlushThreshhold) { if (!::FCIFlushFolder(pcd->hfci, CabCGetNextCabinet, CabCStatus)) { - ExitWithLastError(hr, "failed to flush FCI folder before adding file, Oper: 0x%x Type: 0x%x", pcd->erf.erfOper, pcd->erf.erfType); + CabcExitWithLastError(hr, "failed to flush FCI folder before adding file, Oper: 0x%x Type: 0x%x", pcd->erf.erfOper, pcd->erf.erfType); } pcd->llBytesSinceLastFlush = 0; } @@ -574,10 +590,10 @@ extern "C" HRESULT DAPI CabCFinish( } else { - ExitWithLastError(hr, "failed to add file to FCI object Oper: 0x%x Type: 0x%x File: %ls", pcd->erf.erfOper, pcd->erf.erfType, fileInfo.wzSourcePath); + CabcExitWithLastError(hr, "failed to add file to FCI object Oper: 0x%x Type: 0x%x File: %ls", pcd->erf.erfOper, pcd->erf.erfType, fileInfo.wzSourcePath); } - ExitOnFailure(hr, "failed to add file to FCI object Oper: 0x%x Type: 0x%x File: %ls", pcd->erf.erfOper, pcd->erf.erfType, fileInfo.wzSourcePath); // TODO: can these be converted to HRESULTS? + CabcExitOnFailure(hr, "failed to add file to FCI object Oper: 0x%x Type: 0x%x File: %ls", pcd->erf.erfOper, pcd->erf.erfType, fileInfo.wzSourcePath); // TODO: can these be converted to HRESULTS? } // For Cabinet Splitting case, check for pcd->hrLastError that may be set as result of Error in CabCGetNextCabinet @@ -585,14 +601,14 @@ extern "C" HRESULT DAPI CabCFinish( if (pcd->fCabinetSplittingEnabled && FAILED(pcd->hrLastError)) { hr = pcd->hrLastError; - ExitOnFailure(hr, "Failed to create next cabinet name while splitting cabinet."); + CabcExitOnFailure(hr, "Failed to create next cabinet name while splitting cabinet."); } if (fFlushAfter && pcd->llBytesSinceLastFlush > pcd->llFlushThreshhold) { if (!::FCIFlushFolder(pcd->hfci, CabCGetNextCabinet, CabCStatus)) { - ExitWithLastError(hr, "failed to flush FCI folder after adding file, Oper: 0x%x Type: 0x%x", pcd->erf.erfOper, pcd->erf.erfType); + CabcExitWithLastError(hr, "failed to flush FCI folder after adding file, Oper: 0x%x Type: 0x%x", pcd->erf.erfOper, pcd->erf.erfType); } pcd->llBytesSinceLastFlush = 0; } @@ -610,10 +626,10 @@ extern "C" HRESULT DAPI CabCFinish( } else { - ExitWithLastError(hr, "failed while creating CAB FCI object Oper: 0x%x Type: 0x%x File: %s", pcd->erf.erfOper, pcd->erf.erfType); + CabcExitWithLastError(hr, "failed while creating CAB FCI object Oper: 0x%x Type: 0x%x File: %ls", pcd->erf.erfOper, pcd->erf.erfType, fileInfo.wzSourcePath); } - ExitOnFailure(hr, "failed while creating CAB FCI object Oper: 0x%x Type: 0x%x File: %s", pcd->erf.erfOper, pcd->erf.erfType); // TODO: can these be converted to HRESULTS? + CabcExitOnFailure(hr, "failed while creating CAB FCI object Oper: 0x%x Type: 0x%x File: %ls", pcd->erf.erfOper, pcd->erf.erfType, fileInfo.wzSourcePath); // TODO: can these be converted to HRESULTS? } // Only flush the cabinet if we actually succeeded in previous calls - otherwise we just waste time (a lot on big cabs) @@ -621,13 +637,13 @@ extern "C" HRESULT DAPI CabCFinish( { // If we have a last error, use that, otherwise return the useless error hr = FAILED(pcd->hrLastError) ? pcd->hrLastError : E_FAIL; - ExitOnFailure(hr, "failed to flush FCI object Oper: 0x%x Type: 0x%x", pcd->erf.erfOper, pcd->erf.erfType); // TODO: can these be converted to HRESULTS? + CabcExitOnFailure(hr, "failed to flush FCI object Oper: 0x%x Type: 0x%x", pcd->erf.erfOper, pcd->erf.erfType); // TODO: can these be converted to HRESULTS? } if (pcd->fGoodCab && pcd->cDuplicates) { hr = UpdateDuplicateFiles(pcd); - ExitOnFailure(hr, "Failed to update duplicates in cabinet: %ls", pcd->wzCabinetPath); + CabcExitOnFailure(hr, "Failed to update duplicates in cabinet: %ls", pcd->wzCabinetPath); } LExit: @@ -697,8 +713,8 @@ static HRESULT CheckForDuplicateFile( HRESULT hr = S_OK; UINT er = ERROR_SUCCESS; - ExitOnNull(ppcf, hr, E_INVALIDARG, "No file structure sent while checking for duplicate file"); - ExitOnNull(ppmfHash, hr, E_INVALIDARG, "No file hash structure pointer sent while checking for duplicate file"); + CabcExitOnNull(ppcf, hr, E_INVALIDARG, "No file structure sent while checking for duplicate file"); + CabcExitOnNull(ppmfHash, hr, E_INVALIDARG, "No file hash structure pointer sent while checking for duplicate file"); *ppcf = NULL; // By default, we'll set our output to NULL @@ -712,7 +728,7 @@ static HRESULT CheckForDuplicateFile( { hr = S_OK; } - ExitOnFailure(hr, "Failed while searching for file in dictionary of previously added files"); + CabcExitOnFailure(hr, "Failed while searching for file in dictionary of previously added files"); for (i = 0; i < pcd->cFilePaths; ++i) { @@ -723,22 +739,22 @@ static HRESULT CheckForDuplicateFile( if (pcd->prgFiles[i].pmfHash == NULL) { pcd->prgFiles[i].pmfHash = (PMSIFILEHASHINFO)MemAlloc(sizeof(MSIFILEHASHINFO), FALSE); - ExitOnNull(pcd->prgFiles[i].pmfHash, hr, E_OUTOFMEMORY, "Failed to allocate memory for candidate duplicate file's MSI file hash"); + CabcExitOnNull(pcd->prgFiles[i].pmfHash, hr, E_OUTOFMEMORY, "Failed to allocate memory for candidate duplicate file's MSI file hash"); pcd->prgFiles[i].pmfHash->dwFileHashInfoSize = sizeof(MSIFILEHASHINFO); er = ::MsiGetFileHashW(pcd->prgFiles[i].pwzSourcePath, 0, pcd->prgFiles[i].pmfHash); - ExitOnWin32Error(er, hr, "Failed while getting MSI file hash of candidate duplicate file: %ls", pcd->prgFiles[i].pwzSourcePath); + CabcExitOnWin32Error(er, hr, "Failed while getting MSI file hash of candidate duplicate file: %ls", pcd->prgFiles[i].pwzSourcePath); } // If our own file hasn't yet been hashed, hash it if (NULL == *ppmfHash) { *ppmfHash = (PMSIFILEHASHINFO)MemAlloc(sizeof(MSIFILEHASHINFO), FALSE); - ExitOnNull(*ppmfHash, hr, E_OUTOFMEMORY, "Failed to allocate memory for file's MSI file hash"); + CabcExitOnNull(*ppmfHash, hr, E_OUTOFMEMORY, "Failed to allocate memory for file's MSI file hash"); (*ppmfHash)->dwFileHashInfoSize = sizeof(MSIFILEHASHINFO); er = ::MsiGetFileHashW(wzFileName, 0, *ppmfHash); - ExitOnWin32Error(er, hr, "Failed while getting MSI file hash of file: %ls", pcd->prgFiles[i].pwzSourcePath); + CabcExitOnWin32Error(er, hr, "Failed while getting MSI file hash of file: %ls", pcd->prgFiles[i].pwzSourcePath); } // If the two file hashes are both of the expected size, and they match, we've got a match, so return it! @@ -779,17 +795,17 @@ static HRESULT AddDuplicateFile( size_t cbDuplicates = 0; hr = ::SizeTMult(pcd->cMaxDuplicates, sizeof(CABC_DUPLICATEFILE), &cbDuplicates); - ExitOnFailure(hr, "Maximum allocation exceeded."); + CabcExitOnFailure(hr, "Maximum allocation exceeded."); if (pcd->cDuplicates) { pv = MemReAlloc(pcd->prgDuplicates, cbDuplicates, FALSE); - ExitOnNull(pv, hr, E_OUTOFMEMORY, "Failed to reallocate memory for duplicate file."); + CabcExitOnNull(pv, hr, E_OUTOFMEMORY, "Failed to reallocate memory for duplicate file."); } else { pv = MemAlloc(cbDuplicates, FALSE); - ExitOnNull(pv, hr, E_OUTOFMEMORY, "Failed to allocate memory for duplicate file."); + CabcExitOnNull(pv, hr, E_OUTOFMEMORY, "Failed to allocate memory for duplicate file."); } ZeroMemory(reinterpret_cast(pv) + (pcd->cDuplicates * sizeof(CABC_DUPLICATEFILE)), (pcd->cMaxDuplicates - pcd->cDuplicates) * sizeof(CABC_DUPLICATEFILE)); @@ -804,12 +820,12 @@ static HRESULT AddDuplicateFile( pcd->prgFiles[dwFileArrayIndex].fHasDuplicates = TRUE; // Mark original file as having duplicates hr = StrAllocString(&pcd->prgDuplicates[pcd->cDuplicates].pwzSourcePath, wzSourcePath, 0); - ExitOnFailure(hr, "Failed to copy duplicate file path: %ls", wzSourcePath); + CabcExitOnFailure(hr, "Failed to copy duplicate file path: %ls", wzSourcePath); if (wzToken && *wzToken) { hr = StrAllocString(&pcd->prgDuplicates[pcd->cDuplicates].pwzToken, wzToken, 0); - ExitOnFailure(hr, "Failed to copy duplicate file token: %ls", wzToken); + CabcExitOnFailure(hr, "Failed to copy duplicate file token: %ls", wzToken); } ++pcd->cDuplicates; @@ -839,10 +855,10 @@ static HRESULT AddNonDuplicateFile( size_t cbFilePaths = 0; hr = ::SizeTMult(pcd->cMaxFilePaths, sizeof(CABC_FILE), &cbFilePaths); - ExitOnFailure(hr, "Maximum allocation exceeded."); + CabcExitOnFailure(hr, "Maximum allocation exceeded."); pv = MemReAlloc(pcd->prgFiles, cbFilePaths, FALSE); - ExitOnNull(pv, hr, E_OUTOFMEMORY, "Failed to reallocate memory for file."); + CabcExitOnNull(pv, hr, E_OUTOFMEMORY, "Failed to reallocate memory for file."); ZeroMemory(reinterpret_cast(pv) + (pcd->cFilePaths * sizeof(CABC_FILE)), (pcd->cMaxFilePaths - pcd->cFilePaths) * sizeof(CABC_FILE)); @@ -859,7 +875,7 @@ static HRESULT AddNonDuplicateFile( if (pmfHash && sizeof(MSIFILEHASHINFO) == pmfHash->dwFileHashInfoSize) { pcf->pmfHash = (PMSIFILEHASHINFO)MemAlloc(sizeof(MSIFILEHASHINFO), FALSE); - ExitOnNull(pcf->pmfHash, hr, E_OUTOFMEMORY, "Failed to allocate memory for individual file's MSI file hash"); + CabcExitOnNull(pcf->pmfHash, hr, E_OUTOFMEMORY, "Failed to allocate memory for individual file's MSI file hash"); pcf->pmfHash->dwFileHashInfoSize = sizeof(MSIFILEHASHINFO); pcf->pmfHash->dwData[0] = pmfHash->dwData[0]; @@ -869,18 +885,18 @@ static HRESULT AddNonDuplicateFile( } hr = StrAllocString(&pcf->pwzSourcePath, wzFile, 0); - ExitOnFailure(hr, "Failed to copy file path: %ls", wzFile); + CabcExitOnFailure(hr, "Failed to copy file path: %ls", wzFile); if (wzToken && *wzToken) { hr = StrAllocString(&pcf->pwzToken, wzToken, 0); - ExitOnFailure(hr, "Failed to copy file token: %ls", wzToken); + CabcExitOnFailure(hr, "Failed to copy file token: %ls", wzToken); } ++pcd->cFilePaths; hr = DictAddValue(pcd->shDictHandle, pcf); - ExitOnFailure(hr, "Failed to add file to dictionary of added files"); + CabcExitOnFailure(hr, "Failed to add file to dictionary of added files"); LExit: ReleaseMem(pv); @@ -903,14 +919,14 @@ static HRESULT UpdateDuplicateFiles( hCabinet = ::CreateFileW(pcd->wzCabinetPath, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (INVALID_HANDLE_VALUE == hCabinet) { - ExitWithLastError(hr, "Failed to open cabinet: %ls", pcd->wzCabinetPath); + CabcExitWithLastError(hr, "Failed to open cabinet: %ls", pcd->wzCabinetPath); } // Shouldn't need more than 16 MB to get the whole cabinet header into memory so use that as // the upper bound for the memory map. if (!::GetFileSizeEx(hCabinet, &liCabinetSize)) { - ExitWithLastError(hr, "Failed to get size of cabinet: %ls", pcd->wzCabinetPath); + CabcExitWithLastError(hr, "Failed to get size of cabinet: %ls", pcd->wzCabinetPath); } if (0 == liCabinetSize.HighPart && liCabinetSize.LowPart < MAX_CABINET_HEADER_SIZE) @@ -926,11 +942,11 @@ static HRESULT UpdateDuplicateFiles( hCabinetMapping = ::CreateFileMappingW(hCabinet, NULL, PAGE_READWRITE | SEC_COMMIT, 0, cbCabinet, NULL); if (NULL == hCabinetMapping || INVALID_HANDLE_VALUE == hCabinetMapping) { - ExitWithLastError(hr, "Failed to memory map cabinet file: %ls", pcd->wzCabinetPath); + CabcExitWithLastError(hr, "Failed to memory map cabinet file: %ls", pcd->wzCabinetPath); } pv = ::MapViewOfFile(hCabinetMapping, FILE_MAP_WRITE, 0, 0, 0); - ExitOnNullWithLastError(pv, hr, "Failed to map view of cabinet file: %ls", pcd->wzCabinetPath); + CabcExitOnNullWithLastError(pv, hr, "Failed to map view of cabinet file: %ls", pcd->wzCabinetPath); pCabinetHeader = static_cast(pv); @@ -939,7 +955,7 @@ static HRESULT UpdateDuplicateFiles( const CABC_DUPLICATEFILE *pDuplicateFile = pcd->prgDuplicates + i; hr = DuplicateFile(pCabinetHeader, pcd, pDuplicateFile); - ExitOnFailure(hr, "Failed to find cabinet file items at index: %d and %d", pDuplicateFile->dwFileArrayIndex, pDuplicateFile->dwDuplicateCabFileIndex); + CabcExitOnFailure(hr, "Failed to find cabinet file items at index: %d and %d", pDuplicateFile->dwFileArrayIndex, pDuplicateFile->dwDuplicateCabFileIndex); } LExit: @@ -974,7 +990,7 @@ static HRESULT DuplicateFile( pDuplicate->dwDuplicateCabFileIndex <= pcd->prgFiles[pDuplicate->dwFileArrayIndex].dwCabFileIndex) { hr = E_UNEXPECTED; - ExitOnFailure(hr, "Unexpected duplicate file indices, header cFiles: %d, file index: %d, duplicate index: %d", pHeader->cFiles, pcd->prgFiles[pDuplicate->dwFileArrayIndex].dwCabFileIndex, pDuplicate->dwDuplicateCabFileIndex); + CabcExitOnFailure(hr, "Unexpected duplicate file indices, header cFiles: %d, file index: %d, duplicate index: %d", pHeader->cFiles, pcd->prgFiles[pDuplicate->dwFileArrayIndex].dwCabFileIndex, pDuplicate->dwDuplicateCabFileIndex); } // Step through each cabinet items until we get to the original @@ -1002,7 +1018,7 @@ static HRESULT DuplicateFile( if (0 != pDuplicateItem->cbFile) { hr = E_UNEXPECTED; - ExitOnFailure(hr, "Failed because duplicate file does not have a file size of zero: %d", pDuplicateItem->cbFile); + CabcExitOnFailure(hr, "Failed because duplicate file does not have a file size of zero: %d", pDuplicateItem->cbFile); } pDuplicateItem->cbFile = pOriginalItem->cbFile; @@ -1031,12 +1047,12 @@ static HRESULT UtcFileTimeToLocalDosDateTime( if (!::FileTimeToLocalFileTime(pFileTime, &ftLocal)) { - ExitWithLastError(hr, "Filed to convert file time to local file time."); + CabcExitWithLastError(hr, "Filed to convert file time to local file time."); } if (!::FileTimeToDosDateTime(&ftLocal, pDate, pTime)) { - ExitWithLastError(hr, "Filed to convert file time to DOS date time."); + CabcExitWithLastError(hr, "Filed to convert file time to DOS date time."); } LExit: @@ -1053,7 +1069,7 @@ static __callback int DIAMONDAPI CabCFilePlaced( __in_z PSTR szFile, __in long cbFile, __in BOOL fContinuation, - __out_bcount(CABC_HANDLE_BYTES) void *pv + __inout_bcount(CABC_HANDLE_BYTES) void *pv ) { UNREFERENCED_PARAMETER(pccab); @@ -1085,7 +1101,7 @@ static __callback INT_PTR DIAMONDAPI CabCOpen( __in int oflag, __in int pmode, __out int *err, - __out_bcount(CABC_HANDLE_BYTES) void *pv + __inout_bcount(CABC_HANDLE_BYTES) void *pv ) { CABC_DATA *pcd = reinterpret_cast(pv); @@ -1139,7 +1155,7 @@ static __callback INT_PTR DIAMONDAPI CabCOpen( if (INVALID_HANDLE_VALUE == reinterpret_cast(pFile)) { - ExitOnLastError(hr, "failed to open file: %s", pszFile); + CabcExitOnLastError(hr, "failed to open file: %s", pszFile); } LExit: @@ -1155,18 +1171,18 @@ static __callback UINT FAR DIAMONDAPI CabCRead( __out_bcount(cb) void FAR *memory, __in UINT cb, __out int *err, - __out_bcount(CABC_HANDLE_BYTES) void *pv + __inout_bcount(CABC_HANDLE_BYTES) void *pv ) { CABC_DATA *pcd = reinterpret_cast(pv); HRESULT hr = S_OK; DWORD cbRead = 0; - ExitOnNull(hf, *err, E_INVALIDARG, "Failed to read during cabinet extraction because no file handle was provided"); + CabcExitOnNull(hf, *err, E_INVALIDARG, "Failed to read during cabinet extraction because no file handle was provided"); if (!::ReadFile(reinterpret_cast(hf), memory, cb, &cbRead, NULL)) { *err = ::GetLastError(); - ExitOnLastError(hr, "failed to read during cabinet extraction"); + CabcExitOnLastError(hr, "failed to read during cabinet extraction"); } LExit: @@ -1184,18 +1200,18 @@ static __callback UINT FAR DIAMONDAPI CabCWrite( __in_bcount(cb) void FAR *memory, __in UINT cb, __out int *err, - __out_bcount(CABC_HANDLE_BYTES) void *pv + __inout_bcount(CABC_HANDLE_BYTES) void *pv ) { CABC_DATA *pcd = reinterpret_cast(pv); HRESULT hr = S_OK; DWORD cbWrite = 0; - ExitOnNull(hf, *err, E_INVALIDARG, "Failed to write during cabinet extraction because no file handle was provided"); + CabcExitOnNull(hf, *err, E_INVALIDARG, "Failed to write during cabinet extraction because no file handle was provided"); if (!::WriteFile(reinterpret_cast(hf), memory, cb, &cbWrite, NULL)) { *err = ::GetLastError(); - ExitOnLastError(hr, "failed to write during cabinet extraction"); + CabcExitOnLastError(hr, "failed to write during cabinet extraction"); } LExit: @@ -1211,7 +1227,7 @@ static __callback long FAR DIAMONDAPI CabCSeek( __in long dist, __in int seektype, __out int *err, - __out_bcount(CABC_HANDLE_BYTES) void *pv + __inout_bcount(CABC_HANDLE_BYTES) void *pv ) { CABC_DATA *pcd = reinterpret_cast(pv); @@ -1233,7 +1249,7 @@ static __callback long FAR DIAMONDAPI CabCSeek( default : dwMoveMethod = 0; hr = E_UNEXPECTED; - ExitOnFailure(hr, "unexpected seektype in FCISeek(): %d", seektype); + CabcExitOnFailure(hr, "unexpected seektype in FCISeek(): %d", seektype); } // SetFilePointer returns -1 if it fails (this will cause FDI to quit with an FDIERROR_USER_ABORT error. @@ -1243,7 +1259,7 @@ static __callback long FAR DIAMONDAPI CabCSeek( if (DWORD_MAX == lMove) { *err = ::GetLastError(); - ExitOnLastError(hr, "failed to move file pointer %d bytes", dist); + CabcExitOnLastError(hr, "failed to move file pointer %d bytes", dist); } LExit: @@ -1259,7 +1275,7 @@ LExit: static __callback int FAR DIAMONDAPI CabCClose( __in INT_PTR hf, __out int *err, - __out_bcount(CABC_HANDLE_BYTES) void *pv + __inout_bcount(CABC_HANDLE_BYTES) void *pv ) { CABC_DATA *pcd = reinterpret_cast(pv); @@ -1268,7 +1284,7 @@ static __callback int FAR DIAMONDAPI CabCClose( if (!::CloseHandle(reinterpret_cast(hf))) { *err = ::GetLastError(); - ExitOnLastError(hr, "failed to close file during cabinet extraction"); + CabcExitOnLastError(hr, "failed to close file during cabinet extraction"); } LExit: @@ -1283,7 +1299,7 @@ LExit: static __callback int DIAMONDAPI CabCDelete( __in_z PSTR szFile, __out int *err, - __out_bcount(CABC_HANDLE_BYTES) void *pv + __inout_bcount(CABC_HANDLE_BYTES) void *pv ) { UNREFERENCED_PARAMETER(err); @@ -1302,7 +1318,7 @@ __success(return != FALSE) static __callback BOOL DIAMONDAPI CabCGetTempFile( __out_bcount_z(cbFile) char *szFile, __in int cbFile, - __out_bcount(CABC_HANDLE_BYTES) void *pv + __inout_bcount(CABC_HANDLE_BYTES) void *pv ) { CABC_DATA *pcd = reinterpret_cast(pv); @@ -1316,7 +1332,7 @@ static __callback BOOL DIAMONDAPI CabCGetTempFile( if (MAX_PATH < ::GetTempPathA(cchTempPath, szTempPath)) { - ExitWithLastError(hr, "Failed to get temp path during cabinet creation."); + CabcExitWithLastError(hr, "Failed to get temp path during cabinet creation."); } for (DWORD i = 0; i < DWORD_MAX; ++i) @@ -1324,7 +1340,7 @@ static __callback BOOL DIAMONDAPI CabCGetTempFile( LONG dwTempIndex = ::InterlockedIncrement(reinterpret_cast(&dwIndex)); hr = ::StringCbPrintfA(szFile, cbFile, "%s\\%08x.%03x", szTempPath, dwTempIndex, dwProcessId); - ExitOnFailure(hr, "failed to format log file path."); + CabcExitOnFailure(hr, "failed to format log file path."); hTempFile = ::CreateFileA(szFile, 0, FILE_SHARE_DELETE, NULL, CREATE_NEW, FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE, NULL); if (INVALID_HANDLE_VALUE != hTempFile) @@ -1338,7 +1354,7 @@ static __callback BOOL DIAMONDAPI CabCGetTempFile( hr = E_FAIL; // this file was taken so be pessimistic and assume we're not going to find one. } } - ExitOnFailure(hr, "failed to find temporary file."); + CabcExitOnFailure(hr, "failed to find temporary file."); LExit: ReleaseFileHandle(hTempFile); @@ -1377,7 +1393,7 @@ static __callback BOOL DIAMONDAPI CabCGetNextCabinet( len -= 4; // remove Extention ".cab" of 8.3 Format } hr = ::StringCchCatNW(pcd->wzFirstCabinetName, countof(pcd->wzFirstCabinetName), pwzCabinetName, len); - ExitOnFailure(hr, "Failed to remove extension to create next Cabinet File Name"); + CabcExitOnFailure(hr, "Failed to remove extension to create next Cabinet File Name"); } const int nAlphabets = 26; // Number of Alphabets from a to z @@ -1385,9 +1401,9 @@ static __callback BOOL DIAMONDAPI CabCGetNextCabinet( { // Construct next cab names like cab1a.cab, cab1b.cab, cab1c.cab, ........ hr = ::StringCchPrintfA(pccab->szCab, sizeof(pccab->szCab), "%ls%c.cab", pcd->wzFirstCabinetName, char(((int)('a') - 1) + pccab->iCab)); - ExitOnFailure(hr, "Failed to create next Cabinet File Name"); + CabcExitOnFailure(hr, "Failed to create next Cabinet File Name"); hr = ::StringCchPrintfW(wzNewCabName, countof(wzNewCabName), L"%ls%c.cab", pcd->wzFirstCabinetName, WCHAR(((int)('a') - 1) + pccab->iCab)); - ExitOnFailure(hr, "Failed to create next Cabinet File Name"); + CabcExitOnFailure(hr, "Failed to create next Cabinet File Name"); } else if (pccab->iCab <= nAlphabets*nAlphabets) { @@ -1401,14 +1417,14 @@ static __callback BOOL DIAMONDAPI CabCGetNextCabinet( char1--; // First Char must be decremented by 1 } hr = ::StringCchPrintfA(pccab->szCab, sizeof(pccab->szCab), "%ls%c%c.cab", pcd->wzFirstCabinetName, char(((int)('a') - 1) + char1), char(((int)('a') - 1) + char2)); - ExitOnFailure(hr, "Failed to create next Cabinet File Name"); + CabcExitOnFailure(hr, "Failed to create next Cabinet File Name"); hr = ::StringCchPrintfW(wzNewCabName, countof(wzNewCabName), L"%ls%c%c.cab", pcd->wzFirstCabinetName, WCHAR(((int)('a') - 1) + char1), WCHAR(((int)('a') - 1) + char2)); - ExitOnFailure(hr, "Failed to create next Cabinet File Name"); + CabcExitOnFailure(hr, "Failed to create next Cabinet File Name"); } else { hr = DISP_E_BADINDEX; // Value 0x8002000B stands for Invalid index. - ExitOnFailure(hr, "Cannot Split Cabinet more than 26*26 = 676 times. Failed to create next Cabinet File Name"); + CabcExitOnFailure(hr, "Cannot Split Cabinet more than 26*26 = 676 times. Failed to create next Cabinet File Name"); } // Callback from PFNFCIGETNEXTCABINET CabCGetNextCabinet method @@ -1478,7 +1494,7 @@ static __callback INT_PTR DIAMONDAPI CabCGetOpenInfo( if (!::GetFileAttributesExW(pFileInfo->wzSourcePath, GetFileExInfoStandard, &fad)) { - ExitWithLastError(hr, "Failed to get file attributes on '%s'.", pFileInfo->wzSourcePath); + CabcExitWithLastError(hr, "Failed to get file attributes on '%ls'.", pFileInfo->wzSourcePath); } // Set the attributes but only allow the few attributes that CAB supports. @@ -1492,7 +1508,7 @@ static __callback INT_PTR DIAMONDAPI CabCGetOpenInfo( // found. This would create further problems if the file was written to the CAB without this value. Windows // Installer would then fail to extract the file. hr = UtcFileTimeToLocalDosDateTime(&fad.ftCreationTime, pdate, ptime); - ExitOnFailure(hr, "Filed to read a valid file time stucture on file '%s'.", pszName); + CabcExitOnFailure(hr, "Filed to read a valid file time stucture on file '%s'.", pszName); } iResult = CabCOpen(pszFilePlusMagic, _O_BINARY|_O_RDONLY, 0, err, pv); @@ -1512,7 +1528,7 @@ static __callback long DIAMONDAPI CabCStatus( __in UINT ui, __in ULONG cb1, __in ULONG cb2, - __out_bcount(CABC_HANDLE_BYTES) void *pv + __inout_bcount(CABC_HANDLE_BYTES) void *pv ) { UNREFERENCED_PARAMETER(ui); diff --git a/src/dutil/cabutil.cpp b/src/dutil/cabutil.cpp index e0efb717..4a6f7b7b 100644 --- a/src/dutil/cabutil.cpp +++ b/src/dutil/cabutil.cpp @@ -2,6 +2,22 @@ #include "precomp.h" + +// Exit macros +#define CabExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_CABUTIL, x, s, __VA_ARGS__) +#define CabExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_CABUTIL, x, s, __VA_ARGS__) +#define CabExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_CABUTIL, x, s, __VA_ARGS__) +#define CabExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_CABUTIL, x, s, __VA_ARGS__) +#define CabExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_CABUTIL, x, s, __VA_ARGS__) +#define CabExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_CABUTIL, x, s, __VA_ARGS__) +#define CabExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_CABUTIL, p, x, e, s, __VA_ARGS__) +#define CabExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_CABUTIL, p, x, s, __VA_ARGS__) +#define CabExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_CABUTIL, p, x, e, s, __VA_ARGS__) +#define CabExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_CABUTIL, p, x, s, __VA_ARGS__) +#define CabExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_CABUTIL, e, x, s, __VA_ARGS__) +#define CabExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_CABUTIL, g, x, s, __VA_ARGS__) + + // external prototypes typedef BOOL (FAR DIAMONDAPI *PFNFDIDESTROY)(VOID*); typedef HFDI (FAR DIAMONDAPI *PFNFDICREATE)(PFNALLOC, PFNFREE, PFNOPEN, PFNREAD, PFNWRITE, PFNCLOSE, PFNSEEK, int, PERF); @@ -59,20 +75,20 @@ inline HRESULT LoadCabinetDll() if (!vhCabinetDll) { hr = LoadSystemLibrary(L"cabinet.dll", &vhCabinetDll); - ExitOnFailure(hr, "failed to load cabinet.dll"); + CabExitOnFailure(hr, "failed to load cabinet.dll"); // retrieve all address functions vpfnFDICreate = reinterpret_cast(::GetProcAddress(vhCabinetDll, "FDICreate")); - ExitOnNullWithLastError(vpfnFDICreate, hr, "failed to import FDICreate from CABINET.DLL"); + CabExitOnNullWithLastError(vpfnFDICreate, hr, "failed to import FDICreate from CABINET.DLL"); vpfnFDICopy = reinterpret_cast(::GetProcAddress(vhCabinetDll, "FDICopy")); - ExitOnNullWithLastError(vpfnFDICopy, hr, "failed to import FDICopy from CABINET.DLL"); + CabExitOnNullWithLastError(vpfnFDICopy, hr, "failed to import FDICopy from CABINET.DLL"); vpfnFDIIsCabinet = reinterpret_cast(::GetProcAddress(vhCabinetDll, "FDIIsCabinet")); - ExitOnNullWithLastError(vpfnFDIIsCabinet, hr, "failed to import FDIIsCabinetfrom CABINET.DLL"); + CabExitOnNullWithLastError(vpfnFDIIsCabinet, hr, "failed to import FDIIsCabinetfrom CABINET.DLL"); vpfnFDIDestroy = reinterpret_cast(::GetProcAddress(vhCabinetDll, "FDIDestroy")); - ExitOnNullWithLastError(vpfnFDIDestroy, hr, "failed to import FDIDestroyfrom CABINET.DLL"); + CabExitOnNullWithLastError(vpfnFDIDestroy, hr, "failed to import FDIDestroyfrom CABINET.DLL"); vhfdi = vpfnFDICreate(CabExtractAlloc, CabExtractFree, CabExtractOpen, CabExtractRead, CabExtractWrite, CabExtractClose, CabExtractSeek, cpuUNKNOWN, &verf); - ExitOnNull(vhfdi, hr, E_FAIL, "failed to initialize cabinet.dll"); + CabExitOnNull(vhfdi, hr, E_FAIL, "failed to initialize cabinet.dll"); } LExit: @@ -99,7 +115,7 @@ extern "C" HRESULT DAPI CabInitialize( if (!fDelayLoad) { hr = LoadCabinetDll(); - ExitOnFailure(hr, "failed to load CABINET.DLL"); + CabExitOnFailure(hr, "failed to load CABINET.DLL"); } LExit: @@ -143,8 +159,8 @@ extern "C" void DAPI CabUninitialize( in the cabinet ********************************************************************/ extern "C" HRESULT DAPI CabEnumerate( - __in LPCWSTR wzCabinet, - __in LPCWSTR wzEnumerateFile, + __in_z LPCWSTR wzCabinet, + __in_z LPCWSTR wzEnumerateFile, __in STDCALL_PFNFDINOTIFY pfnNotify, __in DWORD64 dw64EmbeddedOffset ) @@ -161,9 +177,9 @@ extern "C" HRESULT DAPI CabEnumerate( if pfnBeginFile is NULL pfnEndFile must be NULL and vice versa ********************************************************************/ extern "C" HRESULT DAPI CabExtract( - __in LPCWSTR wzCabinet, - __in LPCWSTR wzExtractFile, - __in LPCWSTR wzExtractDir, + __in_z LPCWSTR wzCabinet, + __in_z LPCWSTR wzExtractFile, + __in_z LPCWSTR wzExtractDir, __in_opt CAB_CALLBACK_PROGRESS pfnProgress, __in_opt LPVOID pvContext, __in DWORD64 dw64EmbeddedOffset @@ -238,21 +254,21 @@ static HRESULT DAPI CabOperation( if (!vhfdi) { hr = LoadCabinetDll(); - ExitOnFailure(hr, "failed to load CABINET.DLL"); + CabExitOnFailure(hr, "failed to load CABINET.DLL"); } hr = StrAllocString(&sczCabinet, wzCabinet, 0); - ExitOnFailure(hr, "Failed to make copy of cabinet name:%ls", wzCabinet); + CabExitOnFailure(hr, "Failed to make copy of cabinet name:%ls", wzCabinet); // // split the cabinet full path into directory and filename and convert to multi-byte (ick!) // pwz = FileFromPath(sczCabinet); - ExitOnNull(pwz, hr, E_INVALIDARG, "failed to process cabinet path: %ls", wzCabinet); + CabExitOnNull(pwz, hr, E_INVALIDARG, "failed to process cabinet path: %ls", wzCabinet); if (!::WideCharToMultiByte(CP_UTF8, 0, pwz, -1, szCabFile, countof(szCabFile), NULL, NULL)) { - ExitWithLastError(hr, "failed to convert cabinet filename to ASCII: %ls", pwz); + CabExitWithLastError(hr, "failed to convert cabinet filename to ASCII: %ls", pwz); } *pwz = '\0'; @@ -261,13 +277,13 @@ static HRESULT DAPI CabOperation( if (wzCabinet == pwz) { hr = ::StringCchCopyA(szCabDirectory, countof(szCabDirectory), ".\\"); - ExitOnFailure(hr, "Failed to copy relative current directory as cabinet directory."); + CabExitOnFailure(hr, "Failed to copy relative current directory as cabinet directory."); } else { if (!::WideCharToMultiByte(CP_UTF8, 0, sczCabinet, -1, szCabDirectory, countof(szCabDirectory), NULL, NULL)) { - ExitWithLastError(hr, "failed to convert cabinet directory to ASCII: %ls", sczCabinet); + CabExitWithLastError(hr, "failed to convert cabinet directory to ASCII: %ls", sczCabinet); } } @@ -295,7 +311,7 @@ static HRESULT DAPI CabOperation( fResult = vpfnFDICopy(vhfdi, szCabFile, szCabDirectory, 0, pfnFdiNotify, NULL, static_cast(&ccs)); if (!fResult && !ccs.fStopExtracting) // if something went wrong and it wasn't us just stopping the extraction, then return a failure { - ExitWithLastError(hr, "failed to extract cabinet file: %ls", sczCabinet); + CabExitWithLastError(hr, "failed to extract cabinet file: %ls", sczCabinet); } LExit: @@ -331,22 +347,22 @@ static __callback INT_PTR FAR DIAMONDAPI CabExtractOpen(__in_z PSTR pszFile, __i if ((oflag != (/*_O_BINARY*/ 0x8000 | /*_O_RDONLY*/ 0x0000)) || (pmode != (_S_IREAD | _S_IWRITE))) { hr = E_OUTOFMEMORY; - ExitOnFailure(hr, "FDI asked for a scratch file to be created, which is unsupported"); + CabExitOnFailure(hr, "FDI asked for a scratch file to be created, which is unsupported"); } hr = StrAllocStringAnsi(&sczCabFile, pszFile, 0, CP_UTF8); - ExitOnFailure(hr, "Failed to convert UTF8 cab file name to wide character string"); + CabExitOnFailure(hr, "Failed to convert UTF8 cab file name to wide character string"); pFile = reinterpret_cast(::CreateFileW(sczCabFile, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)); if (INVALID_HANDLE_VALUE == reinterpret_cast(pFile)) { - ExitWithLastError(hr, "failed to open file: %ls", sczCabFile); + CabExitWithLastError(hr, "failed to open file: %ls", sczCabFile); } if (vdw64EmbeddedOffset) { hr = CabExtractSeek(pFile, 0, 0); - ExitOnFailure(hr, "Failed to seek to embedded offset %I64d", vdw64EmbeddedOffset); + CabExitOnFailure(hr, "Failed to seek to embedded offset %I64d", vdw64EmbeddedOffset); } LExit: @@ -361,10 +377,10 @@ static __callback UINT FAR DIAMONDAPI CabExtractRead(__in INT_PTR hf, __out void HRESULT hr = S_OK; DWORD cbRead = 0; - ExitOnNull(hf, hr, E_INVALIDARG, "Failed to read file during cabinet extraction - no file given to read"); + CabExitOnNull(hf, hr, E_INVALIDARG, "Failed to read file during cabinet extraction - no file given to read"); if (!::ReadFile(reinterpret_cast(hf), pv, cb, &cbRead, NULL)) { - ExitWithLastError(hr, "failed to read during cabinet extraction"); + CabExitWithLastError(hr, "failed to read during cabinet extraction"); } LExit: @@ -377,10 +393,10 @@ static __callback UINT FAR DIAMONDAPI CabExtractWrite(__in INT_PTR hf, __in void HRESULT hr = S_OK; DWORD cbWrite = 0; - ExitOnNull(hf, hr, E_INVALIDARG, "Failed to write file during cabinet extraction - no file given to write"); + CabExitOnNull(hf, hr, E_INVALIDARG, "Failed to write file during cabinet extraction - no file given to write"); if (!::WriteFile(reinterpret_cast(hf), pv, cb, &cbWrite, NULL)) { - ExitWithLastError(hr, "failed to write during cabinet extraction"); + CabExitWithLastError(hr, "failed to write during cabinet extraction"); } LExit: @@ -409,7 +425,7 @@ static __callback long FAR DIAMONDAPI CabExtractSeek(__in INT_PTR hf, __in long default : dwMoveMethod = 0; hr = E_UNEXPECTED; - ExitOnFailure(hr, "unexpected seektype in FDISeek(): %d", seektype); + CabExitOnFailure(hr, "unexpected seektype in FDISeek(): %d", seektype); } // SetFilePointer returns -1 if it fails (this will cause FDI to quit with an FDIERROR_USER_ABORT error. @@ -417,7 +433,7 @@ static __callback long FAR DIAMONDAPI CabExtractSeek(__in INT_PTR hf, __in long lMove = ::SetFilePointer(reinterpret_cast(hf), dist, NULL, dwMoveMethod); if (0xFFFFFFFF == lMove) { - ExitWithLastError(hr, "failed to move file pointer %d bytes", dist); + CabExitWithLastError(hr, "failed to move file pointer %d bytes", dist); } LExit: @@ -431,7 +447,7 @@ static __callback int FAR DIAMONDAPI CabExtractClose(__in INT_PTR hf) if (!::CloseHandle(reinterpret_cast(hf))) { - ExitWithLastError(hr, "failed to close file during cabinet extraction"); + CabExitWithLastError(hr, "failed to close file during cabinet extraction"); } LExit: @@ -454,8 +470,8 @@ static __callback INT_PTR DIAMONDAPI CabExtractCallback(__in FDINOTIFICATIONTYPE switch (iNotification) { case fdintCOPY_FILE: // begin extracting a resource from cabinet - ExitOnNull(pFDINotify->psz1, hr, E_INVALIDARG, "No cabinet file ID given to convert"); - ExitOnNull(pccs, hr, E_INVALIDARG, "Failed to call cabextract callback, because no callback struct was provided"); + CabExitOnNull(pFDINotify->psz1, hr, E_INVALIDARG, "No cabinet file ID given to convert"); + CabExitOnNull(pccs, hr, E_INVALIDARG, "Failed to call cabextract callback, because no callback struct was provided"); if (pccs->fStopExtracting) { @@ -466,7 +482,7 @@ static __callback INT_PTR DIAMONDAPI CabExtractCallback(__in FDINOTIFICATIONTYPE sz = static_cast(pFDINotify->psz1); if (!::MultiByteToWideChar(CP_ACP, 0, sz, -1, wz, countof(wz))) { - ExitWithLastError(hr, "failed to convert cabinet file id to unicode: %s", sz); + CabExitWithLastError(hr, "failed to convert cabinet file id to unicode: %s", sz); } if (pccs->pfnProgress) @@ -484,21 +500,21 @@ static __callback INT_PTR DIAMONDAPI CabExtractCallback(__in FDINOTIFICATIONTYPE FILETIME ftLocal; if (!::DosDateTimeToFileTime(pFDINotify->date, pFDINotify->time, &ftLocal)) { - ExitWithLastError(hr, "failed to get time for resource: %ls", wz); + CabExitWithLastError(hr, "failed to get time for resource: %ls", wz); } ::LocalFileTimeToFileTime(&ftLocal, &ft); WCHAR wzPath[MAX_PATH]; hr = ::StringCchCopyW(wzPath, countof(wzPath), pccs->pwzExtractDir); - ExitOnFailure(hr, "failed to copy in extract directory: %ls for file: %ls", pccs->pwzExtractDir, wz); + CabExitOnFailure(hr, "failed to copy in extract directory: %ls for file: %ls", pccs->pwzExtractDir, wz); hr = ::StringCchCatW(wzPath, countof(wzPath), wz); - ExitOnFailure(hr, "failed to concat onto path: %ls file: %ls", wzPath, wz); + CabExitOnFailure(hr, "failed to concat onto path: %ls file: %ls", wzPath, wz); ipResult = reinterpret_cast(::CreateFileW(wzPath, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL)); if (INVALID_HANDLE_VALUE == reinterpret_cast(ipResult)) { - ExitWithLastError(hr, "failed to create file: %s", wzPath); + CabExitWithLastError(hr, "failed to create file: %ls", wzPath); } ::SetFileTime(reinterpret_cast(ipResult), &ft, &ft, &ft); // try to set the file time (who cares if it fails) @@ -520,15 +536,15 @@ static __callback INT_PTR DIAMONDAPI CabExtractCallback(__in FDINOTIFICATIONTYPE break; case fdintCLOSE_FILE_INFO: // resource extraction complete Assert(pFDINotify->hf && pFDINotify->psz1); - ExitOnNull(pccs, hr, E_INVALIDARG, "Failed to call cabextract callback, because no callback struct was provided"); + CabExitOnNull(pccs, hr, E_INVALIDARG, "Failed to call cabextract callback, because no callback struct was provided"); // convert params to useful variables sz = static_cast(pFDINotify->psz1); - ExitOnNull(sz, hr, E_INVALIDARG, "Failed to convert cabinet file id, because no cabinet file id was provided"); + CabExitOnNull(sz, hr, E_INVALIDARG, "Failed to convert cabinet file id, because no cabinet file id was provided"); if (!::MultiByteToWideChar(CP_ACP, 0, sz, -1, wz, countof(wz))) { - ExitWithLastError(hr, "failed to convert cabinet file id to unicode: %s", sz); + CabExitWithLastError(hr, "failed to convert cabinet file id to unicode: %s", sz); } if (NULL != pFDINotify->hf) // just close the file diff --git a/src/dutil/certutil.cpp b/src/dutil/certutil.cpp index 9c0ee256..69897b9e 100644 --- a/src/dutil/certutil.cpp +++ b/src/dutil/certutil.cpp @@ -2,6 +2,21 @@ #include "precomp.h" + +// Exit macros +#define CertExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_CERTUTIL, x, s, __VA_ARGS__) +#define CertExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_CERTUTIL, x, s, __VA_ARGS__) +#define CertExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_CERTUTIL, x, s, __VA_ARGS__) +#define CertExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_CERTUTIL, x, s, __VA_ARGS__) +#define CertExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_CERTUTIL, x, s, __VA_ARGS__) +#define CertExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_CERTUTIL, x, s, __VA_ARGS__) +#define CertExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_CERTUTIL, p, x, e, s, __VA_ARGS__) +#define CertExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_CERTUTIL, p, x, s, __VA_ARGS__) +#define CertExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_CERTUTIL, p, x, e, s, __VA_ARGS__) +#define CertExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_CERTUTIL, p, x, s, __VA_ARGS__) +#define CertExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_CERTUTIL, e, x, s, __VA_ARGS__) +#define CertExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_CERTUTIL, g, x, s, __VA_ARGS__) + /******************************************************************** CertReadProperty - reads a property from the certificate. @@ -20,15 +35,15 @@ extern "C" HRESULT DAPI CertReadProperty( if (!::CertGetCertificateContextProperty(pCertContext, dwProperty, NULL, &cb)) { - ExitWithLastError(hr, "Failed to get size of certificate property."); + CertExitWithLastError(hr, "Failed to get size of certificate property."); } pv = MemAlloc(cb, TRUE); - ExitOnNull(pv, hr, E_OUTOFMEMORY, "Failed to allocate memory for certificate property."); + CertExitOnNull(pv, hr, E_OUTOFMEMORY, "Failed to allocate memory for certificate property."); if (!::CertGetCertificateContextProperty(pCertContext, dwProperty, pv, &cb)) { - ExitWithLastError(hr, "Failed to get certificate property."); + CertExitWithLastError(hr, "Failed to get certificate property."); } *ppvValue = pv; @@ -70,11 +85,11 @@ extern "C" HRESULT DAPI CertGetAuthenticodeSigningTimestamp( if (!pBlob) { hr = TRUST_E_FAIL; - ExitOnFailure(hr, "Failed to find countersigner in signer information."); + CertExitOnFailure(hr, "Failed to find countersigner in signer information."); } hr = CrypDecodeObject(PKCS7_SIGNER_INFO, pBlob->pbData, pBlob->cbData, 0, reinterpret_cast(&pCounterSignerInfo), NULL); - ExitOnFailure(hr, "Failed to decode countersigner information."); + CertExitOnFailure(hr, "Failed to decode countersigner information."); pBlob = NULL; // reset the blob before searching for the signing time. @@ -91,12 +106,12 @@ extern "C" HRESULT DAPI CertGetAuthenticodeSigningTimestamp( if (!pBlob) { hr = TRUST_E_FAIL; - ExitOnFailure(hr, "Failed to find signing time in countersigner information."); + CertExitOnFailure(hr, "Failed to find signing time in countersigner information."); } if (!::CryptDecodeObject(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, szOID_RSA_signingTime, pBlob->pbData, pBlob->cbData, 0, pftSigningTimestamp, &cbSigningTimestamp)) { - ExitWithLastError(hr, "Failed to decode countersigner signing timestamp."); + CertExitWithLastError(hr, "Failed to decode countersigner signing timestamp."); } LExit: @@ -124,10 +139,10 @@ extern "C" HRESULT DAPI GetCryptProvFromCert( GETCRYPTPROVFROMCERTPTR pGetCryptProvFromCert = NULL; hr = LoadSystemLibrary(L"MsSign32.dll", &hMsSign32); - ExitOnFailure(hr, "Failed to get handle to MsSign32.dll"); + CertExitOnFailure(hr, "Failed to get handle to MsSign32.dll"); pGetCryptProvFromCert = (GETCRYPTPROVFROMCERTPTR)::GetProcAddress(hMsSign32, "GetCryptProvFromCert"); - ExitOnNullWithLastError(hMsSign32, hr, "Failed to get handle to MsSign32.dll"); + CertExitOnNullWithLastError(hMsSign32, hr, "Failed to get handle to MsSign32.dll"); if (!pGetCryptProvFromCert(hwnd, pCert, @@ -138,7 +153,7 @@ extern "C" HRESULT DAPI GetCryptProvFromCert( ppwszProviderName, pdwProviderType)) { - ExitWithLastError(hr, "Failed to get CSP from cert."); + CertExitWithLastError(hr, "Failed to get CSP from cert."); } LExit: return hr; @@ -159,10 +174,10 @@ extern "C" HRESULT DAPI FreeCryptProvFromCert( FREECRYPTPROVFROMCERT pFreeCryptProvFromCert = NULL; hr = LoadSystemLibrary(L"MsSign32.dll", &hMsSign32); - ExitOnFailure(hr, "Failed to get handle to MsSign32.dll"); + CertExitOnFailure(hr, "Failed to get handle to MsSign32.dll"); pFreeCryptProvFromCert = (FREECRYPTPROVFROMCERT)::GetProcAddress(hMsSign32, "FreeCryptProvFromCert"); - ExitOnNullWithLastError(hMsSign32, hr, "Failed to get handle to MsSign32.dll"); + CertExitOnNullWithLastError(hMsSign32, hr, "Failed to get handle to MsSign32.dll"); pFreeCryptProvFromCert(fAcquired, hProv, pwszCapiProvider, dwProviderType, pwszTmpContainer); LExit: @@ -185,12 +200,12 @@ extern "C" HRESULT DAPI GetProvSecurityDesc( &ulSize, DACL_SECURITY_INFORMATION)) { - ExitWithLastError(hr, "Error getting security descriptor size for CSP."); + CertExitWithLastError(hr, "Error getting security descriptor size for CSP."); } // Allocate the memory for the security descriptor. pSecurity = static_cast(MemAlloc(ulSize, TRUE)); - ExitOnNullWithLastError(pSecurity, hr, "Error allocating memory for CSP DACL"); + CertExitOnNullWithLastError(pSecurity, hr, "Error allocating memory for CSP DACL"); // Get the security descriptor. if (!::CryptGetProvParam( @@ -201,7 +216,7 @@ extern "C" HRESULT DAPI GetProvSecurityDesc( DACL_SECURITY_INFORMATION)) { MemFree(pSecurity); - ExitWithLastError(hr, "Error getting security descriptor for CSP."); + CertExitWithLastError(hr, "Error getting security descriptor for CSP."); } *ppSecurity = pSecurity; @@ -223,7 +238,7 @@ extern "C" HRESULT DAPI SetProvSecurityDesc( (BYTE*)pSecurity, DACL_SECURITY_INFORMATION)) { - ExitWithLastError(hr, "Error setting security descriptor for CSP."); + CertExitWithLastError(hr, "Error setting security descriptor for CSP."); } LExit: return hr; @@ -278,12 +293,12 @@ extern "C" HRESULT DAPI CertInstallSingleCertificate( if (!::CertSetCertificateContextProperty(pCertContext, CERT_FRIENDLY_NAME_PROP_ID, 0, &blob)) { - ExitWithLastError(hr, "Failed to set the friendly name of the certificate: %ls", wzName); + CertExitWithLastError(hr, "Failed to set the friendly name of the certificate: %ls", wzName); } if (!::CertAddCertificateContextToStore(hStore, pCertContext, CERT_STORE_ADD_REPLACE_EXISTING, NULL)) { - ExitWithLastError(hr, "Failed to add certificate to the store."); + CertExitWithLastError(hr, "Failed to add certificate to the store."); } // if the certificate has a private key, grant Administrators access @@ -293,16 +308,16 @@ extern "C" HRESULT DAPI CertInstallSingleCertificate( { // We added a CSP key hr = GetCryptProvFromCert(NULL, pCertContext, &hCsp, &dwKeySpec, &fAcquired, &pwszTmpContainer, &pwszProviderName, &dwProviderType); - ExitOnFailure(hr, "Failed to get handle to CSP"); + CertExitOnFailure(hr, "Failed to get handle to CSP"); hr = GetProvSecurityDesc(hCsp, &pSecurity); - ExitOnFailure(hr, "Failed to get security descriptor of CSP"); + CertExitOnFailure(hr, "Failed to get security descriptor of CSP"); hr = AclAddAdminToSecurityDescriptor(pSecurity, &pSecurityNew); - ExitOnFailure(hr, "Failed to create new security descriptor"); + CertExitOnFailure(hr, "Failed to create new security descriptor"); hr = SetProvSecurityDesc(hCsp, pSecurityNew); - ExitOnFailure(hr, "Failed to set Admin ACL on CSP"); + CertExitOnFailure(hr, "Failed to set Admin ACL on CSP"); } if (CERT_NCRYPT_KEY_SPEC == dwKeySpec) diff --git a/src/dutil/conutil.cpp b/src/dutil/conutil.cpp index 4c820a1c..33e1b59a 100644 --- a/src/dutil/conutil.cpp +++ b/src/dutil/conutil.cpp @@ -3,6 +3,21 @@ #include "precomp.h" +// Exit macros +#define ConExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_CONUTIL, x, s, __VA_ARGS__) +#define ConExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_CONUTIL, x, s, __VA_ARGS__) +#define ConExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_CONUTIL, x, s, __VA_ARGS__) +#define ConExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_CONUTIL, x, s, __VA_ARGS__) +#define ConExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_CONUTIL, x, s, __VA_ARGS__) +#define ConExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_CONUTIL, x, s, __VA_ARGS__) +#define ConExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_CONUTIL, p, x, e, s, __VA_ARGS__) +#define ConExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_CONUTIL, p, x, s, __VA_ARGS__) +#define ConExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_CONUTIL, p, x, e, s, __VA_ARGS__) +#define ConExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_CONUTIL, p, x, s, __VA_ARGS__) +#define ConExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_CONUTIL, e, x, s, __VA_ARGS__) +#define ConExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_CONUTIL, g, x, s, __VA_ARGS__) + + static HANDLE vhStdIn = INVALID_HANDLE_VALUE; static HANDLE vhStdOut = INVALID_HANDLE_VALUE; static BOOL vfConsoleIn = FALSE; @@ -19,13 +34,13 @@ extern "C" HRESULT DAPI ConsoleInitialize() vhStdIn = ::GetStdHandle(STD_INPUT_HANDLE); if (INVALID_HANDLE_VALUE == vhStdIn) { - ExitOnLastError(hr, "failed to open stdin"); + ConExitOnLastError(hr, "failed to open stdin"); } vhStdOut = ::GetStdHandle(STD_OUTPUT_HANDLE); if (INVALID_HANDLE_VALUE == vhStdOut) { - ExitOnLastError(hr, "failed to open stdout"); + ConExitOnLastError(hr, "failed to open stdout"); } // check if we have a std in on the console @@ -43,7 +58,7 @@ extern "C" HRESULT DAPI ConsoleInitialize() } else { - ExitOnWin32Error(er, hr, "failed to get input console screen buffer info"); + ConExitOnWin32Error(er, hr, "failed to get input console screen buffer info"); } } @@ -62,7 +77,7 @@ extern "C" HRESULT DAPI ConsoleInitialize() } else { - ExitOnWin32Error(er, hr, "failed to get output console screen buffer info"); + ConExitOnWin32Error(er, hr, "failed to get output console screen buffer info"); } } @@ -89,6 +104,8 @@ LExit: extern "C" void DAPI ConsoleUninitialize() { + BOOL fOutEqualsIn = vhStdOut == vhStdIn; + memset(&vcsbiInfo, 0, sizeof(vcsbiInfo)); if (INVALID_HANDLE_VALUE != vhStdOut) @@ -96,7 +113,7 @@ extern "C" void DAPI ConsoleUninitialize() ::CloseHandle(vhStdOut); } - if (INVALID_HANDLE_VALUE != vhStdIn && vhStdOut != vhStdIn) + if (INVALID_HANDLE_VALUE != vhStdIn && !fOutEqualsIn) { ::CloseHandle(vhStdIn); } @@ -178,14 +195,14 @@ extern "C" HRESULT DAPI ConsoleWrite( va_start(args, szFormat); hr = StrAnsiAllocFormattedArgs(&pszOutput, szFormat, args); va_end(args); - ExitOnFailure(hr, "failed to format message: \"%s\"", szFormat); + ConExitOnFailure(hr, "failed to format message: \"%s\"", szFormat); cchOutput = lstrlenA(pszOutput); while (cbTotal < (sizeof(*pszOutput) * cchOutput)) { if (!::WriteFile(vhStdOut, reinterpret_cast(pszOutput) + cbTotal, cchOutput * sizeof(*pszOutput) - cbTotal, &cbWrote, NULL)) { - ExitOnLastError(hr, "failed to write output to console: %s", pszOutput); + ConExitOnLastError(hr, "failed to write output to console: %s", pszOutput); } cbTotal += cbWrote; @@ -236,7 +253,7 @@ extern "C" HRESULT DAPI ConsoleWriteLine( va_start(args, szFormat); hr = StrAnsiAllocFormattedArgs(&pszOutput, szFormat, args); va_end(args); - ExitOnFailure(hr, "failed to format message: \"%s\"", szFormat); + ConExitOnFailure(hr, "failed to format message: \"%s\"", szFormat); // // write the string @@ -245,7 +262,7 @@ extern "C" HRESULT DAPI ConsoleWriteLine( while (cbTotal < (sizeof(*pszOutput) * cchOutput)) { if (!::WriteFile(vhStdOut, reinterpret_cast(pszOutput) + cbTotal, cchOutput * sizeof(*pszOutput) - cbTotal, &cbWrote, NULL)) - ExitOnLastError(hr, "failed to write output to console: %s", pszOutput); + ConExitOnLastError(hr, "failed to write output to console: %s", pszOutput); cbTotal += cbWrote; } @@ -255,7 +272,7 @@ extern "C" HRESULT DAPI ConsoleWriteLine( // if (!::WriteFile(vhStdOut, reinterpret_cast(szNewLine), 2, &cbWrote, NULL)) { - ExitOnLastError(hr, "failed to write newline to console"); + ConExitOnLastError(hr, "failed to write newline to console"); } // reset the color to normal @@ -289,7 +306,7 @@ HRESULT ConsoleWriteError( va_start(args, szFormat); hr = StrAnsiAllocFormattedArgs(&pszMessage, szFormat, args); va_end(args); - ExitOnFailure(hr, "failed to format error message: \"%s\"", szFormat); + ConExitOnFailure(hr, "failed to format error message: \"%s\"", szFormat); if (FAILED(hrError)) { @@ -326,14 +343,14 @@ extern "C" HRESULT DAPI ConsoleReadW( cch = 64; hr = StrAnsiAlloc(&psz, cch); - ExitOnFailure(hr, "failed to allocate memory to read from console"); + ConExitOnFailure(hr, "failed to allocate memory to read from console"); // loop until we read the \r\n from the console for (;;) { // read one character at a time, since that seems to be the only way to make this work if (!::ReadFile(vhStdIn, psz + cchTotalRead, 1, &cchRead, NULL)) - ExitOnLastError(hr, "failed to read string from console"); + ConExitOnLastError(hr, "failed to read string from console"); cchTotalRead += cchRead; if (1 < cchTotalRead && '\r' == psz[cchTotalRead - 2] || '\n' == psz[cchTotalRead - 1]) @@ -351,7 +368,7 @@ extern "C" HRESULT DAPI ConsoleReadW( { cch *= 2; // double everytime we run out of space hr = StrAnsiAlloc(&psz, cch); - ExitOnFailure(hr, "failed to allocate memory to read from console"); + ConExitOnFailure(hr, "failed to allocate memory to read from console"); } } @@ -381,7 +398,7 @@ extern "C" HRESULT DAPI ConsoleReadNonBlockingW( LPSTR psz = NULL; - ExitOnNull(ppwzBuffer, hr, E_INVALIDARG, "Failed to read from console because buffer was not provided"); + ConExitOnNull(ppwzBuffer, hr, E_INVALIDARG, "Failed to read from console because buffer was not provided"); DWORD dwRead; DWORD dwNumInput; @@ -412,7 +429,7 @@ extern "C" HRESULT DAPI ConsoleReadNonBlockingW( if (!GetNumberOfConsoleInputEvents(vhStdIn, &dwRead)) { - ExitOnLastError(hr, "failed to peek at console input"); + ConExitOnLastError(hr, "failed to peek at console input"); } if (0 == dwRead) @@ -424,7 +441,7 @@ extern "C" HRESULT DAPI ConsoleReadNonBlockingW( { if (!ReadConsoleInputW(vhStdIn, &ir, 1, &dwNumInput)) { - ExitOnLastError(hr, "Failed to read input from console"); + ConExitOnLastError(hr, "Failed to read input from console"); } // If what we have is a KEY_EVENT, and that event signifies keyUp, we're interested @@ -463,14 +480,14 @@ extern "C" HRESULT DAPI ConsoleReadNonBlockingW( cch = 8; hr = StrAnsiAlloc(&psz, cch); - ExitOnFailure(hr, "failed to allocate memory to read from console"); + ConExitOnFailure(hr, "failed to allocate memory to read from console"); for (/*dwRead from PeekNamedPipe*/; dwRead > 0; dwRead--) { // read one character at a time, since that seems to be the only way to make this work if (!::ReadFile(vhStdIn, psz + cchTotalRead, 1, &cchRead, NULL)) { - ExitOnLastError(hr, "failed to read string from console"); + ConExitOnLastError(hr, "failed to read string from console"); } cchTotalRead += cchRead; @@ -490,7 +507,7 @@ extern "C" HRESULT DAPI ConsoleReadNonBlockingW( { cch *= 2; // double everytime we run out of space hr = StrAnsiAlloc(&psz, cch); - ExitOnFailure(hr, "failed to allocate memory to read from console"); + ConExitOnFailure(hr, "failed to allocate memory to read from console"); } } @@ -510,7 +527,7 @@ LExit: *********************************************************************/ extern "C" HRESULT DAPI ConsoleReadStringA( - __deref_out_ecount_part(cchCharBuffer,*pcchNumCharReturn) LPSTR* ppszCharBuffer, + __deref_inout_ecount_part(cchCharBuffer,*pcchNumCharReturn) LPSTR* ppszCharBuffer, CONST DWORD cchCharBuffer, __out DWORD* pcchNumCharReturn ) @@ -526,11 +543,11 @@ extern "C" HRESULT DAPI ConsoleReadStringA( do { hr = StrAnsiAlloc(ppszCharBuffer, cchCharBuffer * iRead); - ExitOnFailure(hr, "failed to allocate memory for ConsoleReadStringW"); + ConExitOnFailure(hr, "failed to allocate memory for ConsoleReadStringW"); // ReadConsoleW will not return until , the last two chars are 13 and 10. if (!::ReadConsoleA(vhStdIn, *ppszCharBuffer + iReadCharTotal, cchCharBuffer, pcchNumCharReturn, NULL) || *pcchNumCharReturn == 0) { - ExitOnLastError(hr, "failed to read string from console"); + ConExitOnLastError(hr, "failed to read string from console"); } iReadCharTotal += *pcchNumCharReturn; iRead += 1; @@ -543,7 +560,7 @@ extern "C" HRESULT DAPI ConsoleReadStringA( if (!::ReadConsoleA(vhStdIn, *ppszCharBuffer, cchCharBuffer, pcchNumCharReturn, NULL) || *pcchNumCharReturn > cchCharBuffer || *pcchNumCharReturn == 0) { - ExitOnLastError(hr, "failed to read string from console"); + ConExitOnLastError(hr, "failed to read string from console"); } if ((*ppszCharBuffer)[*pcchNumCharReturn - 1] != 10 || (*ppszCharBuffer)[*pcchNumCharReturn - 2] != 13) @@ -567,7 +584,7 @@ LExit: *********************************************************************/ extern "C" HRESULT DAPI ConsoleReadStringW( - __deref_out_ecount_part(cchCharBuffer,*pcchNumCharReturn) LPWSTR* ppwzCharBuffer, + __deref_inout_ecount_part(cchCharBuffer,*pcchNumCharReturn) LPWSTR* ppwzCharBuffer, const DWORD cchCharBuffer, __out DWORD* pcchNumCharReturn ) @@ -583,11 +600,11 @@ extern "C" HRESULT DAPI ConsoleReadStringW( do { hr = StrAlloc(ppwzCharBuffer, cchCharBuffer * iRead); - ExitOnFailure(hr, "failed to allocate memory for ConsoleReadStringW"); + ConExitOnFailure(hr, "failed to allocate memory for ConsoleReadStringW"); // ReadConsoleW will not return until , the last two chars are 13 and 10. if (!::ReadConsoleW(vhStdIn, *ppwzCharBuffer + iReadCharTotal, cchCharBuffer, pcchNumCharReturn, NULL) || *pcchNumCharReturn == 0) { - ExitOnLastError(hr, "failed to read string from console"); + ConExitOnLastError(hr, "failed to read string from console"); } iReadCharTotal += *pcchNumCharReturn; iRead += 1; @@ -600,7 +617,7 @@ extern "C" HRESULT DAPI ConsoleReadStringW( if (!::ReadConsoleW(vhStdIn, *ppwzCharBuffer, cchCharBuffer, pcchNumCharReturn, NULL) || *pcchNumCharReturn > cchCharBuffer || *pcchNumCharReturn == 0) { - ExitOnLastError(hr, "failed to read string from console"); + ConExitOnLastError(hr, "failed to read string from console"); } if ((*ppwzCharBuffer)[*pcchNumCharReturn - 1] != 10 || (*ppwzCharBuffer)[*pcchNumCharReturn - 2] != 13) @@ -630,7 +647,7 @@ extern "C" HRESULT DAPI ConsoleSetReadHidden(void) ::FlushConsoleInputBuffer(vhStdIn); if (!::SetConsoleMode(vhStdIn, ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT)) { - ExitOnLastError(hr, "failed to set console input mode to be hidden"); + ConExitOnLastError(hr, "failed to set console input mode to be hidden"); } LExit: @@ -647,7 +664,7 @@ extern "C" HRESULT DAPI ConsoleSetReadNormal(void) HRESULT hr = S_OK; if (!::SetConsoleMode(vhStdIn, ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT | ENABLE_PROCESSED_INPUT | ENABLE_MOUSE_INPUT)) { - ExitOnLastError(hr, "failed to set console input mode to be normal"); + ConExitOnLastError(hr, "failed to set console input mode to be normal"); } LExit: diff --git a/src/dutil/cryputil.cpp b/src/dutil/cryputil.cpp index 214704b4..c5c1b221 100644 --- a/src/dutil/cryputil.cpp +++ b/src/dutil/cryputil.cpp @@ -2,6 +2,21 @@ #include "precomp.h" + +// Exit macros +#define CrypExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_CRYPUTIL, x, s, __VA_ARGS__) +#define CrypExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_CRYPUTIL, x, s, __VA_ARGS__) +#define CrypExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_CRYPUTIL, x, s, __VA_ARGS__) +#define CrypExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_CRYPUTIL, x, s, __VA_ARGS__) +#define CrypExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_CRYPUTIL, x, s, __VA_ARGS__) +#define CrypExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_CRYPUTIL, x, s, __VA_ARGS__) +#define CrypExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_CRYPUTIL, p, x, e, s, __VA_ARGS__) +#define CrypExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_CRYPUTIL, p, x, s, __VA_ARGS__) +#define CrypExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_CRYPUTIL, p, x, e, s, __VA_ARGS__) +#define CrypExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_CRYPUTIL, p, x, s, __VA_ARGS__) +#define CrypExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_CRYPUTIL, e, x, s, __VA_ARGS__) +#define CrypExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_CRYPUTIL, g, x, s, __VA_ARGS__) + static PFN_RTLENCRYPTMEMORY vpfnRtlEncryptMemory = NULL; static PFN_RTLDECRYPTMEMORY vpfnRtlDecryptMemory = NULL; static PFN_CRYPTPROTECTMEMORY vpfnCryptProtectMemory = NULL; @@ -32,17 +47,17 @@ extern "C" HRESULT DAPI CrypInitialize( if (!vpfnRtlEncryptMemory || !vpfnRtlDecryptMemory) { hr = LoadSystemLibrary(L"Crypt32.dll", &vhCrypt32Dll); - ExitOnFailure(hr, "Failed to load Crypt32.dll"); + CrypExitOnFailure(hr, "Failed to load Crypt32.dll"); vpfnCryptProtectMemory = reinterpret_cast(::GetProcAddress(vhCrypt32Dll, "CryptProtectMemory")); if (!vpfnRtlEncryptMemory && !vpfnCryptProtectMemory) { - ExitWithLastError(hr, "Failed to load an encryption method"); + CrypExitWithLastError(hr, "Failed to load an encryption method"); } vpfnCryptUnprotectMemory = reinterpret_cast(::GetProcAddress(vhCrypt32Dll, "CryptUnprotectMemory")); if (!vpfnRtlDecryptMemory && !vpfnCryptUnprotectMemory) { - ExitWithLastError(hr, "Failed to load a decryption method"); + CrypExitWithLastError(hr, "Failed to load a decryption method"); } } @@ -94,15 +109,15 @@ extern "C" HRESULT DAPI CrypDecodeObject( if (!::CryptDecodeObject(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, szStructType, pbData, cbData, dwFlags, NULL, &cbObject)) { - ExitWithLastError(hr, "Failed to decode object to determine size."); + CrypExitWithLastError(hr, "Failed to decode object to determine size."); } pvObject = MemAlloc(cbObject, TRUE); - ExitOnNull(pvObject, hr, E_OUTOFMEMORY, "Failed to allocate memory for decoded object."); + CrypExitOnNull(pvObject, hr, E_OUTOFMEMORY, "Failed to allocate memory for decoded object."); if (!::CryptDecodeObject(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, szStructType, pbData, cbData, dwFlags, pvObject, &cbObject)) { - ExitWithLastError(hr, "Failed to decode object."); + CrypExitWithLastError(hr, "Failed to decode object."); } *ppvObject = pvObject; @@ -134,15 +149,15 @@ extern "C" HRESULT DAPI CrypMsgGetParam( if (!::CryptMsgGetParam(hCryptMsg, dwType, dwIndex, NULL, &cb)) { - ExitWithLastError(hr, "Failed to get crypt message parameter data size."); + CrypExitWithLastError(hr, "Failed to get crypt message parameter data size."); } pv = MemAlloc(cb, TRUE); - ExitOnNull(pv, hr, E_OUTOFMEMORY, "Failed to allocate memory for crypt message parameter."); + CrypExitOnNull(pv, hr, E_OUTOFMEMORY, "Failed to allocate memory for crypt message parameter."); if (!::CryptMsgGetParam(hCryptMsg, dwType, dwIndex, pv, &cb)) { - ExitWithLastError(hr, "Failed to get crypt message parameter."); + CrypExitWithLastError(hr, "Failed to get crypt message parameter."); } *ppvData = pv; @@ -161,7 +176,7 @@ LExit: extern "C" HRESULT DAPI CrypHashFile( - __in LPCWSTR wzFilePath, + __in_z LPCWSTR wzFilePath, __in DWORD dwProvType, __in ALG_ID algid, __out_bcount(cbHash) BYTE* pbHash, @@ -176,11 +191,11 @@ extern "C" HRESULT DAPI CrypHashFile( hFile = ::CreateFileW(wzFilePath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL); if (INVALID_HANDLE_VALUE == hFile) { - ExitWithLastError(hr, "Failed to open input file."); + CrypExitWithLastError(hr, "Failed to open input file."); } hr = CrypHashFileHandle(hFile, dwProvType, algid, pbHash, cbHash, pqwBytesHashed); - ExitOnFailure(hr, "Failed to hash file: %ls", wzFilePath); + CrypExitOnFailure(hr, "Failed to hash file: %ls", wzFilePath); LExit: ReleaseFileHandle(hFile); @@ -208,13 +223,13 @@ extern "C" HRESULT DAPI CrypHashFileHandle( // get handle to the crypto provider if (!::CryptAcquireContextW(&hProv, NULL, NULL, dwProvType, CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) { - ExitWithLastError(hr, "Failed to acquire crypto context."); + CrypExitWithLastError(hr, "Failed to acquire crypto context."); } // initiate hash if (!::CryptCreateHash(hProv, algid, 0, 0, &hHash)) { - ExitWithLastError(hr, "Failed to initiate hash."); + CrypExitWithLastError(hr, "Failed to initiate hash."); } for (;;) @@ -222,7 +237,7 @@ extern "C" HRESULT DAPI CrypHashFileHandle( // read data block if (!::ReadFile(hFile, rgbBuffer, sizeof(rgbBuffer), &cbRead, NULL)) { - ExitWithLastError(hr, "Failed to read data block."); + CrypExitWithLastError(hr, "Failed to read data block."); } if (!cbRead) @@ -233,21 +248,21 @@ extern "C" HRESULT DAPI CrypHashFileHandle( // hash data block if (!::CryptHashData(hHash, rgbBuffer, cbRead, 0)) { - ExitWithLastError(hr, "Failed to hash data block."); + CrypExitWithLastError(hr, "Failed to hash data block."); } } // get hash value if (!::CryptGetHashParam(hHash, HP_HASHVAL, pbHash, &cbHash, 0)) { - ExitWithLastError(hr, "Failed to get hash value."); + CrypExitWithLastError(hr, "Failed to get hash value."); } if (pqwBytesHashed) { if (!::SetFilePointerEx(hFile, liZero, (LARGE_INTEGER*)pqwBytesHashed, FILE_CURRENT)) { - ExitWithLastError(hr, "Failed to get file pointer."); + CrypExitWithLastError(hr, "Failed to get file pointer."); } } @@ -280,24 +295,24 @@ HRESULT DAPI CrypHashBuffer( // get handle to the crypto provider if (!::CryptAcquireContextW(&hProv, NULL, NULL, dwProvType, CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) { - ExitWithLastError(hr, "Failed to acquire crypto context."); + CrypExitWithLastError(hr, "Failed to acquire crypto context."); } // initiate hash if (!::CryptCreateHash(hProv, algid, 0, 0, &hHash)) { - ExitWithLastError(hr, "Failed to initiate hash."); + CrypExitWithLastError(hr, "Failed to initiate hash."); } if (!::CryptHashData(hHash, pbBuffer, static_cast(cbBuffer), 0)) { - ExitWithLastError(hr, "Failed to hash data."); + CrypExitWithLastError(hr, "Failed to hash data."); } // get hash value if (!::CryptGetHashParam(hHash, HP_HASHVAL, pbHash, &cbHash, 0)) { - ExitWithLastError(hr, "Failed to get hash value."); + CrypExitWithLastError(hr, "Failed to get hash value."); } LExit: @@ -340,7 +355,7 @@ HRESULT DAPI CrypEncryptMemory( hr = HRESULT_FROM_WIN32(::GetLastError()); } } - ExitOnFailure(hr, "Failed to encrypt memory"); + CrypExitOnFailure(hr, "Failed to encrypt memory"); LExit: return hr; } @@ -372,7 +387,7 @@ HRESULT DAPI CrypDecryptMemory( hr = HRESULT_FROM_WIN32(::GetLastError()); } } - ExitOnFailure(hr, "Failed to decrypt memory"); + CrypExitOnFailure(hr, "Failed to decrypt memory"); LExit: return hr; } diff --git a/src/dutil/deputil.cpp b/src/dutil/deputil.cpp index d65c4348..362b3345 100644 --- a/src/dutil/deputil.cpp +++ b/src/dutil/deputil.cpp @@ -2,6 +2,21 @@ #include "precomp.h" + +// Exit macros +#define DepExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_DEPUTIL, x, s, __VA_ARGS__) +#define DepExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_DEPUTIL, x, s, __VA_ARGS__) +#define DepExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_DEPUTIL, x, s, __VA_ARGS__) +#define DepExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_DEPUTIL, x, s, __VA_ARGS__) +#define DepExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_DEPUTIL, x, s, __VA_ARGS__) +#define DepExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_DEPUTIL, x, s, __VA_ARGS__) +#define DepExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_DEPUTIL, p, x, e, s, __VA_ARGS__) +#define DepExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_DEPUTIL, p, x, s, __VA_ARGS__) +#define DepExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_DEPUTIL, p, x, e, s, __VA_ARGS__) +#define DepExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_DEPUTIL, p, x, s, __VA_ARGS__) +#define DepExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_DEPUTIL, e, x, s, __VA_ARGS__) +#define DepExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_DEPUTIL, g, x, s, __VA_ARGS__) + #define ARRAY_GROWTH_SIZE 5 static LPCWSTR vcszVersionValue = L"Version"; @@ -42,7 +57,7 @@ DAPI_(HRESULT) DepGetProviderInformation( // Format the provider dependency registry key. hr = AllocDependencyKeyName(wzProviderKey, &sczKey); - ExitOnFailure(hr, "Failed to allocate the registry key for dependency \"%ls\".", wzProviderKey); + DepExitOnFailure(hr, "Failed to allocate the registry key for dependency \"%ls\".", wzProviderKey); // Try to open the dependency key. hr = RegOpen(hkHive, sczKey, KEY_READ, &hkKey); @@ -50,7 +65,7 @@ DAPI_(HRESULT) DepGetProviderInformation( { ExitFunction1(hr = E_NOTFOUND); } - ExitOnFailure(hr, "Failed to open the registry key for the dependency \"%ls\".", wzProviderKey); + DepExitOnFailure(hr, "Failed to open the registry key for the dependency \"%ls\".", wzProviderKey); // Get the Id if requested and available. if (psczId) @@ -60,7 +75,7 @@ DAPI_(HRESULT) DepGetProviderInformation( { hr = S_OK; } - ExitOnFailure(hr, "Failed to get the id for the dependency \"%ls\".", wzProviderKey); + DepExitOnFailure(hr, "Failed to get the id for the dependency \"%ls\".", wzProviderKey); } // Get the DisplayName if requested and available. @@ -71,7 +86,7 @@ DAPI_(HRESULT) DepGetProviderInformation( { hr = S_OK; } - ExitOnFailure(hr, "Failed to get the name for the dependency \"%ls\".", wzProviderKey); + DepExitOnFailure(hr, "Failed to get the name for the dependency \"%ls\".", wzProviderKey); } // Get the Version if requested and available. @@ -82,7 +97,7 @@ DAPI_(HRESULT) DepGetProviderInformation( { hr = S_OK; } - ExitOnFailure(hr, "Failed to get the version for the dependency \"%ls\".", wzProviderKey); + DepExitOnFailure(hr, "Failed to get the version for the dependency \"%ls\".", wzProviderKey); } LExit: @@ -116,19 +131,19 @@ DAPI_(HRESULT) DepCheckDependency( // Format the provider dependency registry key. hr = AllocDependencyKeyName(wzProviderKey, &sczKey); - ExitOnFailure(hr, "Failed to allocate the registry key for dependency \"%ls\".", wzProviderKey); + DepExitOnFailure(hr, "Failed to allocate the registry key for dependency \"%ls\".", wzProviderKey); // Try to open the key. If that fails, add the missing dependency key to the dependency array if it doesn't already exist. hr = RegOpen(hkHive, sczKey, KEY_READ, &hkKey); if (E_FILENOTFOUND != hr) { - ExitOnFailure(hr, "Failed to open the registry key for dependency \"%ls\".", wzProviderKey); + DepExitOnFailure(hr, "Failed to open the registry key for dependency \"%ls\".", wzProviderKey); // If there are no registry values, consider the key orphaned and treat it as missing. hr = RegReadVersion(hkKey, vcszVersionValue, &dw64Version); if (E_FILENOTFOUND != hr) { - ExitOnFailure(hr, "Failed to read the %ls registry value for dependency \"%ls\".", vcszVersionValue, wzProviderKey); + DepExitOnFailure(hr, "Failed to read the %ls registry value for dependency \"%ls\".", vcszVersionValue, wzProviderKey); } } @@ -138,15 +153,15 @@ DAPI_(HRESULT) DepCheckDependency( hr = DictKeyExists(sdDependencies, wzProviderKey); if (E_NOTFOUND != hr) { - ExitOnFailure(hr, "Failed to check the dictionary for missing dependency \"%ls\".", wzProviderKey); + DepExitOnFailure(hr, "Failed to check the dictionary for missing dependency \"%ls\".", wzProviderKey); } else { hr = DepDependencyArrayAlloc(prgDependencies, pcDependencies, wzProviderKey, NULL); - ExitOnFailure(hr, "Failed to add the missing dependency \"%ls\" to the array.", wzProviderKey); + DepExitOnFailure(hr, "Failed to add the missing dependency \"%ls\" to the array.", wzProviderKey); hr = DictAddKey(sdDependencies, wzProviderKey); - ExitOnFailure(hr, "Failed to add the missing dependency \"%ls\" to the dictionary.", wzProviderKey); + DepExitOnFailure(hr, "Failed to add the missing dependency \"%ls\" to the dictionary.", wzProviderKey); } // Exit since the check already failed. @@ -160,7 +175,7 @@ DAPI_(HRESULT) DepCheckDependency( if (0 < cchMinVersion) { hr = FileVersionFromStringEx(wzMinVersion, cchMinVersion, &dw64MinVersion); - ExitOnFailure(hr, "Failed to get the 64-bit version number from \"%ls\".", wzMinVersion); + DepExitOnFailure(hr, "Failed to get the 64-bit version number from \"%ls\".", wzMinVersion); fAllowEqual = iAttributes & RequiresAttributesMinVersionInclusive; if (!(fAllowEqual && dw64MinVersion <= dw64Version || dw64MinVersion < dw64Version)) @@ -168,18 +183,18 @@ DAPI_(HRESULT) DepCheckDependency( hr = DictKeyExists(sdDependencies, wzProviderKey); if (E_NOTFOUND != hr) { - ExitOnFailure(hr, "Failed to check the dictionary for the older dependency \"%ls\".", wzProviderKey); + DepExitOnFailure(hr, "Failed to check the dictionary for the older dependency \"%ls\".", wzProviderKey); } else { hr = RegReadString(hkKey, vcszDisplayNameValue, &sczName); - ExitOnFailure(hr, "Failed to get the display name of the older dependency \"%ls\".", wzProviderKey); + DepExitOnFailure(hr, "Failed to get the display name of the older dependency \"%ls\".", wzProviderKey); hr = DepDependencyArrayAlloc(prgDependencies, pcDependencies, wzProviderKey, sczName); - ExitOnFailure(hr, "Failed to add the older dependency \"%ls\" to the dependencies array.", wzProviderKey); + DepExitOnFailure(hr, "Failed to add the older dependency \"%ls\" to the dependencies array.", wzProviderKey); hr = DictAddKey(sdDependencies, wzProviderKey); - ExitOnFailure(hr, "Failed to add the older dependency \"%ls\" to the unique dependency string list.", wzProviderKey); + DepExitOnFailure(hr, "Failed to add the older dependency \"%ls\" to the unique dependency string list.", wzProviderKey); } // Exit since the check already failed. @@ -195,7 +210,7 @@ DAPI_(HRESULT) DepCheckDependency( if (0 < cchMaxVersion) { hr = FileVersionFromStringEx(wzMaxVersion, cchMaxVersion, &dw64MaxVersion); - ExitOnFailure(hr, "Failed to get the 64-bit version number from \"%ls\".", wzMaxVersion); + DepExitOnFailure(hr, "Failed to get the 64-bit version number from \"%ls\".", wzMaxVersion); fAllowEqual = iAttributes & RequiresAttributesMaxVersionInclusive; if (!(fAllowEqual && dw64Version <= dw64MaxVersion || dw64Version < dw64MaxVersion)) @@ -203,18 +218,18 @@ DAPI_(HRESULT) DepCheckDependency( hr = DictKeyExists(sdDependencies, wzProviderKey); if (E_NOTFOUND != hr) { - ExitOnFailure(hr, "Failed to check the dictionary for the newer dependency \"%ls\".", wzProviderKey); + DepExitOnFailure(hr, "Failed to check the dictionary for the newer dependency \"%ls\".", wzProviderKey); } else { hr = RegReadString(hkKey, vcszDisplayNameValue, &sczName); - ExitOnFailure(hr, "Failed to get the display name of the newer dependency \"%ls\".", wzProviderKey); + DepExitOnFailure(hr, "Failed to get the display name of the newer dependency \"%ls\".", wzProviderKey); hr = DepDependencyArrayAlloc(prgDependencies, pcDependencies, wzProviderKey, sczName); - ExitOnFailure(hr, "Failed to add the newer dependency \"%ls\" to the dependencies array.", wzProviderKey); + DepExitOnFailure(hr, "Failed to add the newer dependency \"%ls\" to the dependencies array.", wzProviderKey); hr = DictAddKey(sdDependencies, wzProviderKey); - ExitOnFailure(hr, "Failed to add the newer dependency \"%ls\" to the unique dependency string list.", wzProviderKey); + DepExitOnFailure(hr, "Failed to add the newer dependency \"%ls\" to the unique dependency string list.", wzProviderKey); } // Exit since the check already failed. @@ -249,17 +264,17 @@ DAPI_(HRESULT) DepCheckDependents( // Format the provider dependency registry key. hr = AllocDependencyKeyName(wzProviderKey, &sczKey); - ExitOnFailure(hr, "Failed to allocate the registry key for dependency \"%ls\".", wzProviderKey); + DepExitOnFailure(hr, "Failed to allocate the registry key for dependency \"%ls\".", wzProviderKey); // Try to open the key. If that fails, the dependency information is corrupt. hr = RegOpen(hkHive, sczKey, KEY_READ, &hkProviderKey); - ExitOnFailure(hr, "Failed to open the registry key \"%ls\". The dependency store is corrupt.", sczKey); + DepExitOnFailure(hr, "Failed to open the registry key \"%ls\". The dependency store is corrupt.", sczKey); // Try to open the dependencies key. If that does not exist, there are no dependents. hr = RegOpen(hkProviderKey, vsczRegistryDependents, KEY_READ, &hkDependentsKey); if (E_FILENOTFOUND != hr) { - ExitOnFailure(hr, "Failed to open the registry key for dependents of \"%ls\".", wzProviderKey); + DepExitOnFailure(hr, "Failed to open the registry key for dependents of \"%ls\".", wzProviderKey); } else { @@ -272,7 +287,7 @@ DAPI_(HRESULT) DepCheckDependents( hr = RegKeyEnum(hkDependentsKey, dwIndex, &sczDependentKey); if (E_NOMOREITEMS != hr) { - ExitOnFailure(hr, "Failed to enumerate the dependents key of \"%ls\".", wzProviderKey); + DepExitOnFailure(hr, "Failed to enumerate the dependents key of \"%ls\".", wzProviderKey); } else { @@ -284,16 +299,16 @@ DAPI_(HRESULT) DepCheckDependents( hr = DictKeyExists(sdIgnoredDependents, sczDependentKey); if (E_NOTFOUND != hr) { - ExitOnFailure(hr, "Failed to check the dictionary of ignored dependents."); + DepExitOnFailure(hr, "Failed to check the dictionary of ignored dependents."); } else { // Get the name of the dependent from the key. hr = GetDependencyNameFromKey(hkHive, sczDependentKey, &sczDependentName); - ExitOnFailure(hr, "Failed to get the name of the dependent from the key \"%ls\".", sczDependentKey); + DepExitOnFailure(hr, "Failed to get the name of the dependent from the key \"%ls\".", sczDependentKey); hr = DepDependencyArrayAlloc(prgDependents, pcDependents, sczDependentKey, sczDependentName); - ExitOnFailure(hr, "Failed to add the dependent key \"%ls\" to the string array.", sczDependentKey); + DepExitOnFailure(hr, "Failed to add the dependent key \"%ls\" to the string array.", sczDependentKey); } } @@ -323,32 +338,32 @@ DAPI_(HRESULT) DepRegisterDependency( // Format the provider dependency registry key. hr = AllocDependencyKeyName(wzProviderKey, &sczKey); - ExitOnFailure(hr, "Failed to allocate the registry key for dependency \"%ls\".", wzProviderKey); + DepExitOnFailure(hr, "Failed to allocate the registry key for dependency \"%ls\".", wzProviderKey); // Create the dependency key (or open it if it already exists). hr = RegCreateEx(hkHive, sczKey, KEY_WRITE, FALSE, NULL, &hkKey, &fCreated); - ExitOnFailure(hr, "Failed to create the dependency registry key \"%ls\".", sczKey); + DepExitOnFailure(hr, "Failed to create the dependency registry key \"%ls\".", sczKey); // Set the id if it was provided. if (wzId) { hr = RegWriteString(hkKey, NULL, wzId); - ExitOnFailure(hr, "Failed to set the %ls registry value to \"%ls\".", L"default", wzId); + DepExitOnFailure(hr, "Failed to set the %ls registry value to \"%ls\".", L"default", wzId); } // Set the version. hr = RegWriteString(hkKey, vcszVersionValue, wzVersion); - ExitOnFailure(hr, "Failed to set the %ls registry value to \"%ls\".", vcszVersionValue, wzVersion); + DepExitOnFailure(hr, "Failed to set the %ls registry value to \"%ls\".", vcszVersionValue, wzVersion); // Set the display name. hr = RegWriteString(hkKey, vcszDisplayNameValue, wzDisplayName); - ExitOnFailure(hr, "Failed to set the %ls registry value to \"%ls\".", vcszDisplayNameValue, wzDisplayName); + DepExitOnFailure(hr, "Failed to set the %ls registry value to \"%ls\".", vcszDisplayNameValue, wzDisplayName); // Set the attributes if non-zero. if (0 != iAttributes) { hr = RegWriteNumber(hkKey, vcszAttributesValue, static_cast(iAttributes)); - ExitOnFailure(hr, "Failed to set the %ls registry value to %d.", vcszAttributesValue, iAttributes); + DepExitOnFailure(hr, "Failed to set the %ls registry value to %d.", vcszAttributesValue, iAttributes); } LExit: @@ -370,12 +385,12 @@ DAPI_(HRESULT) DepDependentExists( // Format the provider dependents registry key. hr = StrAllocFormatted(&sczDependentKey, L"%ls%ls\\%ls\\%ls", vsczRegistryRoot, wzDependencyProviderKey, vsczRegistryDependents, wzProviderKey); - ExitOnFailure(hr, "Failed to format registry key to dependent."); + DepExitOnFailure(hr, "Failed to format registry key to dependent."); hr = RegOpen(hkHive, sczDependentKey, KEY_READ, &hkDependentKey); if (E_FILENOTFOUND != hr) { - ExitOnFailure(hr, "Failed to open the dependent registry key at: \"%ls\".", sczDependentKey); + DepExitOnFailure(hr, "Failed to open the dependent registry key at: \"%ls\".", sczDependentKey); } LExit: @@ -403,32 +418,32 @@ DAPI_(HRESULT) DepRegisterDependent( // Format the provider dependency registry key. hr = AllocDependencyKeyName(wzDependencyProviderKey, &sczDependencyKey); - ExitOnFailure(hr, "Failed to allocate the registry key for dependency \"%ls\".", wzDependencyProviderKey); + DepExitOnFailure(hr, "Failed to allocate the registry key for dependency \"%ls\".", wzDependencyProviderKey); // Create the dependency key (or open it if it already exists). hr = RegCreateEx(hkHive, sczDependencyKey, KEY_WRITE, FALSE, NULL, &hkDependencyKey, &fCreated); - ExitOnFailure(hr, "Failed to create the dependency registry key \"%ls\".", sczDependencyKey); + DepExitOnFailure(hr, "Failed to create the dependency registry key \"%ls\".", sczDependencyKey); // Create the subkey to register the dependent. hr = StrAllocFormatted(&sczKey, L"%ls\\%ls", vsczRegistryDependents, wzProviderKey); - ExitOnFailure(hr, "Failed to allocate dependent subkey \"%ls\" under dependency \"%ls\".", wzProviderKey, wzDependencyProviderKey); + DepExitOnFailure(hr, "Failed to allocate dependent subkey \"%ls\" under dependency \"%ls\".", wzProviderKey, wzDependencyProviderKey); hr = RegCreateEx(hkDependencyKey, sczKey, KEY_WRITE, FALSE, NULL, &hkKey, &fCreated); - ExitOnFailure(hr, "Failed to create the dependency subkey \"%ls\".", sczKey); + DepExitOnFailure(hr, "Failed to create the dependency subkey \"%ls\".", sczKey); // Set the minimum version if not NULL. hr = RegWriteString(hkKey, vcszMinVersionValue, wzMinVersion); - ExitOnFailure(hr, "Failed to set the %ls registry value to \"%ls\".", vcszMinVersionValue, wzMinVersion); + DepExitOnFailure(hr, "Failed to set the %ls registry value to \"%ls\".", vcszMinVersionValue, wzMinVersion); // Set the maximum version if not NULL. hr = RegWriteString(hkKey, vcszMaxVersionValue, wzMaxVersion); - ExitOnFailure(hr, "Failed to set the %ls registry value to \"%ls\".", vcszMaxVersionValue, wzMaxVersion); + DepExitOnFailure(hr, "Failed to set the %ls registry value to \"%ls\".", vcszMaxVersionValue, wzMaxVersion); // Set the attributes if non-zero. if (0 != iAttributes) { hr = RegWriteNumber(hkKey, vcszAttributesValue, static_cast(iAttributes)); - ExitOnFailure(hr, "Failed to set the %ls registry value to %d.", vcszAttributesValue, iAttributes); + DepExitOnFailure(hr, "Failed to set the %ls registry value to %d.", vcszAttributesValue, iAttributes); } LExit: @@ -451,13 +466,13 @@ DAPI_(HRESULT) DepUnregisterDependency( // Format the provider dependency registry key. hr = AllocDependencyKeyName(wzProviderKey, &sczKey); - ExitOnFailure(hr, "Failed to allocate the registry key for dependency \"%ls\".", wzProviderKey); + DepExitOnFailure(hr, "Failed to allocate the registry key for dependency \"%ls\".", wzProviderKey); // Delete the entire key including all sub-keys. hr = RegDelete(hkHive, sczKey, REG_KEY_DEFAULT, TRUE); if (E_FILENOTFOUND != hr) { - ExitOnFailure(hr, "Failed to delete the key \"%ls\".", sczKey); + DepExitOnFailure(hr, "Failed to delete the key \"%ls\".", sczKey); } LExit: @@ -484,7 +499,7 @@ DAPI_(HRESULT) DepUnregisterDependent( hr = RegOpen(hkHive, vsczRegistryRoot, KEY_READ, &hkRegistryRoot); if (E_FILENOTFOUND != hr) { - ExitOnFailure(hr, "Failed to open root registry key \"%ls\".", vsczRegistryRoot); + DepExitOnFailure(hr, "Failed to open root registry key \"%ls\".", vsczRegistryRoot); } else { @@ -495,7 +510,7 @@ DAPI_(HRESULT) DepUnregisterDependent( hr = RegOpen(hkRegistryRoot, wzDependencyProviderKey, KEY_READ, &hkDependencyProviderKey); if (E_FILENOTFOUND != hr) { - ExitOnFailure(hr, "Failed to open the registry key for the dependency \"%ls\".", wzDependencyProviderKey); + DepExitOnFailure(hr, "Failed to open the registry key for the dependency \"%ls\".", wzDependencyProviderKey); } else { @@ -506,7 +521,7 @@ DAPI_(HRESULT) DepUnregisterDependent( hr = RegOpen(hkDependencyProviderKey, vsczRegistryDependents, KEY_READ, &hkRegistryDependents); if (E_FILENOTFOUND != hr) { - ExitOnFailure(hr, "Failed to open the dependents subkey under the dependency \"%ls\".", wzDependencyProviderKey); + DepExitOnFailure(hr, "Failed to open the dependents subkey under the dependency \"%ls\".", wzDependencyProviderKey); } else { @@ -515,11 +530,11 @@ DAPI_(HRESULT) DepUnregisterDependent( // Delete the wzProviderKey dependent sub-key. hr = RegDelete(hkRegistryDependents, wzProviderKey, REG_KEY_DEFAULT, TRUE); - ExitOnFailure(hr, "Failed to delete the dependent \"%ls\" under the dependency \"%ls\".", wzProviderKey, wzDependencyProviderKey); + DepExitOnFailure(hr, "Failed to delete the dependent \"%ls\" under the dependency \"%ls\".", wzProviderKey, wzDependencyProviderKey); // If there are no remaining dependents, delete the Dependents subkey. hr = RegQueryKey(hkRegistryDependents, &cSubKeys, NULL); - ExitOnFailure(hr, "Failed to get the number of dependent subkeys under the dependency \"%ls\".", wzDependencyProviderKey); + DepExitOnFailure(hr, "Failed to get the number of dependent subkeys under the dependency \"%ls\".", wzDependencyProviderKey); if (0 < cSubKeys) { @@ -531,11 +546,11 @@ DAPI_(HRESULT) DepUnregisterDependent( // Fail if there are any subkeys since we just checked. hr = RegDelete(hkDependencyProviderKey, vsczRegistryDependents, REG_KEY_DEFAULT, FALSE); - ExitOnFailure(hr, "Failed to delete the dependents subkey under the dependency \"%ls\".", wzDependencyProviderKey); + DepExitOnFailure(hr, "Failed to delete the dependents subkey under the dependency \"%ls\".", wzDependencyProviderKey); // If there are no values, delete the provider dependency key. hr = RegQueryKey(hkDependencyProviderKey, NULL, &cValues); - ExitOnFailure(hr, "Failed to get the number of values under the dependency \"%ls\".", wzDependencyProviderKey); + DepExitOnFailure(hr, "Failed to get the number of values under the dependency \"%ls\".", wzDependencyProviderKey); if (0 == cValues) { @@ -544,7 +559,7 @@ DAPI_(HRESULT) DepUnregisterDependent( // Fail if there are any subkeys since we just checked. hr = RegDelete(hkRegistryRoot, wzDependencyProviderKey, REG_KEY_DEFAULT, FALSE); - ExitOnFailure(hr, "Failed to delete the dependency \"%ls\".", wzDependencyProviderKey); + DepExitOnFailure(hr, "Failed to delete the dependency \"%ls\".", wzDependencyProviderKey); } LExit: @@ -567,21 +582,21 @@ DAPI_(HRESULT) DepDependencyArrayAlloc( DEPENDENCY* pDependency = NULL; hr = ::UIntAdd(*pcDependencies, 1, &cRequired); - ExitOnFailure(hr, "Failed to increment the number of elements required in the dependency array."); + DepExitOnFailure(hr, "Failed to increment the number of elements required in the dependency array."); hr = MemEnsureArraySize(reinterpret_cast(prgDependencies), cRequired, sizeof(DEPENDENCY), ARRAY_GROWTH_SIZE); - ExitOnFailure(hr, "Failed to allocate memory for the dependency array."); + DepExitOnFailure(hr, "Failed to allocate memory for the dependency array."); pDependency = static_cast(&(*prgDependencies)[*pcDependencies]); - ExitOnNull(pDependency, hr, E_POINTER, "The dependency element in the array is invalid."); + DepExitOnNull(pDependency, hr, E_POINTER, "The dependency element in the array is invalid."); hr = StrAllocString(&(pDependency->sczKey), wzKey, 0); - ExitOnFailure(hr, "Failed to allocate the string key in the dependency array."); + DepExitOnFailure(hr, "Failed to allocate the string key in the dependency array."); if (wzName) { hr = StrAllocString(&(pDependency->sczName), wzName, 0); - ExitOnFailure(hr, "Failed to allocate the string name in the dependency array."); + DepExitOnFailure(hr, "Failed to allocate the string name in the dependency array."); } // Update the number of current elements in the dependency array. @@ -623,18 +638,18 @@ static HRESULT AllocDependencyKeyName( // Get the length of the dependency, and add to the length of the root. hr = ::StringCchLengthW(wzName, STRSAFE_MAX_CCH, &cchName); - ExitOnFailure(hr, "Failed to get string length of dependency name."); + DepExitOnFailure(hr, "Failed to get string length of dependency name."); // Add the sizes together to allocate memory once (callee will add space for nul). hr = ::SizeTAdd(cchRegistryRoot, cchName, &cchKeyName); - ExitOnFailure(hr, "Failed to add the string lengths together."); + DepExitOnFailure(hr, "Failed to add the string lengths together."); // Allocate and concat the strings together. hr = StrAllocString(psczKeyName, vsczRegistryRoot, cchKeyName); - ExitOnFailure(hr, "Failed to allocate string for dependency registry root."); + DepExitOnFailure(hr, "Failed to allocate string for dependency registry root."); hr = StrAllocConcat(psczKeyName, wzName, cchName); - ExitOnFailure(hr, "Failed to concatenate the dependency key name."); + DepExitOnFailure(hr, "Failed to concatenate the dependency key name."); LExit: return hr; @@ -656,13 +671,13 @@ static HRESULT GetDependencyNameFromKey( // Format the provider dependency registry key. hr = AllocDependencyKeyName(wzProviderKey, &sczKey); - ExitOnFailure(hr, "Failed to allocate the registry key for dependency \"%ls\".", wzProviderKey); + DepExitOnFailure(hr, "Failed to allocate the registry key for dependency \"%ls\".", wzProviderKey); // Try to open the dependency key. hr = RegOpen(hkHive, sczKey, KEY_READ, &hkKey); if (E_FILENOTFOUND != hr) { - ExitOnFailure(hr, "Failed to open the registry key for the dependency \"%ls\".", wzProviderKey); + DepExitOnFailure(hr, "Failed to open the registry key for the dependency \"%ls\".", wzProviderKey); } else { @@ -673,7 +688,7 @@ static HRESULT GetDependencyNameFromKey( hr = RegReadString(hkKey, vcszDisplayNameValue, psczName); if (E_FILENOTFOUND != hr) { - ExitOnFailure(hr, "Failed to get the dependency name for the dependency \"%ls\".", wzProviderKey); + DepExitOnFailure(hr, "Failed to get the dependency name for the dependency \"%ls\".", wzProviderKey); } else { diff --git a/src/dutil/dictutil.cpp b/src/dutil/dictutil.cpp index 1f0f9e43..0d0743eb 100644 --- a/src/dutil/dictutil.cpp +++ b/src/dutil/dictutil.cpp @@ -2,6 +2,21 @@ #include "precomp.h" + +// Exit macros +#define DictExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_DICTUTIL, x, s, __VA_ARGS__) +#define DictExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_DICTUTIL, x, s, __VA_ARGS__) +#define DictExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_DICTUTIL, x, s, __VA_ARGS__) +#define DictExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_DICTUTIL, x, s, __VA_ARGS__) +#define DictExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_DICTUTIL, x, s, __VA_ARGS__) +#define DictExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_DICTUTIL, x, s, __VA_ARGS__) +#define DictExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_DICTUTIL, p, x, e, s, __VA_ARGS__) +#define DictExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_DICTUTIL, p, x, s, __VA_ARGS__) +#define DictExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_DICTUTIL, p, x, e, s, __VA_ARGS__) +#define DictExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_DICTUTIL, p, x, s, __VA_ARGS__) +#define DictExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_DICTUTIL, e, x, s, __VA_ARGS__) +#define DictExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_DICTUTIL, g, x, s, __VA_ARGS__) + // These should all be primes, and spaced reasonably apart (currently each is about 4x the last) const DWORD MAX_BUCKET_SIZES[] = { 503, @@ -61,7 +76,7 @@ static HRESULT StringHash( __in const STRINGDICT_STRUCT *psd, __in DWORD dwNumBuckets, __in_z LPCWSTR pszString, - __out LPDWORD pdwHash + __out DWORD *pdwHash ); static BOOL IsMatchExact( __in const STRINGDICT_STRUCT *psd, @@ -122,11 +137,11 @@ extern "C" HRESULT DAPI DictCreateWithEmbeddedKey( { HRESULT hr = S_OK; - ExitOnNull(psdHandle, hr, E_INVALIDARG, "Handle not specified while creating dict"); + DictExitOnNull(psdHandle, hr, E_INVALIDARG, "Handle not specified while creating dict"); // Allocate the handle *psdHandle = static_cast(MemAlloc(sizeof(STRINGDICT_STRUCT), FALSE)); - ExitOnNull(*psdHandle, hr, E_OUTOFMEMORY, "Failed to allocate dictionary object"); + DictExitOnNull(*psdHandle, hr, E_OUTOFMEMORY, "Failed to allocate dictionary object"); STRINGDICT_STRUCT *psd = static_cast(*psdHandle); @@ -151,7 +166,7 @@ extern "C" HRESULT DAPI DictCreateWithEmbeddedKey( // Finally, allocate our initial buckets psd->ppvBuckets = static_cast(MemAlloc(sizeof(void *) * MAX_BUCKET_SIZES[psd->dwBucketSizeIndex], TRUE)); - ExitOnNull(psd->ppvBuckets, hr, E_OUTOFMEMORY, "Failed to allocate buckets for dictionary"); + DictExitOnNull(psd->ppvBuckets, hr, E_OUTOFMEMORY, "Failed to allocate buckets for dictionary"); LExit: return hr; @@ -166,11 +181,11 @@ extern "C" HRESULT DAPI DictCreateStringList( { HRESULT hr = S_OK; - ExitOnNull(psdHandle, hr, E_INVALIDARG, "Handle not specified while creating dict"); + DictExitOnNull(psdHandle, hr, E_INVALIDARG, "Handle not specified while creating dict"); // Allocate the handle *psdHandle = static_cast(MemAlloc(sizeof(STRINGDICT_STRUCT), FALSE)); - ExitOnNull(*psdHandle, hr, E_OUTOFMEMORY, "Failed to allocate dictionary object"); + DictExitOnNull(*psdHandle, hr, E_OUTOFMEMORY, "Failed to allocate dictionary object"); STRINGDICT_STRUCT *psd = static_cast(*psdHandle); @@ -195,7 +210,7 @@ extern "C" HRESULT DAPI DictCreateStringList( // Finally, allocate our initial buckets psd->ppvBuckets = static_cast(MemAlloc(sizeof(void *) * MAX_BUCKET_SIZES[psd->dwBucketSizeIndex], TRUE)); - ExitOnNull(psd->ppvBuckets, hr, E_OUTOFMEMORY, "Failed to allocate buckets for dictionary"); + DictExitOnNull(psd->ppvBuckets, hr, E_OUTOFMEMORY, "Failed to allocate buckets for dictionary"); LExit: return hr; @@ -212,7 +227,7 @@ extern "C" HRESULT DAPI DictCreateStringListFromArray( STRINGDICT_HANDLE sd = NULL; hr = DictCreateStringList(&sd, cStringArray, dfFlags); - ExitOnFailure(hr, "Failed to create the string dictionary."); + DictExitOnFailure(hr, "Failed to create the string dictionary."); for (DWORD i = 0; i < cStringArray; ++i) { @@ -221,12 +236,12 @@ extern "C" HRESULT DAPI DictCreateStringListFromArray( hr = DictKeyExists(sd, wzKey); if (E_NOTFOUND != hr) { - ExitOnFailure(hr, "Failed to check the string dictionary."); + DictExitOnFailure(hr, "Failed to check the string dictionary."); } else { hr = DictAddKey(sd, wzKey); - ExitOnFailure(hr, "Failed to add \"%ls\" to the string dictionary.", wzKey); + DictExitOnFailure(hr, "Failed to add \"%ls\" to the string dictionary.", wzKey); } } @@ -252,7 +267,7 @@ extern "C" HRESULT DAPI DictCompareStringListToArray( hr = DictKeyExists(sdStringList, rgwzStringArray[i]); if (E_NOTFOUND != hr) { - ExitOnFailure(hr, "Failed to check the string dictionary."); + DictExitOnFailure(hr, "Failed to check the string dictionary."); ExitFunction1(hr = S_OK); } } @@ -273,19 +288,19 @@ extern "C" HRESULT DAPI DictAddKey( DWORD dwIndex = 0; STRINGDICT_STRUCT *psd = static_cast(sdHandle); - ExitOnNull(sdHandle, hr, E_INVALIDARG, "Handle not specified while adding value to dict"); - ExitOnNull(pszString, hr, E_INVALIDARG, "String not specified while adding value to dict"); + DictExitOnNull(sdHandle, hr, E_INVALIDARG, "Handle not specified while adding value to dict"); + DictExitOnNull(pszString, hr, E_INVALIDARG, "String not specified while adding value to dict"); if (psd->dwBucketSizeIndex >= countof(MAX_BUCKET_SIZES)) { hr = E_INVALIDARG; - ExitOnFailure(hr, "Invalid dictionary - bucket size index is out of range"); + DictExitOnFailure(hr, "Invalid dictionary - bucket size index is out of range"); } if (DICT_STRING_LIST != psd->dtType) { hr = E_INVALIDARG; - ExitOnFailure(hr, "Tried to add key without value to wrong dictionary type! This dictionary type is: %d", psd->dtType); + DictExitOnFailure(hr, "Tried to add key without value to wrong dictionary type! This dictionary type is: %d", psd->dtType); } if ((psd->dwNumItems + 1) >= MAX_BUCKET_SIZES[psd->dwBucketSizeIndex] / MAX_BUCKETS_TO_ITEMS_RATIO) @@ -299,18 +314,18 @@ extern "C" HRESULT DAPI DictAddKey( hr = S_OK; } } - ExitOnFailure(hr, "Failed to grow dictionary"); + DictExitOnFailure(hr, "Failed to grow dictionary"); } hr = GetInsertIndex(psd, MAX_BUCKET_SIZES[psd->dwBucketSizeIndex], psd->ppvBuckets, pszString, &dwIndex); - ExitOnFailure(hr, "Failed to get index to insert into"); + DictExitOnFailure(hr, "Failed to get index to insert into"); hr = MemEnsureArraySize(reinterpret_cast(&(psd->ppvItemList)), psd->dwNumItems + 1, sizeof(void *), 1000); - ExitOnFailure(hr, "Failed to resize list of items in dictionary"); + DictExitOnFailure(hr, "Failed to resize list of items in dictionary"); ++psd->dwNumItems; hr = StrAllocString(reinterpret_cast(&(psd->ppvBuckets[dwIndex])), pszString, 0); - ExitOnFailure(hr, "Failed to allocate copy of string"); + DictExitOnFailure(hr, "Failed to allocate copy of string"); psd->ppvItemList[psd->dwNumItems-1] = psd->ppvBuckets[dwIndex]; @@ -330,23 +345,23 @@ extern "C" HRESULT DAPI DictAddValue( DWORD dwIndex = 0; STRINGDICT_STRUCT *psd = static_cast(sdHandle); - ExitOnNull(sdHandle, hr, E_INVALIDARG, "Handle not specified while adding value to dict"); - ExitOnNull(pvValue, hr, E_INVALIDARG, "Value not specified while adding value to dict"); + DictExitOnNull(sdHandle, hr, E_INVALIDARG, "Handle not specified while adding value to dict"); + DictExitOnNull(pvValue, hr, E_INVALIDARG, "Value not specified while adding value to dict"); if (psd->dwBucketSizeIndex >= countof(MAX_BUCKET_SIZES)) { hr = E_INVALIDARG; - ExitOnFailure(hr, "Invalid dictionary - bucket size index is out of range"); + DictExitOnFailure(hr, "Invalid dictionary - bucket size index is out of range"); } if (DICT_EMBEDDED_KEY != psd->dtType) { hr = E_INVALIDARG; - ExitOnFailure(hr, "Tried to add key/value pair to wrong dictionary type! This dictionary type is: %d", psd->dtType); + DictExitOnFailure(hr, "Tried to add key/value pair to wrong dictionary type! This dictionary type is: %d", psd->dtType); } wzKey = GetKey(psd, pvValue); - ExitOnNull(wzKey, hr, E_INVALIDARG, "String not specified while adding value to dict"); + DictExitOnNull(wzKey, hr, E_INVALIDARG, "String not specified while adding value to dict"); if ((psd->dwNumItems + 1) >= MAX_BUCKET_SIZES[psd->dwBucketSizeIndex] / MAX_BUCKETS_TO_ITEMS_RATIO) { @@ -359,14 +374,14 @@ extern "C" HRESULT DAPI DictAddValue( hr = S_OK; } } - ExitOnFailure(hr, "Failed to grow dictionary"); + DictExitOnFailure(hr, "Failed to grow dictionary"); } hr = GetInsertIndex(psd, MAX_BUCKET_SIZES[psd->dwBucketSizeIndex], psd->ppvBuckets, wzKey, &dwIndex); - ExitOnFailure(hr, "Failed to get index to insert into"); + DictExitOnFailure(hr, "Failed to get index to insert into"); hr = MemEnsureArraySize(reinterpret_cast(&(psd->ppvItemList)), psd->dwNumItems + 1, sizeof(void *), 1000); - ExitOnFailure(hr, "Failed to resize list of items in dictionary"); + DictExitOnFailure(hr, "Failed to resize list of items in dictionary"); ++psd->dwNumItems; pvOffset = TranslateValueToOffset(psd, pvValue); @@ -385,15 +400,15 @@ extern "C" HRESULT DAPI DictGetValue( { HRESULT hr = S_OK; - ExitOnNull(sdHandle, hr, E_INVALIDARG, "Handle not specified while searching dict"); - ExitOnNull(pszString, hr, E_INVALIDARG, "String not specified while searching dict"); + DictExitOnNull(sdHandle, hr, E_INVALIDARG, "Handle not specified while searching dict"); + DictExitOnNull(pszString, hr, E_INVALIDARG, "String not specified while searching dict"); const STRINGDICT_STRUCT *psd = static_cast(sdHandle); if (DICT_EMBEDDED_KEY != psd->dtType) { hr = E_INVALIDARG; - ExitOnFailure(hr, "Tried to lookup value in wrong dictionary type! This dictionary type is: %d", psd->dtType); + DictExitOnFailure(hr, "Tried to lookup value in wrong dictionary type! This dictionary type is: %d", psd->dtType); } hr = GetValue(psd, pszString, ppvValue); @@ -401,7 +416,7 @@ extern "C" HRESULT DAPI DictGetValue( { ExitFunction(); } - ExitOnFailure(hr, "Failed to call internal GetValue()"); + DictExitOnFailure(hr, "Failed to call internal GetValue()"); LExit: return hr; @@ -414,8 +429,8 @@ extern "C" HRESULT DAPI DictKeyExists( { HRESULT hr = S_OK; - ExitOnNull(sdHandle, hr, E_INVALIDARG, "Handle not specified while searching dict"); - ExitOnNull(pszString, hr, E_INVALIDARG, "String not specified while searching dict"); + DictExitOnNull(sdHandle, hr, E_INVALIDARG, "Handle not specified while searching dict"); + DictExitOnNull(pszString, hr, E_INVALIDARG, "String not specified while searching dict"); const STRINGDICT_STRUCT *psd = static_cast(sdHandle); @@ -425,7 +440,7 @@ extern "C" HRESULT DAPI DictKeyExists( { ExitFunction(); } - ExitOnFailure(hr, "Failed to call internal GetValue()"); + DictExitOnFailure(hr, "Failed to call internal GetValue()"); LExit: return hr; @@ -467,7 +482,7 @@ static HRESULT StringHash( if (DICT_FLAG_CASEINSENSITIVE & psd->dfFlags) { hr = StrAllocStringToUpperInvariant(&sczNewKey, pszString, 0); - ExitOnFailure(hr, "Failed to convert the string to upper-case."); + DictExitOnFailure(hr, "Failed to convert the string to upper-case."); wzKey = sczNewKey; } @@ -522,17 +537,17 @@ static HRESULT GetValue( void *pvCandidateValue = NULL; DWORD dwIndex = 0; - ExitOnNull(psd, hr, E_INVALIDARG, "Handle not specified while searching dict"); - ExitOnNull(pszString, hr, E_INVALIDARG, "String not specified while searching dict"); + DictExitOnNull(psd, hr, E_INVALIDARG, "Handle not specified while searching dict"); + DictExitOnNull(pszString, hr, E_INVALIDARG, "String not specified while searching dict"); if (psd->dwBucketSizeIndex >= countof(MAX_BUCKET_SIZES)) { hr = E_INVALIDARG; - ExitOnFailure(hr, "Invalid dictionary - bucket size index is out of range"); + DictExitOnFailure(hr, "Invalid dictionary - bucket size index is out of range"); } hr = StringHash(psd, MAX_BUCKET_SIZES[psd->dwBucketSizeIndex], pszString, &dwOriginalIndexCandidate); - ExitOnFailure(hr, "Failed to hash the string."); + DictExitOnFailure(hr, "Failed to hash the string."); DWORD dwIndexCandidate = dwOriginalIndexCandidate; @@ -553,7 +568,7 @@ static HRESULT GetValue( { ExitFunction(); } - ExitOnFailure(hr, "Failed to find index to get"); + DictExitOnFailure(hr, "Failed to find index to get"); if (NULL != ppvValue) { @@ -581,7 +596,7 @@ static HRESULT GetInsertIndex( DWORD dwOriginalIndexCandidate = 0; hr = StringHash(psd, dwBucketCount, pszString, &dwOriginalIndexCandidate); - ExitOnFailure(hr, "Failed to hash the string."); + DictExitOnFailure(hr, "Failed to hash the string."); DWORD dwIndexCandidate = dwOriginalIndexCandidate; @@ -604,7 +619,7 @@ static HRESULT GetInsertIndex( { // The dict table is full - this error seems to be a reasonably close match hr = HRESULT_FROM_WIN32(ERROR_DATABASE_FULL); - ExitOnRootFailure(hr, "Failed to add item '%ls' to dict table because dict table is full of items", pszString); + DictExitOnRootFailure(hr, "Failed to add item '%ls' to dict table because dict table is full of items", pszString); } } @@ -626,11 +641,11 @@ static HRESULT GetIndex( if (psd->dwBucketSizeIndex >= countof(MAX_BUCKET_SIZES)) { hr = E_INVALIDARG; - ExitOnFailure(hr, "Invalid dictionary - bucket size index is out of range"); + DictExitOnFailure(hr, "Invalid dictionary - bucket size index is out of range"); } hr = StringHash(psd, MAX_BUCKET_SIZES[psd->dwBucketSizeIndex], pszString, &dwOriginalIndexCandidate); - ExitOnFailure(hr, "Failed to hash the string."); + DictExitOnFailure(hr, "Failed to hash the string."); DWORD dwIndexCandidate = dwOriginalIndexCandidate; @@ -704,18 +719,18 @@ static HRESULT GrowDictionary( } hr = ::SizeTMult(sizeof(void *), MAX_BUCKET_SIZES[dwNewBucketSizeIndex], &cbAllocSize); - ExitOnFailure(hr, "Overflow while calculating allocation size to grow dictionary"); + DictExitOnFailure(hr, "Overflow while calculating allocation size to grow dictionary"); ppvNewBuckets = static_cast(MemAlloc(cbAllocSize, TRUE)); - ExitOnNull(ppvNewBuckets, hr, E_OUTOFMEMORY, "Failed to allocate %u buckets while growing dictionary", MAX_BUCKET_SIZES[dwNewBucketSizeIndex]); + DictExitOnNull(ppvNewBuckets, hr, E_OUTOFMEMORY, "Failed to allocate %u buckets while growing dictionary", MAX_BUCKET_SIZES[dwNewBucketSizeIndex]); for (DWORD i = 0; i < psd->dwNumItems; ++i) { wzKey = GetKey(psd, TranslateOffsetToValue(psd, psd->ppvItemList[i])); - ExitOnNull(wzKey, hr, E_INVALIDARG, "String not specified in existing dict value"); + DictExitOnNull(wzKey, hr, E_INVALIDARG, "String not specified in existing dict value"); hr = GetInsertIndex(psd, MAX_BUCKET_SIZES[dwNewBucketSizeIndex], ppvNewBuckets, wzKey, &dwInsertIndex); - ExitOnFailure(hr, "Failed to get index to insert into"); + DictExitOnFailure(hr, "Failed to get index to insert into"); ppvNewBuckets[dwInsertIndex] = psd->ppvItemList[i]; } diff --git a/src/dutil/dirutil.cpp b/src/dutil/dirutil.cpp index 5e22ee65..81130a8d 100644 --- a/src/dutil/dirutil.cpp +++ b/src/dutil/dirutil.cpp @@ -3,6 +3,21 @@ #include "precomp.h" +// Exit macros +#define DirExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_DIRUTIL, x, s, __VA_ARGS__) +#define DirExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_DIRUTIL, x, s, __VA_ARGS__) +#define DirExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_DIRUTIL, x, s, __VA_ARGS__) +#define DirExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_DIRUTIL, x, s, __VA_ARGS__) +#define DirExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_DIRUTIL, x, s, __VA_ARGS__) +#define DirExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_DIRUTIL, x, s, __VA_ARGS__) +#define DirExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_DIRUTIL, p, x, e, s, __VA_ARGS__) +#define DirExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_DIRUTIL, p, x, s, __VA_ARGS__) +#define DirExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_DIRUTIL, p, x, e, s, __VA_ARGS__) +#define DirExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_DIRUTIL, p, x, s, __VA_ARGS__) +#define DirExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_DIRUTIL, e, x, s, __VA_ARGS__) +#define DirExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_DIRUTIL, g, x, s, __VA_ARGS__) + + /******************************************************************* DirExists @@ -59,12 +74,12 @@ extern "C" HRESULT DAPI DirCreateTempPath( cch = ::GetTempPathW(countof(wzDir), wzDir); if (!cch || cch >= countof(wzDir)) { - ExitWithLastError(hr, "Failed to GetTempPath."); + DirExitWithLastError(hr, "Failed to GetTempPath."); } if (!::GetTempFileNameW(wzDir, wzPrefix, 0, wzFile)) { - ExitWithLastError(hr, "Failed to GetTempFileName."); + DirExitWithLastError(hr, "Failed to GetTempFileName."); } hr = ::StringCchCopyW(wzPath, cchPath, wzFile); @@ -111,12 +126,12 @@ extern "C" HRESULT DAPI DirEnsureExists( } // if there is no parent directory fail - ExitOnNullDebugTrace(pwzLastSlash, hr, HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND), "cannot find parent path"); + DirExitOnNullDebugTrace(pwzLastSlash, hr, HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND), "cannot find parent path"); *pwzLastSlash = L'\0'; // null terminate the parent path hr = DirEnsureExists(wzPath, psa); // recurse! *pwzLastSlash = L'\\'; // put the slash back - ExitOnFailureDebugTrace(hr, "failed to create path: %ls", wzPath); + DirExitOnFailureDebugTrace(hr, "failed to create path: %ls", wzPath); // try to create the directory now that all parents are created if (!::CreateDirectoryW(wzPath, psa)) @@ -197,7 +212,7 @@ extern "C" HRESULT DAPI DirEnsureDeleteEx( er = ERROR_PATH_NOT_FOUND; } hr = HRESULT_FROM_WIN32(er); - ExitOnRootFailure(hr, "Failed to get attributes for path: %ls", wzPath); + DirExitOnRootFailure(hr, "Failed to get attributes for path: %ls", wzPath); } if (dwAttrib & FILE_ATTRIBUTE_DIRECTORY) @@ -206,7 +221,7 @@ extern "C" HRESULT DAPI DirEnsureDeleteEx( { if (!::SetFileAttributesW(wzPath, FILE_ATTRIBUTE_NORMAL)) { - ExitWithLastError(hr, "Failed to remove read-only attribute from path: %ls", wzPath); + DirExitWithLastError(hr, "Failed to remove read-only attribute from path: %ls", wzPath); } } @@ -217,18 +232,18 @@ extern "C" HRESULT DAPI DirEnsureDeleteEx( { if (!::GetTempPathW(countof(wzTempDirectory), wzTempDirectory)) { - ExitWithLastError(hr, "Failed to get temp directory."); + DirExitWithLastError(hr, "Failed to get temp directory."); } } // Delete everything in this directory. hr = PathConcat(wzPath, L"*.*", &sczDelete); - ExitOnFailure(hr, "Failed to concat wild cards to string: %ls", wzPath); + DirExitOnFailure(hr, "Failed to concat wild cards to string: %ls", wzPath); hFind = ::FindFirstFileW(sczDelete, &wfd); if (INVALID_HANDLE_VALUE == hFind) { - ExitWithLastError(hr, "failed to get first file in directory: %ls", wzPath); + DirExitWithLastError(hr, "failed to get first file in directory: %ls", wzPath); } do @@ -243,18 +258,18 @@ extern "C" HRESULT DAPI DirEnsureDeleteEx( wfd.cFileName[MAX_PATH - 1] = L'\0'; hr = PathConcat(wzPath, wfd.cFileName, &sczDelete); - ExitOnFailure(hr, "Failed to concat filename '%ls' to directory: %ls", wfd.cFileName, wzPath); + DirExitOnFailure(hr, "Failed to concat filename '%ls' to directory: %ls", wfd.cFileName, wzPath); if (fRecurse && wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { hr = PathBackslashTerminate(&sczDelete); - ExitOnFailure(hr, "Failed to ensure path is backslash terminated: %ls", sczDelete); + DirExitOnFailure(hr, "Failed to ensure path is backslash terminated: %ls", sczDelete); hr = DirEnsureDeleteEx(sczDelete, dwFlags); // recursive call if (FAILED(hr)) { // if we failed to delete a subdirectory, keep trying to finish any remaining files - ExitTraceSource(DUTIL_SOURCE_DEFAULT, hr, "Failed to delete subdirectory; continuing: %ls", sczDelete); + ExitTraceSource(DUTIL_SOURCE_DIRUTIL, hr, "Failed to delete subdirectory; continuing: %ls", sczDelete); hr = S_OK; } } @@ -264,7 +279,7 @@ extern "C" HRESULT DAPI DirEnsureDeleteEx( { if (!::SetFileAttributesW(sczDelete, FILE_ATTRIBUTE_NORMAL)) { - ExitWithLastError(hr, "Failed to remove attributes from file: %ls", sczDelete); + DirExitWithLastError(hr, "Failed to remove attributes from file: %ls", sczDelete); } } @@ -274,7 +289,7 @@ extern "C" HRESULT DAPI DirEnsureDeleteEx( { if (!::GetTempFileNameW(wzTempDirectory, L"DEL", 0, wzTempPath)) { - ExitWithLastError(hr, "Failed to get temp file to move to."); + DirExitWithLastError(hr, "Failed to get temp file to move to."); } // Try to move the file to the temp directory then schedule for delete, @@ -290,7 +305,7 @@ extern "C" HRESULT DAPI DirEnsureDeleteEx( } else { - ExitWithLastError(hr, "Failed to delete file: %ls", sczDelete); + DirExitWithLastError(hr, "Failed to delete file: %ls", sczDelete); } } } @@ -303,7 +318,7 @@ extern "C" HRESULT DAPI DirEnsureDeleteEx( } else { - ExitWithLastError(hr, "Failed while looping through files in directory: %ls", wzPath); + DirExitWithLastError(hr, "Failed while looping through files in directory: %ls", wzPath); } } @@ -318,13 +333,13 @@ extern "C" HRESULT DAPI DirEnsureDeleteEx( } } - ExitOnRootFailure(hr, "Failed to remove directory: %ls", wzPath); + DirExitOnRootFailure(hr, "Failed to remove directory: %ls", wzPath); } } else { hr = E_UNEXPECTED; - ExitOnFailure(hr, "Directory delete cannot delete file: %ls", wzPath); + DirExitOnFailure(hr, "Directory delete cannot delete file: %ls", wzPath); } Assert(S_OK == hr); @@ -351,22 +366,22 @@ extern "C" HRESULT DAPI DirGetCurrent( if (psczCurrentDirectory && *psczCurrentDirectory) { hr = StrMaxLength(*psczCurrentDirectory, &cch); - ExitOnFailure(hr, "Failed to determine size of current directory."); + DirExitOnFailure(hr, "Failed to determine size of current directory."); } DWORD cchRequired = ::GetCurrentDirectoryW(static_cast(cch), 0 == cch ? NULL : *psczCurrentDirectory); if (0 == cchRequired) { - ExitWithLastError(hr, "Failed to get current directory."); + DirExitWithLastError(hr, "Failed to get current directory."); } else if (cch < cchRequired) { hr = StrAlloc(psczCurrentDirectory, cchRequired); - ExitOnFailure(hr, "Failed to allocate string for current directory."); + DirExitOnFailure(hr, "Failed to allocate string for current directory."); if (!::GetCurrentDirectoryW(cchRequired, *psczCurrentDirectory)) { - ExitWithLastError(hr, "Failed to get current directory using allocated string."); + DirExitWithLastError(hr, "Failed to get current directory using allocated string."); } } @@ -387,7 +402,7 @@ extern "C" HRESULT DAPI DirSetCurrent( if (!::SetCurrentDirectoryW(wzDirectory)) { - ExitWithLastError(hr, "Failed to set current directory to: %ls", wzDirectory); + DirExitWithLastError(hr, "Failed to set current directory to: %ls", wzDirectory); } LExit: diff --git a/src/dutil/dlutil.cpp b/src/dutil/dlutil.cpp index 1b30f410..70155e6f 100644 --- a/src/dutil/dlutil.cpp +++ b/src/dutil/dlutil.cpp @@ -5,6 +5,21 @@ #include #include + +// Exit macros +#define DlExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_DLUTIL, x, s, __VA_ARGS__) +#define DlExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_DLUTIL, x, s, __VA_ARGS__) +#define DlExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_DLUTIL, x, s, __VA_ARGS__) +#define DlExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_DLUTIL, x, s, __VA_ARGS__) +#define DlExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_DLUTIL, x, s, __VA_ARGS__) +#define DlExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_DLUTIL, x, s, __VA_ARGS__) +#define DlExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_DLUTIL, p, x, e, s, __VA_ARGS__) +#define DlExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_DLUTIL, p, x, s, __VA_ARGS__) +#define DlExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_DLUTIL, p, x, e, s, __VA_ARGS__) +#define DlExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_DLUTIL, p, x, s, __VA_ARGS__) +#define DlExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_DLUTIL, e, x, s, __VA_ARGS__) +#define DlExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_DLUTIL, g, x, s, __VA_ARGS__) + static const DWORD64 DOWNLOAD_ENGINE_TWO_GIGABYTES = DWORD64(2) * 1024 * 1024 * 1024; static LPCWSTR DOWNLOAD_ENGINE_ACCEPT_TYPES[] = { L"*/*", NULL }; @@ -41,7 +56,7 @@ static HRESULT DownloadResource( static HRESULT AllocateRangeRequestHeader( __in DWORD64 dw64ResumeOffset, __in DWORD64 dw64ResourceLength, - __deref_out_z LPWSTR* psczHeader + __deref_inout_z LPWSTR* psczHeader ); static HRESULT WriteToFile( __in HINTERNET hUrl, @@ -126,10 +141,10 @@ extern "C" HRESULT DAPI DownloadUrl( // Copy the download source into a working variable to handle redirects then // open the internet session. hr = StrAllocString(&sczUrl, pDownloadSource->sczUrl, 0); - ExitOnFailure(hr, "Failed to copy download source URL."); + DlExitOnFailure(hr, "Failed to copy download source URL."); hSession = ::InternetOpenW(L"Burn", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); - ExitOnNullWithLastError(hSession, hr, "Failed to open internet session"); + DlExitOnNullWithLastError(hSession, hr, "Failed to open internet session"); // Make a best effort to set the download timeouts to 2 minutes or whatever policy says. PolcReadNumber(POLICY_BURN_REGISTRY_PATH, L"DownloadTimeout", 2 * 60, &dwTimeout); @@ -143,14 +158,14 @@ extern "C" HRESULT DAPI DownloadUrl( // Get the resource size and creation time from the internet. hr = GetResourceMetadata(hSession, &sczUrl, pDownloadSource->sczUser, pDownloadSource->sczPassword, pAuthenticate, &dw64Size, &ftCreated); - ExitOnFailure(hr, "Failed to get size and time for URL: %ls", sczUrl); + DlExitOnFailure(hr, "Failed to get size and time for URL: %ls", sczUrl); // Ignore failure to initialize resume because we will fall back to full download then // download. InitializeResume(wzDestinationPath, &sczResumePath, &hResumeFile, &dw64ResumeOffset); hr = DownloadResource(hSession, &sczUrl, pDownloadSource->sczUser, pDownloadSource->sczPassword, wzDestinationPath, dw64AuthoredDownloadSize, dw64Size, dw64ResumeOffset, hResumeFile, pCache, pAuthenticate); - ExitOnFailure(hr, "Failed to download URL: %ls", sczUrl); + DlExitOnFailure(hr, "Failed to download URL: %ls", sczUrl); // Cleanup the resume file because we successfully downloaded the whole file. if (sczResumePath && *sczResumePath) @@ -185,19 +200,19 @@ static HRESULT InitializeResume( *pdw64ResumeOffset = 0; hr = DownloadGetResumePath(wzDestinationPath, psczResumePath); - ExitOnFailure(hr, "Failed to calculate resume path from working path: %ls", wzDestinationPath); + DlExitOnFailure(hr, "Failed to calculate resume path from working path: %ls", wzDestinationPath); hResumeFile = ::CreateFileW(*psczResumePath, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_DELETE, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (INVALID_HANDLE_VALUE == hResumeFile) { - ExitWithLastError(hr, "Failed to create resume file: %ls", *psczResumePath); + DlExitWithLastError(hr, "Failed to create resume file: %ls", *psczResumePath); } do { if (!::ReadFile(hResumeFile, reinterpret_cast(pdw64ResumeOffset) + cbTotalReadResumeData, sizeof(DWORD64) - cbTotalReadResumeData, &cbReadData, NULL)) { - ExitWithLastError(hr, "Failed to read resume file: %ls", *psczResumePath); + DlExitWithLastError(hr, "Failed to read resume file: %ls", *psczResumePath); } cbTotalReadResumeData += cbReadData; } while (cbReadData && sizeof(DWORD64) > cbTotalReadResumeData); @@ -233,7 +248,7 @@ static HRESULT GetResourceMetadata( LONGLONG llLength = 0; hr = MakeRequest(hSession, psczUrl, L"HEAD", NULL, wzUser, wzPassword, pAuthenticate, &hConnect, &hUrl, &fRangeRequestsAccepted); - ExitOnFailure(hr, "Failed to connect to URL: %ls", *psczUrl); + DlExitOnFailure(hr, "Failed to connect to URL: %ls", *psczUrl); hr = InternetGetSizeByHandle(hUrl, &llLength); if (FAILED(hr)) @@ -286,12 +301,12 @@ static HRESULT DownloadResource( hPayloadFile = ::CreateFileW(wzDestinationPath, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_DELETE, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (INVALID_HANDLE_VALUE == hPayloadFile) { - ExitWithLastError(hr, "Failed to create download destination file: %ls", wzDestinationPath); + DlExitWithLastError(hr, "Failed to create download destination file: %ls", wzDestinationPath); } // Allocate a memory block on a page boundary in case we want to do optimal writing. pbData = static_cast(::VirtualAlloc(NULL, cbMaxData, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); - ExitOnNullWithLastError(pbData, hr, "Failed to allocate buffer to download files into."); + DlExitOnNullWithLastError(pbData, hr, "Failed to allocate buffer to download files into."); // Let's try downloading the file assuming that range requests are accepted. If range requests // are not supported we'll have to start over and accept the fact that we only get one shot @@ -300,13 +315,13 @@ static HRESULT DownloadResource( while (fRangeRequestsAccepted && (0 == dw64ResourceLength || dw64ResumeOffset < dw64ResourceLength)) { hr = AllocateRangeRequestHeader(dw64ResumeOffset, 0 == dw64ResourceLength ? dw64AuthoredResourceLength : dw64ResourceLength, &sczRangeRequestHeader); - ExitOnFailure(hr, "Failed to allocate range request header."); + DlExitOnFailure(hr, "Failed to allocate range request header."); ReleaseNullInternet(hConnect); ReleaseNullInternet(hUrl); hr = MakeRequest(hSession, psczUrl, L"GET", sczRangeRequestHeader, wzUser, wzPassword, pAuthenticate, &hConnect, &hUrl, &fRangeRequestsAccepted); - ExitOnFailure(hr, "Failed to request URL for download: %ls", *psczUrl); + DlExitOnFailure(hr, "Failed to request URL for download: %ls", *psczUrl); // If we didn't get the size of the resource from the initial "HEAD" request // then let's try to get the size from this "GET" request. @@ -335,7 +350,7 @@ static HRESULT DownloadResource( } hr = WriteToFile(hUrl, hPayloadFile, &dw64ResumeOffset, hResumeFile, dw64ResourceLength, pbData, cbMaxData, pCache); - ExitOnFailure(hr, "Failed while reading from internet and writing to: %ls", wzDestinationPath); + DlExitOnFailure(hr, "Failed while reading from internet and writing to: %ls", wzDestinationPath); } LExit: @@ -354,7 +369,7 @@ LExit: static HRESULT AllocateRangeRequestHeader( __in DWORD64 dw64ResumeOffset, __in DWORD64 dw64ResourceLength, - __deref_out_z LPWSTR* psczHeader + __deref_inout_z LPWSTR* psczHeader ) { HRESULT hr = S_OK; @@ -368,7 +383,7 @@ static HRESULT AllocateRangeRequestHeader( if (0 < dw64ResumeOffset) { hr = StrAllocFormatted(psczHeader, L"Range: bytes=%I64u-", dw64ResumeOffset); - ExitOnFailure(hr, "Failed to add range read header."); + DlExitOnFailure(hr, "Failed to add range read header."); } else { @@ -378,7 +393,7 @@ static HRESULT AllocateRangeRequestHeader( else // we'll have to download in chunks. { hr = StrAllocFormatted(psczHeader, L"Range: bytes=%I64u-%I64u", dw64ResumeOffset, dw64ResumeOffset + dw64RemainingLength - 1); - ExitOnFailure(hr, "Failed to add range read header."); + DlExitOnFailure(hr, "Failed to add range read header."); } LExit: @@ -400,14 +415,14 @@ static HRESULT WriteToFile( DWORD cbReadData = 0; hr = FileSetPointer(hPayloadFile, *pdw64ResumeOffset, NULL, FILE_BEGIN); - ExitOnFailure(hr, "Failed to seek to start point in file."); + DlExitOnFailure(hr, "Failed to seek to start point in file."); do { // Read bits from the internet. if (!::InternetReadFile(hUrl, static_cast(pbData), cbData, &cbReadData)) { - ExitWithLastError(hr, "Failed while reading from internet."); + DlExitWithLastError(hr, "Failed while reading from internet."); } // Write bits to disk (if there are any). @@ -419,7 +434,7 @@ static HRESULT WriteToFile( { if (!::WriteFile(hPayloadFile, pbData + cbTotalWritten, cbReadData - cbTotalWritten, &cbWritten, NULL)) { - ExitWithLastError(hr, "Failed to write data from internet."); + DlExitWithLastError(hr, "Failed to write data from internet."); } cbTotalWritten += cbWritten; @@ -431,7 +446,7 @@ static HRESULT WriteToFile( if (pCallback && pCallback->pfnProgress) { hr = DownloadSendProgressCallback(pCallback, *pdw64ResumeOffset, dw64ResourceLength, hPayloadFile); - ExitOnFailure(hr, "UX aborted on cache progress."); + DlExitOnFailure(hr, "UX aborted on cache progress."); } } } while (cbReadData); @@ -456,14 +471,14 @@ static HRESULT UpdateResumeOffset( DWORD cbWrittenResumeData = 0; hr = FileSetPointer(hResumeFile, 0, NULL, FILE_BEGIN); - ExitOnFailure(hr, "Failed to seek to start point in file."); + DlExitOnFailure(hr, "Failed to seek to start point in file."); do { // Ignore failure to write to the resume file as that should not prevent the download from happening. if (!::WriteFile(hResumeFile, pdw64ResumeOffset + cbTotalWrittenResumeData, sizeof(DWORD64) - cbTotalWrittenResumeData, &cbWrittenResumeData, NULL)) { - ExitOnFailure(hr, "Failed to seek to write to file."); + DlExitOnFailure(hr, "Failed to seek to write to file."); } cbTotalWrittenResumeData += cbWrittenResumeData; @@ -504,10 +519,10 @@ static HRESULT MakeRequest( // Open the url. hr = UriCrackEx(*psczSourceUrl, &uri); - ExitOnFailure(hr, "Failed to break URL into server and resource parts."); + DlExitOnFailure(hr, "Failed to break URL into server and resource parts."); hConnect = ::InternetConnectW(hSession, uri.sczHostName, uri.port, (wzUser && *wzUser) ? wzUser : uri.sczUser, (wzPassword && *wzPassword) ? wzPassword : uri.sczPassword, INTERNET_SCHEME_FTP == uri.scheme ? INTERNET_SERVICE_FTP : INTERNET_SERVICE_HTTP, 0, 0); - ExitOnNullWithLastError(hConnect, hr, "Failed to connect to URL: %ls", *psczSourceUrl); + DlExitOnNullWithLastError(hConnect, hr, "Failed to connect to URL: %ls", *psczSourceUrl); // Best effort set the proxy username and password, if they were provided. if ((wzUser && *wzUser) && (wzPassword && *wzPassword)) @@ -519,10 +534,10 @@ static HRESULT MakeRequest( } hr = OpenRequest(hConnect, wzMethod, uri.scheme, uri.sczPath, uri.sczQueryString, wzHeaders, &hUrl); - ExitOnFailure(hr, "Failed to open internet URL: %ls", *psczSourceUrl); + DlExitOnFailure(hr, "Failed to open internet URL: %ls", *psczSourceUrl); hr = SendRequest(hUrl, psczSourceUrl, pAuthenticate, &fRetry, pfRangeRequestsAccepted); - ExitOnFailure(hr, "Failed to send request to URL: %ls", *psczSourceUrl); + DlExitOnFailure(hr, "Failed to send request to URL: %ls", *psczSourceUrl); } while (fRetry); // Okay, we're all ready to start downloading. Update the connection information. @@ -565,23 +580,23 @@ static HRESULT OpenRequest( // Allocate the resource name. hr = StrAllocString(&sczResource, wzResource, 0); - ExitOnFailure(hr, "Failed to allocate string for resource URI."); + DlExitOnFailure(hr, "Failed to allocate string for resource URI."); if (wzQueryString && *wzQueryString) { hr = StrAllocConcat(&sczResource, wzQueryString, 0); - ExitOnFailure(hr, "Failed to append query strong to resource from URI."); + DlExitOnFailure(hr, "Failed to append query strong to resource from URI."); } // Open the request and add the header if provided. hUrl = ::HttpOpenRequestW(hConnect, wzMethod, sczResource, NULL, NULL, DOWNLOAD_ENGINE_ACCEPT_TYPES, dwRequestFlags, NULL); - ExitOnNullWithLastError(hUrl, hr, "Failed to open internet request."); + DlExitOnNullWithLastError(hUrl, hr, "Failed to open internet request."); if (wzHeader && *wzHeader) { if (!::HttpAddRequestHeadersW(hUrl, wzHeader, static_cast(-1), HTTP_ADDREQ_FLAG_COALESCE)) { - ExitWithLastError(hr, "Failed to add header to HTTP request."); + DlExitWithLastError(hr, "Failed to add header to HTTP request."); } } @@ -618,12 +633,12 @@ static HRESULT SendRequest( // Try to get the HTTP status code and, if good, handle via the switch statement below but if it // fails return the error code from the send request above as the result of the function. HRESULT hrQueryStatusCode = InternetQueryInfoNumber(hUrl, HTTP_QUERY_STATUS_CODE, &lCode); - ExitOnFailure(hrQueryStatusCode, "Failed to get HTTP status code for failed request to URL: %ls", *psczUrl); + DlExitOnFailure(hrQueryStatusCode, "Failed to get HTTP status code for failed request to URL: %ls", *psczUrl); } else // get the http status code. { hr = InternetQueryInfoNumber(hUrl, HTTP_QUERY_STATUS_CODE, &lCode); - ExitOnFailure(hr, "Failed to get HTTP status code for request to URL: %ls", *psczUrl); + DlExitOnFailure(hr, "Failed to get HTTP status code for request to URL: %ls", *psczUrl); } switch (lCode) @@ -643,7 +658,7 @@ static HRESULT SendRequest( case 302: __fallthrough; // temporary case 303: // redirect method hr = InternetQueryInfoString(hUrl, HTTP_QUERY_CONTENT_LOCATION, psczUrl); - ExitOnFailure(hr, "Failed to get redirect url: %ls", *psczUrl); + DlExitOnFailure(hr, "Failed to get redirect url: %ls", *psczUrl); *pfRetry = TRUE; break; @@ -734,7 +749,7 @@ static HRESULT DownloadGetResumePath( HRESULT hr = S_OK; hr = StrAllocFormatted(psczResumePath, L"%ls.R", wzPayloadWorkingPath); - ExitOnFailure(hr, "Failed to create resume path."); + DlExitOnFailure(hr, "Failed to create resume path."); LExit: return hr; @@ -769,7 +784,7 @@ static HRESULT DownloadSendProgressCallback( case PROGRESS_CANCEL: __fallthrough; // TODO: should cancel and stop be treated differently? case PROGRESS_STOP: hr = HRESULT_FROM_WIN32(ERROR_INSTALL_USEREXIT); - ExitOnRootFailure(hr, "UX aborted on download progress."); + DlExitOnRootFailure(hr, "UX aborted on download progress."); case PROGRESS_QUIET: // Not actually an error, just an indication to the caller to stop requesting progress. pCallback->pfnProgress = NULL; @@ -778,7 +793,7 @@ static HRESULT DownloadSendProgressCallback( default: hr = E_UNEXPECTED; - ExitOnRootFailure(hr, "Invalid return code from progress routine."); + DlExitOnRootFailure(hr, "Invalid return code from progress routine."); } } diff --git a/src/dutil/dutil.cpp b/src/dutil/dutil.cpp index 99ce1bc6..c500191a 100644 --- a/src/dutil/dutil.cpp +++ b/src/dutil/dutil.cpp @@ -2,6 +2,21 @@ #include "precomp.h" + +// Exit macros +#define DExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_DUTIL, x, s, __VA_ARGS__) +#define DExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_DUTIL, x, s, __VA_ARGS__) +#define DExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_DUTIL, x, s, __VA_ARGS__) +#define DExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_DUTIL, x, s, __VA_ARGS__) +#define DExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_DUTIL, x, s, __VA_ARGS__) +#define DExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_DUTIL, x, s, __VA_ARGS__) +#define DExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_DUTIL, p, x, e, s, __VA_ARGS__) +#define DExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_DUTIL, p, x, s, __VA_ARGS__) +#define DExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_DUTIL, p, x, e, s, __VA_ARGS__) +#define DExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_DUTIL, p, x, s, __VA_ARGS__) +#define DExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_DUTIL, e, x, s, __VA_ARGS__) +#define DExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_DUTIL, g, x, s, __VA_ARGS__) + // No need for OACR to warn us about using non-unicode APIs in this file. #pragma prefast(disable:25068) @@ -84,7 +99,7 @@ extern "C" void DAPI Dutil_AssertMsg( char szMsg[DUTIL_STRING_BUFFER]; hr = ::StringCchCopyA(szMsg, countof(szMsg), szMessage); - ExitOnFailure(hr, "failed to copy message while building assert message"); + DExitOnFailure(hr, "failed to copy message while building assert message"); if (Dutil_pfnDisplayAssert) { @@ -123,7 +138,7 @@ extern "C" void DAPI Dutil_AssertMsg( if (ERROR_SUCCESS != er) { hr = ::StringCchCatA(szMsg, countof(szMsg), "\nAbort=Debug, Retry=Skip, Ignore=Skip all"); - ExitOnFailure(hr, "failed to concat string while building assert message"); + DExitOnFailure(hr, "failed to concat string while building assert message"); id = ::MessageBoxA(0, szMsg, "Debug Assert Message", MB_SERVICE_NOTIFICATION | MB_TOPMOST | @@ -480,24 +495,24 @@ extern "C" HRESULT DAPI LoadSystemLibraryWithPath( WCHAR wzPath[MAX_PATH] = { }; cch = ::GetSystemDirectoryW(wzPath, MAX_PATH); - ExitOnNullWithLastError(cch, hr, "Failed to get the Windows system directory."); + DExitOnNullWithLastError(cch, hr, "Failed to get the Windows system directory."); if (L'\\' != wzPath[cch - 1]) { hr = ::StringCchCatNW(wzPath, MAX_PATH, L"\\", 1); - ExitOnRootFailure(hr, "Failed to terminate the string with a backslash."); + DExitOnRootFailure(hr, "Failed to terminate the string with a backslash."); } hr = ::StringCchCatW(wzPath, MAX_PATH, wzModuleName); - ExitOnRootFailure(hr, "Failed to create the fully-qualified path to %ls.", wzModuleName); + DExitOnRootFailure(hr, "Failed to create the fully-qualified path to %ls.", wzModuleName); *phModule = ::LoadLibraryW(wzPath); - ExitOnNullWithLastError(*phModule, hr, "Failed to load the library %ls.", wzModuleName); + DExitOnNullWithLastError(*phModule, hr, "Failed to load the library %ls.", wzModuleName); if (psczPath) { hr = StrAllocString(psczPath, wzPath, MAX_PATH); - ExitOnFailure(hr, "Failed to copy the path to library."); + DExitOnFailure(hr, "Failed to copy the path to library."); } LExit: diff --git a/src/dutil/eseutil.cpp b/src/dutil/eseutil.cpp index 599a3943..d2bd7dc5 100644 --- a/src/dutil/eseutil.cpp +++ b/src/dutil/eseutil.cpp @@ -2,6 +2,21 @@ #include "precomp.h" + +// Exit macros +#define EseExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_ESEUTIL, x, s, __VA_ARGS__) +#define EseExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_ESEUTIL, x, s, __VA_ARGS__) +#define EseExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_ESEUTIL, x, s, __VA_ARGS__) +#define EseExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_ESEUTIL, x, s, __VA_ARGS__) +#define EseExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_ESEUTIL, x, s, __VA_ARGS__) +#define EseExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_ESEUTIL, x, s, __VA_ARGS__) +#define EseExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_ESEUTIL, p, x, e, s, __VA_ARGS__) +#define EseExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_ESEUTIL, p, x, s, __VA_ARGS__) +#define EseExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_ESEUTIL, p, x, e, s, __VA_ARGS__) +#define EseExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_ESEUTIL, p, x, s, __VA_ARGS__) +#define EseExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_ESEUTIL, e, x, s, __VA_ARGS__) +#define EseExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_ESEUTIL, g, x, s, __VA_ARGS__) + struct ESE_QUERY { ESE_QUERY_TYPE qtQueryType; @@ -85,13 +100,13 @@ HRESULT HresultFromJetError(JET_ERR jEr) } // Log the actual Jet error code so we have record of it before it's morphed into an HRESULT to be compatible with the rest of our code - ExitTraceSource(DUTIL_SOURCE_DEFAULT, hr, "Encountered Jet Error: 0x%08x", jEr); + ExitTraceSource(DUTIL_SOURCE_ESEUTIL, hr, "Encountered Jet Error: 0x%08x", jEr); return hr; } -#define ExitOnJetFailure(e, x, s, ...) { x = HresultFromJetError(e); if (S_OK != x) { ExitTraceSource(DUTIL_SOURCE_DEFAULT, x, s, __VA_ARGS__); goto LExit; }} -#define ExitOnRootJetFailure(e, x, s, ...) { x = HresultFromJetError(e); if (S_OK != x) { Dutil_RootFailure(__FILE__, __LINE__, x); ExitTraceSource(DUTIL_SOURCE_DEFAULT, x, s, __VA_ARGS__); goto LExit; }} +#define ExitOnJetFailure(e, x, s, ...) { x = HresultFromJetError(e); if (S_OK != x) { ExitTraceSource(DUTIL_SOURCE_ESEUTIL, x, s, __VA_ARGS__); goto LExit; }} +#define ExitOnRootJetFailure(e, x, s, ...) { x = HresultFromJetError(e); if (S_OK != x) { Dutil_RootFailure(__FILE__, __LINE__, x); ExitTraceSource(DUTIL_SOURCE_ESEUTIL, x, s, __VA_ARGS__); goto LExit; }} HRESULT DAPI EseBeginSession( __out JET_INSTANCE *pjiInstance, @@ -106,15 +121,15 @@ HRESULT DAPI EseBeginSession( LPSTR pszAnsiPath = NULL; hr = DirEnsureExists(pszPath, NULL); - ExitOnFailure(hr, "Failed to ensure database directory exists"); + EseExitOnFailure(hr, "Failed to ensure database directory exists"); // Sigh. JETblue requires Vista and up for the wide character version of this function, so we'll convert to ANSI before calling, // likely breaking everyone with unicode characters in their path. hr = StrAnsiAllocString(&pszAnsiInstance, pszInstance, 0, CP_ACP); - ExitOnFailure(hr, "Failed converting instance name to ansi"); + EseExitOnFailure(hr, "Failed converting instance name to ansi"); hr = StrAnsiAllocString(&pszAnsiPath, pszPath, 0, CP_ACP); - ExitOnFailure(hr, "Failed converting session path name to ansi"); + EseExitOnFailure(hr, "Failed converting session path name to ansi"); jEr = JetCreateInstanceA(pjiInstance, pszAnsiInstance); ExitOnJetFailure(jEr, hr, "Failed to create instance"); @@ -173,17 +188,17 @@ HRESULT AllocColumnCreateStruct( size_t cbAllocSize = 0; hr = ::SizeTMult(ptsSchema->dwColumns, sizeof(JET_COLUMNCREATE), &(cbAllocSize)); - ExitOnFailure(hr, "Maximum allocation exceeded."); + EseExitOnFailure(hr, "Maximum allocation exceeded."); *ppjccColumnCreate = static_cast(MemAlloc(cbAllocSize, TRUE)); - ExitOnNull(*ppjccColumnCreate, hr, E_OUTOFMEMORY, "Failed to allocate column create structure for database"); + EseExitOnNull(*ppjccColumnCreate, hr, E_OUTOFMEMORY, "Failed to allocate column create structure for database"); for (i = 0; i < ptsSchema->dwColumns; ++i) { (*ppjccColumnCreate)[i].cbStruct = sizeof(JET_COLUMNCREATE); hr = StrAnsiAllocString(&(*ppjccColumnCreate)[i].szColumnName, ptsSchema->pcsColumns[i].pszName, 0, CP_ACP); - ExitOnFailure(hr, "Failed to allocate ansi column name: %ls", ptsSchema->pcsColumns[i].pszName); + EseExitOnFailure(hr, "Failed to allocate ansi column name: %ls", ptsSchema->pcsColumns[i].pszName); (*ppjccColumnCreate)[i].coltyp = ptsSchema->pcsColumns[i].jcColumnType; @@ -237,7 +252,7 @@ HRESULT FreeColumnCreateStruct( } hr = MemFree(pjccColumnCreate); - ExitOnFailure(hr, "Failed to release core column create struct"); + EseExitOnFailure(hr, "Failed to release core column create struct"); LExit: return hr; @@ -261,20 +276,20 @@ HRESULT AllocIndexCreateStruct( if (ptsSchema->pcsColumns[i].fKey) { hr = StrAnsiAllocString(&pszTempString, ptsSchema->pcsColumns[i].pszName, 0, CP_ACP); - ExitOnFailure(hr, "Failed to convert string to ansi: %ls", ptsSchema->pcsColumns[i].pszName); + EseExitOnFailure(hr, "Failed to convert string to ansi: %ls", ptsSchema->pcsColumns[i].pszName); hr = StrAnsiAllocConcat(&pszMultiSzKeys, "+", 0); - ExitOnFailure(hr, "Failed to append plus sign to multisz string: %s", pszTempString); + EseExitOnFailure(hr, "Failed to append plus sign to multisz string: %s", pszTempString); hr = StrAnsiAllocConcat(&pszMultiSzKeys, pszTempString, 0); - ExitOnFailure(hr, "Failed to append column name to multisz string: %s", pszTempString); + EseExitOnFailure(hr, "Failed to append column name to multisz string: %s", pszTempString); ReleaseNullStr(pszTempString); // All question marks will be converted to null characters later; this is just to trick dutil // into letting us create an ansi, double-null-terminated list of single-null-terminated strings hr = StrAnsiAllocConcat(&pszMultiSzKeys, "?", 0); - ExitOnFailure(hr, "Failed to append placeholder character to multisz string: %ls", pszMultiSzKeys); + EseExitOnFailure(hr, "Failed to append placeholder character to multisz string: %hs", pszMultiSzKeys); // Record that at least one key column was found fKeyColumns = TRUE; @@ -288,18 +303,18 @@ HRESULT AllocIndexCreateStruct( } hr = StrAnsiAllocString(&pszIndexName, ptsSchema->pszName, 0, CP_ACP); - ExitOnFailure(hr, "Failed to allocate ansi string version of %ls", ptsSchema->pszName); + EseExitOnFailure(hr, "Failed to allocate ansi string version of %ls", ptsSchema->pszName); hr = StrAnsiAllocConcat(&pszIndexName, "_Index", 0); - ExitOnFailure(hr, "Failed to append table name string version of %ls", ptsSchema->pszName); + EseExitOnFailure(hr, "Failed to append table name string version of %ls", ptsSchema->pszName); *ppjicIndexCreate = static_cast(MemAlloc(sizeof(JET_INDEXCREATE), TRUE)); - ExitOnNull(*ppjicIndexCreate, hr, E_OUTOFMEMORY, "Failed to allocate index create structure for database"); + EseExitOnNull(*ppjicIndexCreate, hr, E_OUTOFMEMORY, "Failed to allocate index create structure for database"); // Record the size including both null terminators - the struct requires this DWORD dwSize = 0; dwSize = lstrlen(pszMultiSzKeys) + 1; // add 1 to include null character at the end - ExitOnFailure(hr, "Failed to get size of keys string"); + EseExitOnFailure(hr, "Failed to get size of keys string"); // At this point convert all question marks to null characters for (i = 0; i < dwSize; ++i) @@ -349,7 +364,7 @@ HRESULT EnsureSchema( jtTableCreate.cIndexes = 1; hr = EseBeginTransaction(jsSession); - ExitOnFailure(hr, "Failed to begin transaction to create tables"); + EseExitOnFailure(hr, "Failed to begin transaction to create tables"); fTransaction = TRUE; for (dwTable = 0;dwTable < pdsSchema->dwTables; ++dwTable) @@ -363,13 +378,13 @@ HRESULT EnsureSchema( { // Fill out the JET_TABLECREATE struct hr = StrAnsiAllocString(&jtTableCreate.szTableName, pdsSchema->ptsTables[dwTable].pszName, 0, CP_ACP); - ExitOnFailure(hr, "Failed converting table name to ansi"); + EseExitOnFailure(hr, "Failed converting table name to ansi"); hr = AllocColumnCreateStruct(&(pdsSchema->ptsTables[dwTable]), &jtTableCreate.rgcolumncreate); - ExitOnFailure(hr, "Failed to allocate column create struct"); + EseExitOnFailure(hr, "Failed to allocate column create struct"); hr = AllocIndexCreateStruct(&(pdsSchema->ptsTables[dwTable]), &jtTableCreate.rgindexcreate); - ExitOnFailure(hr, "Failed to allocate index create struct"); + EseExitOnFailure(hr, "Failed to allocate index create struct"); jtTableCreate.cColumns = pdsSchema->ptsTables[dwTable].dwColumns; jtTableCreate.tableid = NULL; @@ -392,7 +407,7 @@ HRESULT EnsureSchema( ReleaseNullStr(jtTableCreate.szTableName); hr = FreeColumnCreateStruct(jtTableCreate.rgcolumncreate, jtTableCreate.cColumns); - ExitOnFailure(hr, "Failed to free column create struct"); + EseExitOnFailure(hr, "Failed to free column create struct"); jtTableCreate.rgcolumncreate = NULL; } else @@ -422,7 +437,7 @@ HRESULT EnsureSchema( } hr = EseEnsureColumn(jsSession, pdsSchema->ptsTables[dwTable].jtTable, pcsColumn->pszName, pcsColumn->jcColumnType, ulColumnSize, pcsColumn->fFixed, fNullable, &pcsColumn->jcColumn); - ExitOnFailure(hr, "Failed to create column %u of %ls table", dwColumn, pwzTableName); + EseExitOnFailure(hr, "Failed to create column %u of %ls table", dwColumn, pwzTableName); } } } @@ -464,13 +479,13 @@ HRESULT DAPI EseEnsureDatabase( // Sigh. JETblue requires Vista and up for the wide character version of this function, so we'll convert to ANSI before calling, // likely breaking all those with unicode characters in their path. hr = StrAnsiAllocString(&pszAnsiFile, pszFile, 0, CP_ACP); - ExitOnFailure(hr, "Failed converting database name to ansi"); + EseExitOnFailure(hr, "Failed converting database name to ansi"); hr = PathGetDirectory(pszFile, &pszDir); - ExitOnFailure(hr, "Failed to get directory that will contain database file"); + EseExitOnFailure(hr, "Failed to get directory that will contain database file"); hr = DirEnsureExists(pszDir, NULL); - ExitOnFailure(hr, "Failed to ensure directory exists for database: %ls", pszDir); + EseExitOnFailure(hr, "Failed to ensure directory exists for database: %ls", pszDir); if (FileExistsEx(pszFile, NULL)) { @@ -498,7 +513,7 @@ HRESULT DAPI EseEnsureDatabase( } hr = EnsureSchema(*pjdbDb, jsSession, pdsSchema); - ExitOnFailure(hr, "Failed to ensure database schema matches expectations"); + EseExitOnFailure(hr, "Failed to ensure database schema matches expectations"); LExit: ReleaseStr(pszDir); @@ -535,7 +550,7 @@ HRESULT DAPI EseCreateTable( LPSTR pszAnsiTable = NULL; hr = StrAnsiAllocString(&pszAnsiTable, pszTable, 0, CP_ACP); - ExitOnFailure(hr, "Failed converting table name to ansi"); + EseExitOnFailure(hr, "Failed converting table name to ansi"); jEr = JetCreateTableA(jsSession, jdbDb, pszAnsiTable, 100, 0, pjtTable); ExitOnJetFailure(jEr, hr, "Failed to create table %s", pszAnsiTable); @@ -558,7 +573,7 @@ HRESULT DAPI EseOpenTable( LPSTR pszAnsiTable = NULL; hr = StrAnsiAllocString(&pszAnsiTable, pszTable, 0, CP_ACP); - ExitOnFailure(hr, "Failed converting table name to ansi"); + EseExitOnFailure(hr, "Failed converting table name to ansi"); jEr = JetOpenTableA(jsSession, jdbDb, pszAnsiTable, NULL, 0, 0, pjtTable); ExitOnJetFailure(jEr, hr, "Failed to open table %s", pszAnsiTable); @@ -602,7 +617,7 @@ HRESULT DAPI EseEnsureColumn( JET_COLUMNBASE jcdTempBase = { sizeof(JET_COLUMNBASE) }; hr = StrAnsiAllocString(&pszAnsiColumnName, pszColumnName, 0, CP_ACP); - ExitOnFailure(hr, "Failed converting column name to ansi"); + EseExitOnFailure(hr, "Failed converting column name to ansi"); jEr = JetGetTableColumnInfoA(jsSession, jtTable, pszAnsiColumnName, &jcdTempBase, sizeof(JET_COLUMNBASE), JET_ColInfoBase); if (JET_errSuccess == jEr) @@ -661,7 +676,7 @@ HRESULT DAPI EseGetColumn( JET_COLUMNBASE jcdTempBase = { sizeof(JET_COLUMNBASE) }; hr = StrAnsiAllocString(&pszAnsiColumnName, pszColumnName, 0, CP_ACP); - ExitOnFailure(hr, "Failed converting column name to ansi"); + EseExitOnFailure(hr, "Failed converting column name to ansi"); jEr = JetGetTableColumnInfoA(jsSession, jtTable, pszAnsiColumnName, &jcdTempBase, sizeof(JET_COLUMNBASE), JET_ColInfoBase); if (JET_errSuccess == jEr) @@ -898,7 +913,7 @@ HRESULT DAPI EseGetColumnBinary( __in JET_SESID jsSession, __in ESE_TABLE_SCHEMA tsTable, __in DWORD dwColumn, - __deref_out_bcount(*piBuffer) BYTE** ppbBuffer, + __deref_inout_bcount(*piBuffer) BYTE** ppbBuffer, __inout SIZE_T* piBuffer ) { @@ -916,12 +931,12 @@ HRESULT DAPI EseGetColumnBinary( if (NULL == *ppbBuffer) { *ppbBuffer = reinterpret_cast(MemAlloc(ulActualSize, FALSE)); - ExitOnNull(*ppbBuffer, hr, E_OUTOFMEMORY, "Failed to allocate memory for reading binary value column"); + EseExitOnNull(*ppbBuffer, hr, E_OUTOFMEMORY, "Failed to allocate memory for reading binary value column"); } else { *ppbBuffer = reinterpret_cast(MemReAlloc(*ppbBuffer, ulActualSize, FALSE)); - ExitOnNull(*ppbBuffer, hr, E_OUTOFMEMORY, "Failed to reallocate memory for reading binary value column"); + EseExitOnNull(*ppbBuffer, hr, E_OUTOFMEMORY, "Failed to reallocate memory for reading binary value column"); } jEr = JetRetrieveColumn(jsSession, tsTable.jtTable, tsTable.pcsColumns[dwColumn].jcColumn, *ppbBuffer, ulActualSize, NULL, 0, NULL); @@ -1001,7 +1016,7 @@ HRESULT DAPI EseGetColumnString( ExitOnJetFailure(jEr, hr, "Failed to check size of string value from record"); hr = StrAlloc(ppszValue, ulActualSize); - ExitOnFailure(hr, "Failed to allocate string while retrieving column value"); + EseExitOnFailure(hr, "Failed to allocate string while retrieving column value"); jEr = JetRetrieveColumn(jsSession, tsTable.jtTable, tsTable.pcsColumns[dwColumn].jcColumn, *ppszValue, ulActualSize, NULL, 0, NULL); ExitOnJetFailure(jEr, hr, "Failed to retrieve string value from record"); @@ -1023,7 +1038,7 @@ HRESULT DAPI EseBeginQuery( HRESULT hr = S_OK; *peqhHandle = static_cast(MemAlloc(sizeof(ESE_QUERY), TRUE)); - ExitOnNull(*peqhHandle, hr, E_OUTOFMEMORY, "Failed to allocate new query"); + EseExitOnNull(*peqhHandle, hr, E_OUTOFMEMORY, "Failed to allocate new query"); ESE_QUERY *peqHandle = static_cast(*peqhHandle); peqHandle->qtQueryType = qtQueryType; @@ -1050,7 +1065,7 @@ HRESULT DAPI SetQueryColumn( if (peqHandle->dwColumns == countof(peqHandle->pvData)) { hr = E_NOTIMPL; - ExitOnFailure(hr, "Dutil hasn't implemented support for queries of more than %d columns", countof(peqHandle->pvData)); + EseExitOnFailure(hr, "Dutil hasn't implemented support for queries of more than %d columns", countof(peqHandle->pvData)); } if (0 == peqHandle->dwColumns) // If it's the first column, start a new key @@ -1065,7 +1080,7 @@ HRESULT DAPI SetQueryColumn( if (ESE_QUERY_EXACT != peqHandle->qtQueryType) { peqHandle->pvData[peqHandle->dwColumns] = MemAlloc(cbData, FALSE); - ExitOnNull(peqHandle->pvData[peqHandle->dwColumns], hr, E_OUTOFMEMORY, "Failed to allocate memory"); + EseExitOnNull(peqHandle->pvData[peqHandle->dwColumns], hr, E_OUTOFMEMORY, "Failed to allocate memory"); memcpy(peqHandle->pvData[peqHandle->dwColumns], pvData, cbData); @@ -1108,7 +1123,7 @@ HRESULT DAPI EseSetQueryColumnBinary( } hr = SetQueryColumn(eqhHandle, reinterpret_cast(pbBuffer), static_cast(cbBuffer), jGrb); - ExitOnFailure(hr, "Failed to set value of query colum (as binary) to:"); + EseExitOnFailure(hr, "Failed to set value of query colum (as binary) to:"); LExit: return hr; @@ -1137,7 +1152,7 @@ HRESULT DAPI EseSetQueryColumnDword( } hr = SetQueryColumn(eqhHandle, (const void *)&dwData, sizeof(DWORD), jGrb); - ExitOnFailure(hr, "Failed to set value of query colum (as dword) to: %u", dwData); + EseExitOnFailure(hr, "Failed to set value of query colum (as dword) to: %u", dwData); LExit: return hr; @@ -1167,7 +1182,7 @@ HRESULT DAPI EseSetQueryColumnBool( } hr = SetQueryColumn(eqhHandle, (const void *)&bByte, 1, jGrb); - ExitOnFailure(hr, "Failed to set value of query colum (as bool) to: %s", fValue ? "TRUE" : "FALSE"); + EseExitOnFailure(hr, "Failed to set value of query colum (as bool) to: %s", fValue ? "TRUE" : "FALSE"); LExit: return hr; @@ -1200,7 +1215,7 @@ HRESULT DAPI EseSetQueryColumnString( } hr = SetQueryColumn(eqhHandle, (const void *)pszString, dwStringSize, jGrb); - ExitOnFailure(hr, "Failed to set value of query colum (as string) to: %ls", pszString); + EseExitOnFailure(hr, "Failed to set value of query colum (as string) to: %ls", pszString); LExit: return hr; diff --git a/src/dutil/fileutil.cpp b/src/dutil/fileutil.cpp index 6191ec06..c76017de 100644 --- a/src/dutil/fileutil.cpp +++ b/src/dutil/fileutil.cpp @@ -2,6 +2,21 @@ #include "precomp.h" + +// Exit macros +#define FileExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_FILEUTIL, x, s, __VA_ARGS__) +#define FileExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_FILEUTIL, x, s, __VA_ARGS__) +#define FileExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_FILEUTIL, x, s, __VA_ARGS__) +#define FileExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_FILEUTIL, x, s, __VA_ARGS__) +#define FileExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_FILEUTIL, x, s, __VA_ARGS__) +#define FileExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_FILEUTIL, x, s, __VA_ARGS__) +#define FileExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_FILEUTIL, p, x, e, s, __VA_ARGS__) +#define FileExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_FILEUTIL, p, x, s, __VA_ARGS__) +#define FileExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_FILEUTIL, p, x, e, s, __VA_ARGS__) +#define FileExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_FILEUTIL, p, x, s, __VA_ARGS__) +#define FileExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_FILEUTIL, e, x, s, __VA_ARGS__) +#define FileExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_FILEUTIL, g, x, s, __VA_ARGS__) + // constants const BYTE UTF8BOM[] = {0xEF, 0xBB, 0xBF}; @@ -15,7 +30,7 @@ const LPCWSTR REGISTRY_PENDING_FILE_RENAME_VALUE = L"PendingFileRenameOperations ********************************************************************/ extern "C" LPWSTR DAPI FileFromPath( - __in LPCWSTR wzPath + __in_z LPCWSTR wzPath ) { if (!wzPath) @@ -42,7 +57,7 @@ extern "C" LPWSTR DAPI FileFromPath( ********************************************************************/ extern "C" HRESULT DAPI FileResolvePath( - __in LPCWSTR wzRelativePath, + __in_z LPCWSTR wzRelativePath, __out LPWSTR *ppwzFullPath ) { @@ -63,28 +78,28 @@ extern "C" HRESULT DAPI FileResolvePath( // cchExpandedPath = MAX_PATH; hr = StrAlloc(&pwzExpandedPath, cchExpandedPath); - ExitOnFailure(hr, "Failed to allocate space for expanded path."); + FileExitOnFailure(hr, "Failed to allocate space for expanded path."); cch = ::ExpandEnvironmentStringsW(wzRelativePath, pwzExpandedPath, cchExpandedPath); if (0 == cch) { - ExitWithLastError(hr, "Failed to expand environment variables in string: %ls", wzRelativePath); + FileExitWithLastError(hr, "Failed to expand environment variables in string: %ls", wzRelativePath); } else if (cchExpandedPath < cch) { cchExpandedPath = cch; hr = StrAlloc(&pwzExpandedPath, cchExpandedPath); - ExitOnFailure(hr, "Failed to re-allocate more space for expanded path."); + FileExitOnFailure(hr, "Failed to re-allocate more space for expanded path."); cch = ::ExpandEnvironmentStringsW(wzRelativePath, pwzExpandedPath, cchExpandedPath); if (0 == cch) { - ExitWithLastError(hr, "Failed to expand environment variables in string: %ls", wzRelativePath); + FileExitWithLastError(hr, "Failed to expand environment variables in string: %ls", wzRelativePath); } else if (cchExpandedPath < cch) { hr = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); - ExitOnRootFailure(hr, "Failed to allocate buffer for expanded path."); + FileExitOnRootFailure(hr, "Failed to allocate buffer for expanded path."); } } @@ -93,28 +108,28 @@ extern "C" HRESULT DAPI FileResolvePath( // cchFullPath = MAX_PATH; hr = StrAlloc(&pwzFullPath, cchFullPath); - ExitOnFailure(hr, "Failed to allocate space for full path."); + FileExitOnFailure(hr, "Failed to allocate space for full path."); cch = ::GetFullPathNameW(pwzExpandedPath, cchFullPath, pwzFullPath, &wzFileName); if (0 == cch) { - ExitWithLastError(hr, "Failed to get full path for string: %ls", pwzExpandedPath); + FileExitWithLastError(hr, "Failed to get full path for string: %ls", pwzExpandedPath); } else if (cchFullPath < cch) { cchFullPath = cch; hr = StrAlloc(&pwzFullPath, cchFullPath); - ExitOnFailure(hr, "Failed to re-allocate more space for full path."); + FileExitOnFailure(hr, "Failed to re-allocate more space for full path."); cch = ::GetFullPathNameW(pwzExpandedPath, cchFullPath, pwzFullPath, &wzFileName); if (0 == cch) { - ExitWithLastError(hr, "Failed to get full path for string: %ls", pwzExpandedPath); + FileExitWithLastError(hr, "Failed to get full path for string: %ls", pwzExpandedPath); } else if (cchFullPath < cch) { hr = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); - ExitOnRootFailure(hr, "Failed to allocate buffer for full path."); + FileExitOnRootFailure(hr, "Failed to allocate buffer for full path."); } } @@ -133,7 +148,7 @@ LExit: FileStripExtension - Strip extension from filename ********************************************************************/ extern "C" HRESULT DAPI FileStripExtension( -__in LPCWSTR wzFileName, +__in_z LPCWSTR wzFileName, __out LPWSTR *ppwzFileNameNoExtension ) { @@ -158,14 +173,14 @@ __out LPWSTR *ppwzFileNameNoExtension } hr = StrAlloc(&pwzFileNameNoExtension, cchFileNameNoExtension); - ExitOnFailure(hr, "failed to allocate space for File Name without extension"); + FileExitOnFailure(hr, "failed to allocate space for File Name without extension"); // _wsplitpath_s can handle drive/path/filename/extension errno_t err = _wsplitpath_s(wzFileName, NULL, NULL, NULL, NULL, pwzFileNameNoExtension, cchFileNameNoExtension, NULL, NULL); if (0 != err) { hr = E_INVALIDARG; - ExitOnFailure(hr, "failed to parse filename: %ls", wzFileName); + FileExitOnFailure(hr, "failed to parse filename: %ls", wzFileName); } *ppwzFileNameNoExtension = pwzFileNameNoExtension; @@ -182,8 +197,8 @@ LExit: FileChangeExtension - Changes the extension of a filename ********************************************************************/ extern "C" HRESULT DAPI FileChangeExtension( - __in LPCWSTR wzFileName, - __in LPCWSTR wzNewExtension, + __in_z LPCWSTR wzFileName, + __in_z LPCWSTR wzNewExtension, __out LPWSTR *ppwzFileNameNewExtension ) { @@ -193,10 +208,10 @@ extern "C" HRESULT DAPI FileChangeExtension( LPWSTR sczFileName = NULL; hr = FileStripExtension(wzFileName, &sczFileName); - ExitOnFailure(hr, "Failed to strip extension from file name: %ls", wzFileName); + FileExitOnFailure(hr, "Failed to strip extension from file name: %ls", wzFileName); hr = StrAllocConcat(&sczFileName, wzNewExtension, 0); - ExitOnFailure(hr, "Failed to add new extension."); + FileExitOnFailure(hr, "Failed to add new extension."); *ppwzFileNameNewExtension = sczFileName; sczFileName = NULL; @@ -238,11 +253,11 @@ extern "C" HRESULT DAPI FileAddSuffixToBaseName( { // no extension, so add the suffix at the end of the whole name hr = StrAllocString(&sczNewFileName, wzFileName, 0); - ExitOnFailure(hr, "Failed to allocate new file name."); + FileExitOnFailure(hr, "Failed to allocate new file name."); hr = StrAllocConcat(&sczNewFileName, wzSuffix, 0); } - ExitOnFailure(hr, "Failed to allocate new file name with suffix."); + FileExitOnFailure(hr, "Failed to allocate new file name with suffix."); *psczNewFileName = sczNewFileName; sczNewFileName = NULL; @@ -259,7 +274,7 @@ LExit: ********************************************************************/ extern "C" HRESULT DAPI FileVersion( - __in LPCWSTR wzFilename, + __in_z LPCWSTR wzFilename, __out DWORD *pdwVerMajor, __out DWORD* pdwVerMinor ) @@ -274,20 +289,20 @@ extern "C" HRESULT DAPI FileVersion( if (0 == (cbVerBuffer = ::GetFileVersionInfoSizeW(wzFilename, &dwHandle))) { - ExitOnLastErrorDebugTrace(hr, "failed to get version info for file: %ls", wzFilename); + FileExitOnLastErrorDebugTrace(hr, "failed to get version info for file: %ls", wzFilename); } pVerBuffer = ::GlobalAlloc(GMEM_FIXED, cbVerBuffer); - ExitOnNullDebugTrace(pVerBuffer, hr, E_OUTOFMEMORY, "failed to allocate version info for file: %ls", wzFilename); + FileExitOnNullDebugTrace(pVerBuffer, hr, E_OUTOFMEMORY, "failed to allocate version info for file: %ls", wzFilename); if (!::GetFileVersionInfoW(wzFilename, dwHandle, cbVerBuffer, pVerBuffer)) { - ExitOnLastErrorDebugTrace(hr, "failed to get version info for file: %ls", wzFilename); + FileExitOnLastErrorDebugTrace(hr, "failed to get version info for file: %ls", wzFilename); } if (!::VerQueryValueW(pVerBuffer, L"\\", (void**)&pvsFileInfo, &cbFileInfo)) { - ExitOnLastErrorDebugTrace(hr, "failed to get version value for file: %ls", wzFilename); + FileExitOnLastErrorDebugTrace(hr, "failed to get version value for file: %ls", wzFilename); } *pdwVerMajor = pvsFileInfo->dwFileVersionMS; @@ -307,7 +322,7 @@ LExit: *******************************************************************/ extern "C" HRESULT DAPI FileVersionFromString( - __in LPCWSTR wzVersion, + __in_z LPCWSTR wzVersion, __out DWORD* pdwVerMajor, __out DWORD* pdwVerMinor ) @@ -394,7 +409,7 @@ LExit: *******************************************************************/ extern "C" HRESULT DAPI FileVersionFromStringEx( - __in LPCWSTR wzVersion, + __in_z LPCWSTR wzVersion, __in DWORD cchVersion, __out DWORD64* pqwVersion ) @@ -453,11 +468,11 @@ extern "C" HRESULT DAPI FileVersionFromStringEx( DWORD cchPart; hr = ::PtrdiffTToDWord(wzPartEnd - wzPartBegin, &cchPart); - ExitOnFailure(hr, "Version number part was too long."); + FileExitOnFailure(hr, "Version number part was too long."); // parse version part hr = StrStringToUInt16(wzPartBegin, cchPart, &us); - ExitOnFailure(hr, "Failed to parse version number part."); + FileExitOnFailure(hr, "Failed to parse version number part."); // add part to qword version qwVersion |= (DWORD64)us << ((3 - iPart) * 16); @@ -501,7 +516,7 @@ extern "C" HRESULT DAPI FileVersionToStringEx( // Format and return the version string. hr = StrAllocFormatted(psczVersion, L"%u.%u.%u.%u", wMajor, wMinor, wBuild, wRevision); - ExitOnFailure(hr, "Failed to allocate and format the version number."); + FileExitOnFailure(hr, "Failed to allocate and format the version number."); LExit: return hr; @@ -527,7 +542,7 @@ extern "C" HRESULT DAPI FileSetPointer( liMove.QuadPart = dw64Move; if (!::SetFilePointerEx(hFile, liMove, &liNewPosition, dwMoveMethod)) { - ExitWithLastError(hr, "Failed to set file pointer."); + FileExitWithLastError(hr, "Failed to set file pointer."); } if (pdw64NewPosition) @@ -545,23 +560,23 @@ LExit: ********************************************************************/ extern "C" HRESULT DAPI FileSize( - __in LPCWSTR pwzFileName, + __in_z LPCWSTR pwzFileName, __out LONGLONG* pllSize ) { HRESULT hr = S_OK; HANDLE hFile = INVALID_HANDLE_VALUE; - ExitOnNull(pwzFileName, hr, E_INVALIDARG, "Attempted to check filename, but no filename was provided"); + FileExitOnNull(pwzFileName, hr, E_INVALIDARG, "Attempted to check filename, but no filename was provided"); hFile = ::CreateFileW(pwzFileName, FILE_READ_ATTRIBUTES, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if (INVALID_HANDLE_VALUE == hFile) { - ExitWithLastError(hr, "Failed to open file %ls while checking file size", pwzFileName); + FileExitWithLastError(hr, "Failed to open file %ls while checking file size", pwzFileName); } hr = FileSizeByHandle(hFile, pllSize); - ExitOnFailure(hr, "Failed to check size of file %ls by handle", pwzFileName); + FileExitOnFailure(hr, "Failed to check size of file %ls by handle", pwzFileName); LExit: ReleaseFileHandle(hFile); @@ -587,7 +602,7 @@ extern "C" HRESULT DAPI FileSizeByHandle( if (!::GetFileSizeEx(hFile, &li)) { - ExitWithLastError(hr, "Failed to get size of file."); + FileExitWithLastError(hr, "Failed to get size of file."); } *pllSize = li.QuadPart; @@ -602,7 +617,7 @@ LExit: ********************************************************************/ extern "C" BOOL DAPI FileExistsEx( - __in LPCWSTR wzPath, + __in_z LPCWSTR wzPath, __out_opt DWORD *pdwAttributes ) { @@ -655,14 +670,14 @@ extern "C" BOOL DAPI FileExistsAfterRestart( { ExitFunction1(hr = S_OK); } - ExitOnFailure(hr, "Failed to open pending file rename registry key."); + FileExitOnFailure(hr, "Failed to open pending file rename registry key."); hr = RegReadStringArray(hkPendingFileRename, REGISTRY_PENDING_FILE_RENAME_VALUE, &rgsczRenames, &cRenames); if (E_FILENOTFOUND == hr) { ExitFunction1(hr = S_OK); } - ExitOnFailure(hr, "Failed to read pending file renames."); + FileExitOnFailure(hr, "Failed to read pending file renames."); // The pending file renames array is pairs of source and target paths. We only care // about checking the source paths so skip the target paths (i += 2). @@ -678,7 +693,7 @@ extern "C" BOOL DAPI FileExistsAfterRestart( } hr = PathCompare(wzPath, wzRename, &nCompare); - ExitOnFailure(hr, "Failed to compare path from pending file rename to check path."); + FileExitOnFailure(hr, "Failed to compare path from pending file rename to check path."); if (CSTR_EQUAL == nCompare) { @@ -719,14 +734,14 @@ extern "C" HRESULT DAPI FileRemoveFromPendingRename( { ExitFunction1(hr = S_OK); } - ExitOnFailure(hr, "Failed to open pending file rename registry key."); + FileExitOnFailure(hr, "Failed to open pending file rename registry key."); hr = RegReadStringArray(hkPendingFileRename, REGISTRY_PENDING_FILE_RENAME_VALUE, &rgsczRenames, &cRenames); if (E_FILENOTFOUND == hr) { ExitFunction1(hr = S_OK); } - ExitOnFailure(hr, "Failed to read pending file renames."); + FileExitOnFailure(hr, "Failed to read pending file renames."); // The pending file renames array is pairs of source and target paths. We only care // about checking the source paths so skip the target paths (i += 2). @@ -742,7 +757,7 @@ extern "C" HRESULT DAPI FileRemoveFromPendingRename( } hr = PathCompare(wzPath, wzRename, &nCompare); - ExitOnFailure(hr, "Failed to compare path from pending file rename to check path."); + FileExitOnFailure(hr, "Failed to compare path from pending file rename to check path."); // If we find our path in the list, null out the source and target slot and // we'll compact the array next. @@ -772,7 +787,7 @@ extern "C" HRESULT DAPI FileRemoveFromPendingRename( // Write the new array back to the pending file rename key. hr = RegWriteStringArray(hkPendingFileRename, REGISTRY_PENDING_FILE_RENAME_VALUE, rgsczRenames, cRenames); - ExitOnFailure(hr, "Failed to update pending file renames."); + FileExitOnFailure(hr, "Failed to update pending file renames."); } LExit: @@ -790,7 +805,7 @@ LExit: extern "C" HRESULT DAPI FileRead( __deref_out_bcount_full(*pcbDest) LPBYTE* ppbDest, __out SIZE_T* pcbDest, - __in LPCWSTR wzSrcPath + __in_z LPCWSTR wzSrcPath ) { HRESULT hr = FileReadPartial(ppbDest, pcbDest, wzSrcPath, FALSE, 0, 0xFFFFFFFF, FALSE); @@ -819,7 +834,7 @@ extern "C" HRESULT DAPI FileReadEx( extern "C" HRESULT DAPI FileReadUntil( __deref_out_bcount_full(*pcbDest) LPBYTE* ppbDest, __out_range(<=, cbMaxRead) SIZE_T* pcbDest, - __in LPCWSTR wzSrcPath, + __in_z LPCWSTR wzSrcPath, __in DWORD cbMaxRead ) { @@ -835,7 +850,7 @@ extern "C" HRESULT DAPI FileReadUntil( extern "C" HRESULT DAPI FileReadPartial( __deref_out_bcount_full(*pcbDest) LPBYTE* ppbDest, __out_range(<=, cbMaxRead) SIZE_T* pcbDest, - __in LPCWSTR wzSrcPath, + __in_z LPCWSTR wzSrcPath, __in BOOL fSeek, __in DWORD cbStartPosition, __in DWORD cbMaxRead, @@ -850,7 +865,7 @@ extern "C" HRESULT DAPI FileReadPartial( (with specified share mode) ********************************************************************/ extern "C" HRESULT DAPI FileReadPartialEx( - __deref_out_bcount_full(*pcbDest) LPBYTE* ppbDest, + __deref_inout_bcount_full(*pcbDest) LPBYTE* ppbDest, __out_range(<=, cbMaxRead) SIZE_T* pcbDest, __in_z LPCWSTR wzSrcPath, __in BOOL fSeek, @@ -868,10 +883,10 @@ extern "C" HRESULT DAPI FileReadPartialEx( DWORD cbData = 0; BYTE* pbData = NULL; - ExitOnNull(pcbDest, hr, E_INVALIDARG, "Invalid argument pcbDest"); - ExitOnNull(ppbDest, hr, E_INVALIDARG, "Invalid argument ppbDest"); - ExitOnNull(wzSrcPath, hr, E_INVALIDARG, "Invalid argument wzSrcPath"); - ExitOnNull(*wzSrcPath, hr, E_INVALIDARG, "*wzSrcPath is null"); + FileExitOnNull(pcbDest, hr, E_INVALIDARG, "Invalid argument pcbDest"); + FileExitOnNull(ppbDest, hr, E_INVALIDARG, "Invalid argument ppbDest"); + FileExitOnNull(wzSrcPath, hr, E_INVALIDARG, "Invalid argument wzSrcPath"); + FileExitOnNull(*wzSrcPath, hr, E_INVALIDARG, "*wzSrcPath is null"); hFile = ::CreateFileW(wzSrcPath, GENERIC_READ, dwShareMode, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL); if (INVALID_HANDLE_VALUE == hFile) @@ -881,12 +896,12 @@ extern "C" HRESULT DAPI FileReadPartialEx( { ExitFunction1(hr = E_FILENOTFOUND); } - ExitOnWin32Error(er, hr, "Failed to open file: %ls", wzSrcPath); + FileExitOnWin32Error(er, hr, "Failed to open file: %ls", wzSrcPath); } if (!::GetFileSizeEx(hFile, &liFileSize)) { - ExitWithLastError(hr, "Failed to get size of file: %ls", wzSrcPath); + FileExitWithLastError(hr, "Failed to get size of file: %ls", wzSrcPath); } if (fSeek) @@ -894,13 +909,13 @@ extern "C" HRESULT DAPI FileReadPartialEx( if (cbStartPosition > liFileSize.QuadPart) { hr = E_INVALIDARG; - ExitOnFailure(hr, "Start position %d bigger than file '%ls' size %d", cbStartPosition, wzSrcPath, liFileSize.QuadPart); + FileExitOnFailure(hr, "Start position %d bigger than file '%ls' size %llu", cbStartPosition, wzSrcPath, liFileSize.QuadPart); } DWORD dwErr = ::SetFilePointer(hFile, cbStartPosition, NULL, FILE_CURRENT); if (INVALID_SET_FILE_POINTER == dwErr) { - ExitOnLastError(hr, "Failed to seek position %d", cbStartPosition); + FileExitOnLastError(hr, "Failed to seek position %d", cbStartPosition); } } else @@ -918,7 +933,7 @@ extern "C" HRESULT DAPI FileReadPartialEx( if (cbMaxRead < liFileSize.QuadPart - cbStartPosition) { hr = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); - ExitOnRootFailure(hr, "Failed to load file: %ls, too large.", wzSrcPath); + FileExitOnRootFailure(hr, "Failed to load file: %ls, too large.", wzSrcPath); } } @@ -932,7 +947,7 @@ extern "C" HRESULT DAPI FileReadPartialEx( } LPVOID pv = MemReAlloc(*ppbDest, cbData, TRUE); - ExitOnNull(pv, hr, E_OUTOFMEMORY, "Failed to re-allocate memory to read in file: %ls", wzSrcPath); + FileExitOnNull(pv, hr, E_OUTOFMEMORY, "Failed to re-allocate memory to read in file: %ls", wzSrcPath); pbData = static_cast(pv); } @@ -945,7 +960,7 @@ extern "C" HRESULT DAPI FileReadPartialEx( } pbData = static_cast(MemAlloc(cbData, TRUE)); - ExitOnNull(pbData, hr, E_OUTOFMEMORY, "Failed to allocate memory to read in file: %ls", wzSrcPath); + FileExitOnNull(pbData, hr, E_OUTOFMEMORY, "Failed to allocate memory to read in file: %ls", wzSrcPath); } DWORD cbTotalRead = 0; @@ -954,11 +969,11 @@ extern "C" HRESULT DAPI FileReadPartialEx( { DWORD cbRemaining = 0; hr = ::ULongSub(cbData, cbTotalRead, &cbRemaining); - ExitOnFailure(hr, "Underflow calculating remaining buffer size."); + FileExitOnFailure(hr, "Underflow calculating remaining buffer size."); if (!::ReadFile(hFile, pbData + cbTotalRead, cbRemaining, &cbRead, NULL)) { - ExitWithLastError(hr, "Failed to read from file: %ls", wzSrcPath); + FileExitWithLastError(hr, "Failed to read from file: %ls", wzSrcPath); } cbTotalRead += cbRead; @@ -967,7 +982,7 @@ extern "C" HRESULT DAPI FileReadPartialEx( if (cbTotalRead != cbData) { hr = E_UNEXPECTED; - ExitOnFailure(hr, "Failed to completely read file: %ls", wzSrcPath); + FileExitOnFailure(hr, "Failed to completely read file: %ls", wzSrcPath); } *ppbDest = pbData; @@ -999,10 +1014,10 @@ extern "C" HRESULT DAPI FileWrite( // Open the file hFile = ::CreateFileW(pwzFileName, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, dwFlagsAndAttributes, NULL); - ExitOnInvalidHandleWithLastError(hFile, hr, "Failed to open file: %ls", pwzFileName); + FileExitOnInvalidHandleWithLastError(hFile, hr, "Failed to open file: %ls", pwzFileName); hr = FileWriteHandle(hFile, pbData, cbData); - ExitOnFailure(hr, "Failed to write to file: %ls", pwzFileName); + FileExitOnFailure(hr, "Failed to write to file: %ls", pwzFileName); if (pHandle) { @@ -1036,7 +1051,7 @@ extern "C" HRESULT DAPI FileWriteHandle( { if (!::WriteFile(hFile, pbData + cbTotal, (DWORD)(cbData - cbTotal), &cbDataWritten, NULL)) { - ExitOnLastError(hr, "Failed to write data to file handle."); + FileExitOnLastError(hr, "Failed to write data to file handle."); } cbTotal += cbDataWritten; @@ -1068,13 +1083,13 @@ extern "C" HRESULT DAPI FileCopyUsingHandles( cbRead = static_cast((0 == cbCopy) ? countof(rgbData) : min(countof(rgbData), cbCopy - cbTotalCopied)); if (!::ReadFile(hSource, rgbData, cbRead, &cbRead, NULL)) { - ExitWithLastError(hr, "Failed to read from source."); + FileExitWithLastError(hr, "Failed to read from source."); } if (cbRead) { hr = FileWriteHandle(hTarget, rgbData, cbRead); - ExitOnFailure(hr, "Failed to write to target."); + FileExitOnFailure(hr, "Failed to write to target."); } cbTotalCopied += cbRead; @@ -1095,8 +1110,8 @@ LExit: *******************************************************************/ extern "C" HRESULT DAPI FileEnsureCopy( - __in LPCWSTR wzSource, - __in LPCWSTR wzTarget, + __in_z LPCWSTR wzSource, + __in_z LPCWSTR wzTarget, __in BOOL fOverwrite ) { @@ -1132,12 +1147,12 @@ extern "C" HRESULT DAPI FileEnsureCopy( *pwzLastSlash = L'\0'; // null terminate hr = DirEnsureExists(wzTarget, NULL); *pwzLastSlash = L'\\'; // now put the slash back - ExitOnFailureDebugTrace(hr, "failed to create directory while copying file: '%ls' to: '%ls'", wzSource, wzTarget); + FileExitOnFailureDebugTrace(hr, "failed to create directory while copying file: '%ls' to: '%ls'", wzSource, wzTarget); // try to copy again if (!::CopyFileW(wzSource, wzTarget, fOverwrite)) { - ExitOnLastErrorDebugTrace(hr, "failed to copy file: '%ls' to: '%ls'", wzSource, wzTarget); + FileExitOnLastErrorDebugTrace(hr, "failed to copy file: '%ls' to: '%ls'", wzSource, wzTarget); } } else // no path was specified so just return the error @@ -1186,7 +1201,7 @@ extern "C" HRESULT DAPI FileEnsureCopyWithRetry( break; // no reason to retry these errors. } } - ExitOnFailure(hr, "Failed to copy file: '%ls' to: '%ls' after %u retries.", wzSource, wzTarget, i); + FileExitOnFailure(hr, "Failed to copy file: '%ls' to: '%ls' after %u retries.", wzSource, wzTarget, i); LExit: return hr; @@ -1198,8 +1213,8 @@ LExit: *******************************************************************/ extern "C" HRESULT DAPI FileEnsureMove( - __in LPCWSTR wzSource, - __in LPCWSTR wzTarget, + __in_z LPCWSTR wzSource, + __in_z LPCWSTR wzTarget, __in BOOL fOverwrite, __in BOOL fAllowCopy ) @@ -1260,12 +1275,12 @@ extern "C" HRESULT DAPI FileEnsureMove( *pwzLastSlash = L'\0'; // null terminate hr = DirEnsureExists(wzTarget, NULL); *pwzLastSlash = L'\\'; // now put the slash back - ExitOnFailureDebugTrace(hr, "failed to create directory while moving file: '%ls' to: '%ls'", wzSource, wzTarget); + FileExitOnFailureDebugTrace(hr, "failed to create directory while moving file: '%ls' to: '%ls'", wzSource, wzTarget); // try to move again if (!::MoveFileExW(wzSource, wzTarget, dwFlags)) { - ExitOnLastErrorDebugTrace(hr, "failed to move file: '%ls' to: '%ls'", wzSource, wzTarget); + FileExitOnLastErrorDebugTrace(hr, "failed to move file: '%ls' to: '%ls'", wzSource, wzTarget); } } else // no path was specified so just return the error @@ -1310,7 +1325,7 @@ extern "C" HRESULT DAPI FileEnsureMoveWithRetry( hr = FileEnsureMove(wzSource, wzTarget, fOverwrite, fAllowCopy); } - ExitOnFailure(hr, "Failed to move file: '%ls' to: '%ls' after %u retries.", wzSource, wzTarget, i); + FileExitOnFailure(hr, "Failed to move file: '%ls' to: '%ls' after %u retries.", wzSource, wzTarget, i); LExit: return hr; @@ -1323,8 +1338,8 @@ LExit: NOTE: uses ANSI functions internally so it is Win9x safe ********************************************************************/ extern "C" HRESULT DAPI FileCreateTemp( - __in LPCWSTR wzPrefix, - __in LPCWSTR wzExtension, + __in_z LPCWSTR wzPrefix, + __in_z LPCWSTR wzExtension, __deref_opt_out_z LPWSTR* ppwzTempFile, __out_opt HANDLE* phTempFile ) @@ -1340,13 +1355,13 @@ extern "C" HRESULT DAPI FileCreateTemp( int i = 0; hr = StrAnsiAlloc(&pszTempPath, cchTempPath); - ExitOnFailure(hr, "failed to allocate memory for the temp path"); + FileExitOnFailure(hr, "failed to allocate memory for the temp path"); ::GetTempPathA(cchTempPath, pszTempPath); for (i = 0; i < 1000 && INVALID_HANDLE_VALUE == hTempFile; ++i) { hr = StrAnsiAllocFormatted(&pszTempFile, "%s%ls%05d.%ls", pszTempPath, wzPrefix, i, wzExtension); - ExitOnFailure(hr, "failed to allocate memory for log file"); + FileExitOnFailure(hr, "failed to allocate memory for log file"); hTempFile = ::CreateFileA(pszTempFile, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL); if (INVALID_HANDLE_VALUE == hTempFile) @@ -1358,7 +1373,7 @@ extern "C" HRESULT DAPI FileCreateTemp( hr = S_OK; continue; } - ExitOnFailureDebugTrace(hr, "failed to create file: %ls", pszTempFile); + FileExitOnFailureDebugTrace(hr, "failed to create file: %hs", pszTempFile); } } @@ -1387,8 +1402,8 @@ LExit: *******************************************************************/ extern "C" HRESULT DAPI FileCreateTempW( - __in LPCWSTR wzPrefix, - __in LPCWSTR wzExtension, + __in_z LPCWSTR wzPrefix, + __in_z LPCWSTR wzExtension, __deref_opt_out_z LPWSTR* ppwzTempFile, __out_opt HANDLE* phTempFile ) @@ -1405,13 +1420,13 @@ extern "C" HRESULT DAPI FileCreateTempW( if (!::GetTempPathW(cchTempPath, wzTempPath)) { - ExitOnLastError(hr, "failed to get temp path"); + FileExitOnLastError(hr, "failed to get temp path"); } for (i = 0; i < 1000 && INVALID_HANDLE_VALUE == hTempFile; ++i) { hr = StrAllocFormatted(&pwzTempFile, L"%s%s%05d.%s", wzTempPath, wzPrefix, i, wzExtension); - ExitOnFailure(hr, "failed to allocate memory for temp filename"); + FileExitOnFailure(hr, "failed to allocate memory for temp filename"); hTempFile = ::CreateFileW(pwzTempFile, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL); if (INVALID_HANDLE_VALUE == hTempFile) @@ -1423,7 +1438,7 @@ extern "C" HRESULT DAPI FileCreateTempW( hr = S_OK; continue; } - ExitOnFailureDebugTrace(hr, "failed to create file: %ls", pwzTempFile); + FileExitOnFailureDebugTrace(hr, "failed to create file: %ls", pwzTempFile); } } @@ -1452,8 +1467,8 @@ LExit: ********************************************************************/ extern "C" HRESULT DAPI FileIsSame( - __in LPCWSTR wzFile1, - __in LPCWSTR wzFile2, + __in_z LPCWSTR wzFile1, + __in_z LPCWSTR wzFile2, __out LPBOOL lpfSameFile ) { @@ -1464,19 +1479,19 @@ extern "C" HRESULT DAPI FileIsSame( BY_HANDLE_FILE_INFORMATION fileInfo2 = { }; hFile1 = ::CreateFileW(wzFile1, FILE_READ_ATTRIBUTES, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); - ExitOnInvalidHandleWithLastError(hFile1, hr, "Failed to open file 1. File = '%ls'", wzFile1); + FileExitOnInvalidHandleWithLastError(hFile1, hr, "Failed to open file 1. File = '%ls'", wzFile1); hFile2 = ::CreateFileW(wzFile2, FILE_READ_ATTRIBUTES, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); - ExitOnInvalidHandleWithLastError(hFile2, hr, "Failed to open file 2. File = '%ls'", wzFile2); + FileExitOnInvalidHandleWithLastError(hFile2, hr, "Failed to open file 2. File = '%ls'", wzFile2); if (!::GetFileInformationByHandle(hFile1, &fileInfo1)) { - ExitWithLastError(hr, "Failed to get information for file 1. File = '%ls'", wzFile1); + FileExitWithLastError(hr, "Failed to get information for file 1. File = '%ls'", wzFile1); } if (!::GetFileInformationByHandle(hFile2, &fileInfo2)) { - ExitWithLastError(hr, "Failed to get information for file 2. File = '%ls'", wzFile2); + FileExitWithLastError(hr, "Failed to get information for file 2. File = '%ls'", wzFile2); } *lpfSameFile = fileInfo1.dwVolumeSerialNumber == fileInfo2.dwVolumeSerialNumber && @@ -1495,7 +1510,7 @@ LExit: hidden, or system attributes if necessary. ********************************************************************/ extern "C" HRESULT DAPI FileEnsureDelete( - __in LPCWSTR wzFile + __in_z LPCWSTR wzFile ) { HRESULT hr = S_OK; @@ -1507,13 +1522,13 @@ extern "C" HRESULT DAPI FileEnsureDelete( { if (!::SetFileAttributesW(wzFile, FILE_ATTRIBUTE_NORMAL)) { - ExitOnLastError(hr, "Failed to remove attributes from file: %ls", wzFile); + FileExitOnLastError(hr, "Failed to remove attributes from file: %ls", wzFile); } } if (!::DeleteFileW(wzFile)) { - ExitOnLastError(hr, "Failed to delete file: %ls", wzFile); + FileExitOnLastError(hr, "Failed to delete file: %ls", wzFile); } } @@ -1525,7 +1540,7 @@ LExit: FileGetTime - Gets the file time of a specified file ********************************************************************/ extern "C" HRESULT DAPI FileGetTime( - __in LPCWSTR wzFile, + __in_z LPCWSTR wzFile, __out_opt LPFILETIME lpCreationTime, __out_opt LPFILETIME lpLastAccessTime, __out_opt LPFILETIME lpLastWriteTime @@ -1535,11 +1550,11 @@ extern "C" HRESULT DAPI FileGetTime( HANDLE hFile = NULL; hFile = ::CreateFileW(wzFile, FILE_READ_ATTRIBUTES, FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, 0, NULL); - ExitOnInvalidHandleWithLastError(hFile, hr, "Failed to open file. File = '%ls'", wzFile); + FileExitOnInvalidHandleWithLastError(hFile, hr, "Failed to open file. File = '%ls'", wzFile); if (!::GetFileTime(hFile, lpCreationTime, lpLastAccessTime, lpLastWriteTime)) { - ExitWithLastError(hr, "Failed to get file time for file. File = '%ls'", wzFile); + FileExitWithLastError(hr, "Failed to get file time for file. File = '%ls'", wzFile); } LExit: @@ -1551,7 +1566,7 @@ LExit: FileSetTime - Sets the file time of a specified file ********************************************************************/ extern "C" HRESULT DAPI FileSetTime( - __in LPCWSTR wzFile, + __in_z LPCWSTR wzFile, __in_opt const FILETIME *lpCreationTime, __in_opt const FILETIME *lpLastAccessTime, __in_opt const FILETIME *lpLastWriteTime @@ -1561,11 +1576,11 @@ extern "C" HRESULT DAPI FileSetTime( HANDLE hFile = NULL; hFile = ::CreateFileW(wzFile, FILE_WRITE_ATTRIBUTES, FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, 0, NULL); - ExitOnInvalidHandleWithLastError(hFile, hr, "Failed to open file. File = '%ls'", wzFile); + FileExitOnInvalidHandleWithLastError(hFile, hr, "Failed to open file. File = '%ls'", wzFile); if (!::SetFileTime(hFile, lpCreationTime, lpLastAccessTime, lpLastWriteTime)) { - ExitWithLastError(hr, "Failed to set file time for file. File = '%ls'", wzFile); + FileExitWithLastError(hr, "Failed to set file time for file. File = '%ls'", wzFile); } LExit: @@ -1578,7 +1593,7 @@ LExit: creation time of the file ********************************************************************/ extern "C" HRESULT DAPI FileResetTime( - __in LPCWSTR wzFile + __in_z LPCWSTR wzFile ) { HRESULT hr = S_OK; @@ -1586,16 +1601,16 @@ extern "C" HRESULT DAPI FileResetTime( FILETIME ftCreateTime; hFile = ::CreateFileW(wzFile, FILE_WRITE_ATTRIBUTES | FILE_READ_ATTRIBUTES, FILE_SHARE_WRITE | FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); - ExitOnInvalidHandleWithLastError(hFile, hr, "Failed to open file. File = '%ls'", wzFile); + FileExitOnInvalidHandleWithLastError(hFile, hr, "Failed to open file. File = '%ls'", wzFile); if (!::GetFileTime(hFile, &ftCreateTime, NULL, NULL)) { - ExitWithLastError(hr, "Failed to get file time for file. File = '%ls'", wzFile); + FileExitWithLastError(hr, "Failed to get file time for file. File = '%ls'", wzFile); } if (!::SetFileTime(hFile, NULL, NULL, &ftCreateTime)) { - ExitWithLastError(hr, "Failed to reset file time for file. File = '%ls'", wzFile); + FileExitWithLastError(hr, "Failed to reset file time for file. File = '%ls'", wzFile); } LExit: @@ -1609,7 +1624,7 @@ LExit: *******************************************************************/ extern "C" HRESULT DAPI FileExecutableArchitecture( - __in LPCWSTR wzFile, + __in_z LPCWSTR wzFile, __out FILE_ARCHITECTURE *pArchitecture ) { @@ -1623,34 +1638,34 @@ extern "C" HRESULT DAPI FileExecutableArchitecture( hFile = ::CreateFileW(wzFile, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if (hFile == INVALID_HANDLE_VALUE) { - ExitWithLastError(hr, "Failed to open file: %ls", wzFile); + FileExitWithLastError(hr, "Failed to open file: %ls", wzFile); } if (!::ReadFile(hFile, &DosImageHeader, sizeof(DosImageHeader), &cbRead, NULL)) { - ExitWithLastError(hr, "Failed to read DOS header from file: %ls", wzFile); + FileExitWithLastError(hr, "Failed to read DOS header from file: %ls", wzFile); } if (DosImageHeader.e_magic != IMAGE_DOS_SIGNATURE) { hr = HRESULT_FROM_WIN32(ERROR_BAD_FORMAT); - ExitOnRootFailure(hr, "Read invalid DOS header from file: %ls", wzFile); + FileExitOnRootFailure(hr, "Read invalid DOS header from file: %ls", wzFile); } if (INVALID_SET_FILE_POINTER == ::SetFilePointer(hFile, DosImageHeader.e_lfanew, NULL, FILE_BEGIN)) { - ExitWithLastError(hr, "Failed to seek the NT header in file: %ls", wzFile); + FileExitWithLastError(hr, "Failed to seek the NT header in file: %ls", wzFile); } if (!::ReadFile(hFile, &NtImageHeader, sizeof(NtImageHeader), &cbRead, NULL)) { - ExitWithLastError(hr, "Failed to read NT header from file: %ls", wzFile); + FileExitWithLastError(hr, "Failed to read NT header from file: %ls", wzFile); } if (NtImageHeader.Signature != IMAGE_NT_SIGNATURE) { hr = HRESULT_FROM_WIN32(ERROR_BAD_FORMAT); - ExitOnRootFailure(hr, "Read invalid NT header from file: %ls", wzFile); + FileExitOnRootFailure(hr, "Read invalid NT header from file: %ls", wzFile); } if (IMAGE_SUBSYSTEM_NATIVE == NtImageHeader.OptionalHeader.Subsystem || @@ -1677,7 +1692,7 @@ extern "C" HRESULT DAPI FileExecutableArchitecture( { hr = HRESULT_FROM_WIN32(ERROR_BAD_FORMAT); } - ExitOnFailure(hr, "Unexpected subsystem: %d machine type: %d specified in NT header from file: %ls", NtImageHeader.OptionalHeader.Subsystem, NtImageHeader.FileHeader.Machine, wzFile); + FileExitOnFailure(hr, "Unexpected subsystem: %d machine type: %d specified in NT header from file: %ls", NtImageHeader.OptionalHeader.Subsystem, NtImageHeader.FileHeader.Machine, wzFile); LExit: if (hFile != INVALID_HANDLE_VALUE) @@ -1706,7 +1721,7 @@ extern "C" HRESULT DAPI FileToString( // Check if the file is ANSI hr = FileRead(&pbFullFileBuffer, &cbFullFileBuffer, wzFile); - ExitOnFailure(hr, "Failed to read file: %ls", wzFile); + FileExitOnFailure(hr, "Failed to read file: %ls", wzFile); if (0 == cbFullFileBuffer) { @@ -1723,7 +1738,7 @@ extern "C" HRESULT DAPI FileToString( } hr = StrAllocStringAnsi(&sczFileText, reinterpret_cast(pbFullFileBuffer + 3), cbFullFileBuffer - 3, CP_UTF8); - ExitOnFailure(hr, "Failed to convert file %ls from UTF-8 as its BOM indicated", wzFile); + FileExitOnFailure(hr, "Failed to convert file %ls from UTF-8 as its BOM indicated", wzFile); *psczString = sczFileText; sczFileText = NULL; @@ -1737,7 +1752,7 @@ extern "C" HRESULT DAPI FileToString( } hr = StrAllocString(psczString, reinterpret_cast(pbFullFileBuffer + 2), (cbFullFileBuffer - 2) / sizeof(WCHAR)); - ExitOnFailure(hr, "Failed to allocate copy of string"); + FileExitOnFailure(hr, "Failed to allocate copy of string"); } // No BOM, let's try to detect else @@ -1763,7 +1778,7 @@ extern "C" HRESULT DAPI FileToString( { if (E_OUTOFMEMORY == hr) { - ExitOnFailure(hr, "Failed to convert file %ls from UTF-8", wzFile); + FileExitOnFailure(hr, "Failed to convert file %ls from UTF-8", wzFile); } } else @@ -1780,7 +1795,7 @@ extern "C" HRESULT DAPI FileToString( } hr = StrAllocString(psczString, reinterpret_cast(pbFullFileBuffer), cbFullFileBuffer / sizeof(WCHAR)); - ExitOnFailure(hr, "Failed to allocate copy of string"); + FileExitOnFailure(hr, "Failed to allocate copy of string"); } } @@ -1813,20 +1828,20 @@ extern "C" HRESULT DAPI FileFromString( { case FILE_ENCODING_UTF8: hr = StrAnsiAllocString(&sczUtf8String, sczString, 0, CP_UTF8); - ExitOnFailure(hr, "Failed to convert string to UTF-8 to write UTF-8 file"); + FileExitOnFailure(hr, "Failed to convert string to UTF-8 to write UTF-8 file"); cbFullFileBuffer = lstrlenA(sczUtf8String); pcbFullFileBuffer = reinterpret_cast(sczUtf8String); break; case FILE_ENCODING_UTF8_WITH_BOM: hr = StrAnsiAllocString(&sczUtf8String, sczString, 0, CP_UTF8); - ExitOnFailure(hr, "Failed to convert string to UTF-8 to write UTF-8 file"); + FileExitOnFailure(hr, "Failed to convert string to UTF-8 to write UTF-8 file"); cbStrLen = lstrlenA(sczUtf8String); cbFullFileBuffer = sizeof(UTF8BOM) + cbStrLen; pbFullFileBuffer = reinterpret_cast(MemAlloc(cbFullFileBuffer, TRUE)); - ExitOnNull(pbFullFileBuffer, hr, E_OUTOFMEMORY, "Failed to allocate memory for output file buffer"); + FileExitOnNull(pbFullFileBuffer, hr, E_OUTOFMEMORY, "Failed to allocate memory for output file buffer"); memcpy_s(pbFullFileBuffer, sizeof(UTF8BOM), UTF8BOM, sizeof(UTF8BOM)); memcpy_s(pbFullFileBuffer + sizeof(UTF8BOM), cbStrLen, sczUtf8String, cbStrLen); @@ -1841,7 +1856,7 @@ extern "C" HRESULT DAPI FileFromString( cbFullFileBuffer = sizeof(UTF16BOM) + cbStrLen; pbFullFileBuffer = reinterpret_cast(MemAlloc(cbFullFileBuffer, TRUE)); - ExitOnNull(pbFullFileBuffer, hr, E_OUTOFMEMORY, "Failed to allocate memory for output file buffer"); + FileExitOnNull(pbFullFileBuffer, hr, E_OUTOFMEMORY, "Failed to allocate memory for output file buffer"); memcpy_s(pbFullFileBuffer, sizeof(UTF16BOM), UTF16BOM, sizeof(UTF16BOM)); memcpy_s(pbFullFileBuffer + sizeof(UTF16BOM), cbStrLen, sczString, cbStrLen); @@ -1850,7 +1865,7 @@ extern "C" HRESULT DAPI FileFromString( } hr = FileWrite(wzFile, dwFlagsAndAttributes, pcbFullFileBuffer, cbFullFileBuffer, NULL); - ExitOnFailure(hr, "Failed to write file from string to: %ls", wzFile); + FileExitOnFailure(hr, "Failed to write file from string to: %ls", wzFile); LExit: ReleaseStr(sczUtf8String); diff --git a/src/dutil/gdiputil.cpp b/src/dutil/gdiputil.cpp index aef6178f..b5a0087c 100644 --- a/src/dutil/gdiputil.cpp +++ b/src/dutil/gdiputil.cpp @@ -4,6 +4,21 @@ using namespace Gdiplus; + +// Exit macros +#define GdipExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_GDIPUTIL, x, s, __VA_ARGS__) +#define GdipExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_GDIPUTIL, x, s, __VA_ARGS__) +#define GdipExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_GDIPUTIL, x, s, __VA_ARGS__) +#define GdipExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_GDIPUTIL, x, s, __VA_ARGS__) +#define GdipExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_GDIPUTIL, x, s, __VA_ARGS__) +#define GdipExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_GDIPUTIL, x, s, __VA_ARGS__) +#define GdipExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_GDIPUTIL, p, x, e, s, __VA_ARGS__) +#define GdipExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_GDIPUTIL, p, x, s, __VA_ARGS__) +#define GdipExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_GDIPUTIL, p, x, e, s, __VA_ARGS__) +#define GdipExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_GDIPUTIL, p, x, s, __VA_ARGS__) +#define GdipExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_GDIPUTIL, e, x, s, __VA_ARGS__) +#define GdipExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_GDIPUTIL, g, x, s, __VA_ARGS__) + /******************************************************************** GdipInitialize - initializes GDI+. @@ -22,7 +37,7 @@ extern "C" HRESULT DAPI GdipInitialize( Status status = Ok; status = GdiplusStartup(pToken, pInput, pOutput); - ExitOnGdipFailure(status, hr, "Failed to initialize GDI+."); + GdipExitOnGdipFailure(status, hr, "Failed to initialize GDI+."); LExit: return hr; @@ -59,15 +74,15 @@ extern "C" HRESULT DAPI GdipBitmapFromResource( Status gs = Ok; hr = ResReadData(hinst, szId, &pvData, &cbData); - ExitOnFailure(hr, "Failed to load GDI+ bitmap from resource."); + GdipExitOnFailure(hr, "Failed to load GDI+ bitmap from resource."); // Have to copy the fixed resource data into moveable (heap) memory // since that's what GDI+ expects. hGlobal = ::GlobalAlloc(GMEM_MOVEABLE, cbData); - ExitOnNullWithLastError(hGlobal, hr, "Failed to allocate global memory."); + GdipExitOnNullWithLastError(hGlobal, hr, "Failed to allocate global memory."); pv = ::GlobalLock(hGlobal); - ExitOnNullWithLastError(pv, hr, "Failed to lock global memory."); + GdipExitOnNullWithLastError(pv, hr, "Failed to lock global memory."); memcpy(pv, pvData, cbData); @@ -75,15 +90,15 @@ extern "C" HRESULT DAPI GdipBitmapFromResource( pv = NULL; hr = ::CreateStreamOnHGlobal(hGlobal, TRUE, &pStream); - ExitOnFailure(hr, "Failed to allocate stream from global memory."); + GdipExitOnFailure(hr, "Failed to allocate stream from global memory."); hGlobal = NULL; // we gave the global memory to the stream object so it will close it pBitmap = Bitmap::FromStream(pStream); - ExitOnNull(pBitmap, hr, E_OUTOFMEMORY, "Failed to allocate bitmap from stream."); + GdipExitOnNull(pBitmap, hr, E_OUTOFMEMORY, "Failed to allocate bitmap from stream."); gs = pBitmap->GetLastStatus(); - ExitOnGdipFailure(gs, hr, "Failed to load bitmap from stream."); + GdipExitOnGdipFailure(gs, hr, "Failed to load bitmap from stream."); *ppBitmap = pBitmap; pBitmap = NULL; @@ -123,13 +138,13 @@ extern "C" HRESULT DAPI GdipBitmapFromFile( Bitmap *pBitmap = NULL; Status gs = Ok; - ExitOnNull(ppBitmap, hr, E_INVALIDARG, "Invalid null wzFileName"); + GdipExitOnNull(ppBitmap, hr, E_INVALIDARG, "Invalid null wzFileName"); pBitmap = Bitmap::FromFile(wzFileName); - ExitOnNull(pBitmap, hr, E_OUTOFMEMORY, "Failed to allocate bitmap from file."); + GdipExitOnNull(pBitmap, hr, E_OUTOFMEMORY, "Failed to allocate bitmap from file."); gs = pBitmap->GetLastStatus(); - ExitOnGdipFailure(gs, hr, "Failed to load bitmap from file: %ls", wzFileName); + GdipExitOnGdipFailure(gs, hr, "Failed to load bitmap from file: %ls", wzFileName); *ppBitmap = pBitmap; pBitmap = NULL; diff --git a/src/dutil/guidutil.cpp b/src/dutil/guidutil.cpp index c0353892..204c9af2 100644 --- a/src/dutil/guidutil.cpp +++ b/src/dutil/guidutil.cpp @@ -2,6 +2,21 @@ #include "precomp.h" + +// Exit macros +#define GuidExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_GUIDUTIL, x, s, __VA_ARGS__) +#define GuidExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_GUIDUTIL, x, s, __VA_ARGS__) +#define GuidExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_GUIDUTIL, x, s, __VA_ARGS__) +#define GuidExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_GUIDUTIL, x, s, __VA_ARGS__) +#define GuidExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_GUIDUTIL, x, s, __VA_ARGS__) +#define GuidExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_GUIDUTIL, x, s, __VA_ARGS__) +#define GuidExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_GUIDUTIL, p, x, e, s, __VA_ARGS__) +#define GuidExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_GUIDUTIL, p, x, s, __VA_ARGS__) +#define GuidExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_GUIDUTIL, p, x, e, s, __VA_ARGS__) +#define GuidExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_GUIDUTIL, p, x, s, __VA_ARGS__) +#define GuidExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_GUIDUTIL, e, x, s, __VA_ARGS__) +#define GuidExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_GUIDUTIL, g, x, s, __VA_ARGS__) + extern "C" HRESULT DAPI GuidFixedCreate( _Out_z_cap_c_(GUID_STRING_LENGTH) WCHAR* wzGuid ) @@ -10,12 +25,12 @@ extern "C" HRESULT DAPI GuidFixedCreate( UUID guid = { }; hr = HRESULT_FROM_RPC(::UuidCreate(&guid)); - ExitOnFailure(hr, "UuidCreate failed."); + GuidExitOnFailure(hr, "UuidCreate failed."); if (!::StringFromGUID2(guid, wzGuid, GUID_STRING_LENGTH)) { hr = E_OUTOFMEMORY; - ExitOnRootFailure(hr, "Failed to convert guid into string."); + GuidExitOnRootFailure(hr, "Failed to convert guid into string."); } LExit: @@ -29,10 +44,10 @@ extern "C" HRESULT DAPI GuidCreate( HRESULT hr = S_OK; hr = StrAlloc(psczGuid, GUID_STRING_LENGTH); - ExitOnFailure(hr, "Failed to allocate space for guid"); + GuidExitOnFailure(hr, "Failed to allocate space for guid"); hr = GuidFixedCreate(*psczGuid); - ExitOnFailure(hr, "Failed to create new guid."); + GuidExitOnFailure(hr, "Failed to create new guid."); LExit: return hr; diff --git a/src/dutil/iis7util.cpp b/src/dutil/iis7util.cpp index 04165a8d..d0a0b000 100644 --- a/src/dutil/iis7util.cpp +++ b/src/dutil/iis7util.cpp @@ -3,6 +3,21 @@ #include "precomp.h" #include "iis7util.h" + +// Exit macros +#define IisExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_IIS7UTIL, x, s, __VA_ARGS__) +#define IisExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_IIS7UTIL, x, s, __VA_ARGS__) +#define IisExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_IIS7UTIL, x, s, __VA_ARGS__) +#define IisExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_IIS7UTIL, x, s, __VA_ARGS__) +#define IisExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_IIS7UTIL, x, s, __VA_ARGS__) +#define IisExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_IIS7UTIL, x, s, __VA_ARGS__) +#define IisExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_IIS7UTIL, p, x, e, s, __VA_ARGS__) +#define IisExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_IIS7UTIL, p, x, s, __VA_ARGS__) +#define IisExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_IIS7UTIL, p, x, e, s, __VA_ARGS__) +#define IisExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_IIS7UTIL, p, x, s, __VA_ARGS__) +#define IisExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_IIS7UTIL, e, x, s, __VA_ARGS__) +#define IisExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_IIS7UTIL, g, x, s, __VA_ARGS__) + #define ISSTRINGVARIANT(vt) (VT_BSTR == vt || VT_LPWSTR == vt) extern "C" HRESULT DAPI Iis7PutPropertyVariant( @@ -16,13 +31,13 @@ extern "C" HRESULT DAPI Iis7PutPropertyVariant( BSTR bstrPropName = NULL; bstrPropName = ::SysAllocString(wzPropName); - ExitOnNull(bstrPropName, hr, E_OUTOFMEMORY, "failed SysAllocString"); + IisExitOnNull(bstrPropName, hr, E_OUTOFMEMORY, "failed SysAllocString"); hr = pElement->GetPropertyByName(bstrPropName, &pProperty); - ExitOnFailure(hr, "Failed to get property object for %ls", wzPropName); + IisExitOnFailure(hr, "Failed to get property object for %ls", wzPropName); hr = pProperty->put_Value(vtPut); - ExitOnFailure(hr, "Failed to set property value for %ls", wzPropName); + IisExitOnFailure(hr, "Failed to set property value for %ls", wzPropName); LExit: ReleaseBSTR(bstrPropName); @@ -44,7 +59,7 @@ extern "C" HRESULT DAPI Iis7PutPropertyString( ::VariantInit(&vtPut); vtPut.vt = VT_BSTR; vtPut.bstrVal = ::SysAllocString(wzString); - ExitOnNull(vtPut.bstrVal, hr, E_OUTOFMEMORY, "failed SysAllocString"); + IisExitOnNull(vtPut.bstrVal, hr, E_OUTOFMEMORY, "failed SysAllocString"); hr = Iis7PutPropertyVariant(pElement, wzPropName, vtPut); @@ -92,13 +107,13 @@ extern "C" HRESULT DAPI Iis7GetPropertyVariant( BSTR bstrPropName = NULL; bstrPropName = ::SysAllocString(wzPropName); - ExitOnNull(bstrPropName, hr, E_OUTOFMEMORY, "failed SysAllocString"); + IisExitOnNull(bstrPropName, hr, E_OUTOFMEMORY, "failed SysAllocString"); hr = pElement->GetPropertyByName(bstrPropName, &pProperty); - ExitOnFailure(hr, "Failed to get property object for %ls", wzPropName); + IisExitOnFailure(hr, "Failed to get property object for %ls", wzPropName); hr = pProperty->get_Value(vtGet); - ExitOnFailure(hr, "Failed to get property value for %ls", wzPropName); + IisExitOnFailure(hr, "Failed to get property value for %ls", wzPropName); LExit: ReleaseBSTR(bstrPropName); @@ -119,12 +134,12 @@ extern "C" HRESULT DAPI Iis7GetPropertyString( ::VariantInit(&vtGet); hr = Iis7GetPropertyVariant(pElement, wzPropName, &vtGet); - ExitOnFailure(hr, "Failed to get iis7 property variant with name: %ls", wzPropName); + IisExitOnFailure(hr, "Failed to get iis7 property variant with name: %ls", wzPropName); if (!ISSTRINGVARIANT(vtGet.vt)) { hr = E_UNEXPECTED; - ExitOnFailure(hr, "Tried to get property as a string, but type was %d instead.", vtGet.vt); + IisExitOnFailure(hr, "Tried to get property as a string, but type was %d instead.", vtGet.vt); } hr = StrAllocString(psczGet, vtGet.bstrVal, 0); @@ -198,13 +213,13 @@ BOOL DAPI CompareVariantPath( if (ISSTRINGVARIANT(pVariant1->vt)) { hr = PathExpand(&wzValue1, pVariant1->bstrVal, PATH_EXPAND_ENVIRONMENT | PATH_EXPAND_FULLPATH); - ExitOnFailure(hr, "Failed to expand path %ls", pVariant1->bstrVal); + IisExitOnFailure(hr, "Failed to expand path %ls", pVariant1->bstrVal); } if (ISSTRINGVARIANT(pVariant2->vt)) { hr = PathExpand(&wzValue2, pVariant2->bstrVal, PATH_EXPAND_ENVIRONMENT | PATH_EXPAND_FULLPATH); - ExitOnFailure(hr, "Failed to expand path %ls", pVariant2->bstrVal); + IisExitOnFailure(hr, "Failed to expand path %ls", pVariant2->bstrVal); } fEqual = CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, NORM_IGNORECASE, wzValue1, -1, wzValue2, -1); @@ -242,14 +257,14 @@ extern "C" BOOL DAPI Iis7IsMatchingAppHostElement( VARIANTCOMPARATORPROC pComparator = pComparison->pComparator ? pComparison->pComparator : CompareVariantDefault; hr = pElement->get_Name(&bstrElementName); - ExitOnFailure(hr, "Failed to get name of element"); + IisExitOnFailure(hr, "Failed to get name of element"); if (CSTR_EQUAL != ::CompareStringW(LOCALE_INVARIANT, NORM_IGNORECASE, pComparison->sczElementName, -1, bstrElementName, -1)) { ExitFunction(); } hr = Iis7GetPropertyVariant(pElement, pComparison->sczAttributeName, &vPropValue); - ExitOnFailure(hr, "Failed to get value of %ls attribute of %ls element", pComparison->sczAttributeName, pComparison->sczElementName); + IisExitOnFailure(hr, "Failed to get value of %ls attribute of %ls element", pComparison->sczAttributeName, pComparison->sczElementName); if (TRUE == pComparator(pComparison->pvAttributeValue, &vPropValue)) { @@ -274,7 +289,9 @@ BOOL DAPI IsMatchingAppHostMethod( BSTR bstrName = NULL; hr = pMethod->get_Name(&bstrName); - ExitOnFailure(hr, "Failed to get name of element"); + IisExitOnFailure(hr, "Failed to get name of element"); + + Assert(bstrName); if (CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, NORM_IGNORECASE, wzMethodName, -1, bstrName, -1)) { @@ -303,7 +320,7 @@ extern "C" HRESULT DAPI Iis7FindAppHostElementPath( vtValue.vt = VT_BSTR; vtValue.bstrVal = ::SysAllocString(wzAttributeValue); - ExitOnNull(vtValue.bstrVal, hr, E_OUTOFMEMORY, "failed SysAllocString"); + IisExitOnNull(vtValue.bstrVal, hr, E_OUTOFMEMORY, "failed SysAllocString"); comparison.sczElementName = wzElementName; comparison.sczAttributeName = wzAttributeName; @@ -337,7 +354,7 @@ extern "C" HRESULT DAPI Iis7FindAppHostElementString( vtValue.vt = VT_BSTR; vtValue.bstrVal = ::SysAllocString(wzAttributeValue); - ExitOnNull(vtValue.bstrVal, hr, E_OUTOFMEMORY, "failed SysAllocString"); + IisExitOnNull(vtValue.bstrVal, hr, E_OUTOFMEMORY, "failed SysAllocString"); hr = Iis7FindAppHostElementVariant(pCollection, wzElementName, @@ -427,14 +444,14 @@ extern "C" HRESULT DAPI Iis7EnumAppHostElements( } hr = pCollection->get_Count(&dwElements); - ExitOnFailure(hr, "Failed get application IAppHostElementCollection count"); + IisExitOnFailure(hr, "Failed get application IAppHostElementCollection count"); vtIndex.vt = VT_UI4; for (DWORD i = 0; i < dwElements; ++i) { vtIndex.ulVal = i; hr = pCollection->get_Item(vtIndex , &pElement); - ExitOnFailure(hr, "Failed get IAppHostElement element"); + IisExitOnFailure(hr, "Failed get IAppHostElement element"); if (pCallback(pElement, pContext)) { @@ -484,14 +501,14 @@ extern "C" HRESULT DAPI Iis7FindAppHostMethod( } hr = pCollection->get_Count(&dwMethods); - ExitOnFailure(hr, "Failed get application IAppHostMethodCollection count"); + IisExitOnFailure(hr, "Failed get application IAppHostMethodCollection count"); vtIndex.vt = VT_UI4; for (DWORD i = 0; i < dwMethods; ++i) { vtIndex.ulVal = i; hr = pCollection->get_Item(vtIndex , &pMethod); - ExitOnFailure(hr, "Failed get IAppHostMethod element"); + IisExitOnFailure(hr, "Failed get IAppHostMethod element"); if (IsMatchingAppHostMethod(pMethod, wzMethodName)) { diff --git a/src/dutil/inc/atomutil.h b/src/dutil/inc/atomutil.h index ff869c4a..9acfc1d5 100644 --- a/src/dutil/inc/atomutil.h +++ b/src/dutil/inc/atomutil.h @@ -138,7 +138,7 @@ HRESULT DAPI AtomParseFromDocument( ); void DAPI AtomFreeFeed( - __in_xcount(pFeed->cItems) ATOM_FEED *pFEED + __in_xcount(pFeed->cItems) ATOM_FEED* pFeed ); #ifdef __cplusplus diff --git a/src/dutil/inc/buffutil.h b/src/dutil/inc/buffutil.h index a718e9c0..7509f76a 100644 --- a/src/dutil/inc/buffutil.h +++ b/src/dutil/inc/buffutil.h @@ -50,37 +50,37 @@ HRESULT BuffReadStream( __in_bcount(cbBuffer) const BYTE* pbBuffer, __in SIZE_T cbBuffer, __inout SIZE_T* piBuffer, - __deref_out_bcount(*pcbStream) BYTE** ppbStream, + __deref_inout_bcount(*pcbStream) BYTE** ppbStream, __out SIZE_T* pcbStream ); HRESULT BuffWriteNumber( - __deref_out_bcount(*piBuffer) BYTE** ppbBuffer, + __deref_inout_bcount(*piBuffer) BYTE** ppbBuffer, __inout SIZE_T* piBuffer, __in DWORD_PTR dw ); HRESULT BuffWriteNumber64( - __deref_out_bcount(*piBuffer) BYTE** ppbBuffer, + __deref_inout_bcount(*piBuffer) BYTE** ppbBuffer, __inout SIZE_T* piBuffer, __in DWORD64 dw64 ); HRESULT BuffWritePointer( - __deref_out_bcount(*piBuffer) BYTE** ppbBuffer, + __deref_inout_bcount(*piBuffer) BYTE** ppbBuffer, __inout SIZE_T* piBuffer, __in DWORD_PTR dw ); HRESULT BuffWriteString( - __deref_out_bcount(*piBuffer) BYTE** ppbBuffer, + __deref_inout_bcount(*piBuffer) BYTE** ppbBuffer, __inout SIZE_T* piBuffer, __in_z_opt LPCWSTR scz ); HRESULT BuffWriteStringAnsi( - __deref_out_bcount(*piBuffer) BYTE** ppbBuffer, + __deref_inout_bcount(*piBuffer) BYTE** ppbBuffer, __inout SIZE_T* piBuffer, __in_z_opt LPCSTR scz ); HRESULT BuffWriteStream( - __deref_out_bcount(*piBuffer) BYTE** ppbBuffer, + __deref_inout_bcount(*piBuffer) BYTE** ppbBuffer, __inout SIZE_T* piBuffer, __in_bcount(cbStream) const BYTE* pbStream, __in SIZE_T cbStream diff --git a/src/dutil/inc/conutil.h b/src/dutil/inc/conutil.h index 5f611d01..38aaea84 100644 --- a/src/dutil/inc/conutil.h +++ b/src/dutil/inc/conutil.h @@ -55,12 +55,12 @@ HRESULT DAPI ConsoleReadW( ); HRESULT DAPI ConsoleReadStringA( - __deref_out_ecount_part(cchCharBuffer,*pcchNumCharReturn) LPSTR* szCharBuffer, + __deref_inout_ecount_part(cchCharBuffer,*pcchNumCharReturn) LPSTR* szCharBuffer, CONST DWORD cchCharBuffer, __out DWORD* pcchNumCharReturn ); HRESULT DAPI ConsoleReadStringW( - __deref_out_ecount_part(cchCharBuffer,*pcchNumCharReturn) LPWSTR* szCharBuffer, + __deref_inout_ecount_part(cchCharBuffer,*pcchNumCharReturn) LPWSTR* szCharBuffer, CONST DWORD cchCharBuffer, __out DWORD* pcchNumCharReturn ); diff --git a/src/dutil/inc/deputil.h b/src/dutil/inc/deputil.h index 8f5f0ae8..bfe235f3 100644 --- a/src/dutil/inc/deputil.h +++ b/src/dutil/inc/deputil.h @@ -55,7 +55,7 @@ DAPI_(HRESULT) DepCheckDependency( DAPI_(HRESULT) DepCheckDependents( __in HKEY hkHive, __in_z LPCWSTR wzProviderKey, - __in int iAttributes, + __reserved int iAttributes, __in C_STRINGDICT_HANDLE sdIgnoredDependents, __deref_inout_ecount_opt(*pcDependents) DEPENDENCY** prgDependents, __inout LPUINT pcDependents diff --git a/src/dutil/inc/dutil.h b/src/dutil/inc/dutil.h index 15d45d21..fc9ec0f4 100644 --- a/src/dutil/inc/dutil.h +++ b/src/dutil/inc/dutil.h @@ -44,7 +44,7 @@ void DAPI DutilUninitialize(); void DAPI Dutil_SetAssertModule(__in HMODULE hAssertModule); void DAPI Dutil_SetAssertDisplayFunction(__in DUTIL_ASSERTDISPLAYFUNCTION pfn); void DAPI Dutil_Assert(__in_z LPCSTR szFile, __in int iLine); -void DAPI Dutil_AssertSz(__in_z LPCSTR szFile, __in int iLine, __in_z LPCSTR szMessage); +void DAPI Dutil_AssertSz(__in_z LPCSTR szFile, __in int iLine, __in_z __format_string LPCSTR szMessage); void DAPI Dutil_TraceSetLevel(__in REPORT_LEVEL ll, __in BOOL fTraceFilenames); REPORT_LEVEL DAPI Dutil_TraceGetLevel(); diff --git a/src/dutil/inc/eseutil.h b/src/dutil/inc/eseutil.h index 1c408927..bea47b2b 100644 --- a/src/dutil/inc/eseutil.h +++ b/src/dutil/inc/eseutil.h @@ -160,7 +160,7 @@ HRESULT DAPI EseGetColumnBinary( __in JET_SESID jsSession, __in ESE_TABLE_SCHEMA tsTable, __in DWORD dwColumn, - __deref_out_bcount(*piBuffer) BYTE** ppbBuffer, + __deref_inout_bcount(*piBuffer) BYTE** ppbBuffer, __inout SIZE_T* piBuffer ); HRESULT DAPI EseGetColumnDword( diff --git a/src/dutil/inc/fileutil.h b/src/dutil/inc/fileutil.h index d2b2f4fe..7caa62b8 100644 --- a/src/dutil/inc/fileutil.h +++ b/src/dutil/inc/fileutil.h @@ -121,7 +121,7 @@ HRESULT DAPI FileReadPartial( __in BOOL fPartialOK ); HRESULT DAPI FileReadPartialEx( - __deref_out_bcount_full(*pcbDest) LPBYTE* ppbDest, + __deref_inout_bcount_full(*pcbDest) LPBYTE* ppbDest, __out_range(<=, cbMaxRead) SIZE_T* pcbDest, __in_z LPCWSTR wzSrcPath, __in BOOL fSeek, diff --git a/src/dutil/inc/inetutil.h b/src/dutil/inc/inetutil.h index 4cbf510b..19ace88b 100644 --- a/src/dutil/inc/inetutil.h +++ b/src/dutil/inc/inetutil.h @@ -30,7 +30,7 @@ HRESULT DAPI InternetQueryInfoString( HRESULT DAPI InternetQueryInfoNumber( __in HINTERNET h, __in DWORD dwInfo, - __out LONG* plInfo + __inout LONG* plInfo ); #ifdef __cplusplus diff --git a/src/dutil/inc/iniutil.h b/src/dutil/inc/iniutil.h index d5b50c17..c8503155 100644 --- a/src/dutil/inc/iniutil.h +++ b/src/dutil/inc/iniutil.h @@ -55,7 +55,7 @@ HRESULT DAPI IniParse( // (their value will be NULL) HRESULT DAPI IniGetValueList( __in_bcount(INI_HANDLE_BYTES) INI_HANDLE piHandle, - __deref_out_ecount_opt(pcValues) INI_VALUE** prgivValues, + __deref_out_ecount_opt(*pcValues) INI_VALUE** prgivValues, __out DWORD *pcValues ); HRESULT DAPI IniGetValue( diff --git a/src/dutil/inc/memutil.h b/src/dutil/inc/memutil.h index 93e53228..49f86e0a 100644 --- a/src/dutil/inc/memutil.h +++ b/src/dutil/inc/memutil.h @@ -39,13 +39,13 @@ HRESULT DAPI MemReAllocArray( __in DWORD dwNewItemCount ); HRESULT DAPI MemEnsureArraySize( - __deref_out_bcount(cArray * cbArrayType) LPVOID* ppvArray, + __deref_inout_bcount(cArray * cbArrayType) LPVOID* ppvArray, __in DWORD cArray, __in SIZE_T cbArrayType, __in DWORD dwGrowthCount ); HRESULT DAPI MemInsertIntoArray( - __deref_out_bcount((cExistingArray + cInsertItems) * cbArrayType) LPVOID* ppvArray, + __deref_inout_bcount((cExistingArray + cInsertItems) * cbArrayType) LPVOID* ppvArray, __in DWORD dwInsertIndex, __in DWORD cInsertItems, __in DWORD cExistingArray, @@ -61,7 +61,7 @@ void DAPI MemRemoveFromArray( __in BOOL fPreserveOrder ); void DAPI MemArraySwapItems( - __inout_bcount((cExistingArray) * cbArrayType) LPVOID pvArray, + __inout_bcount(cbArrayType) LPVOID pvArray, __in DWORD dwIndex1, __in DWORD dwIndex2, __in SIZE_T cbArrayType diff --git a/src/dutil/inc/pathutil.h b/src/dutil/inc/pathutil.h index bee8ed1b..f4f4e59c 100644 --- a/src/dutil/inc/pathutil.h +++ b/src/dutil/inc/pathutil.h @@ -19,7 +19,7 @@ typedef enum PATH_EXPAND (i.e. quote arguments with spaces in them). ********************************************************************/ DAPI_(HRESULT) PathCommandLineAppend( - __deref_out_z LPWSTR* psczCommandLine, + __deref_inout_z LPWSTR* psczCommandLine, __in_z LPCWSTR wzArgument ); @@ -43,7 +43,7 @@ DAPI_(LPCWSTR) PathExtension( ********************************************************************/ DAPI_(HRESULT) PathGetDirectory( __in_z LPCWSTR wzPath, - __out LPWSTR *psczDirectory + __out_z LPWSTR *psczDirectory ); /******************************************************************* @@ -206,7 +206,7 @@ DAPI_(HRESULT) PathCompress( *******************************************************************/ DAPI_(HRESULT) PathGetHierarchyArray( __in_z LPCWSTR wzPath, - __deref_inout_ecount_opt(*pcStrArray) LPWSTR **prgsczPathArray, + __deref_inout_ecount_opt(*pcPathArray) LPWSTR **prgsczPathArray, __inout LPUINT pcPathArray ); diff --git a/src/dutil/inc/regutil.h b/src/dutil/inc/regutil.h index 897b9d03..2f09d244 100644 --- a/src/dutil/inc/regutil.h +++ b/src/dutil/inc/regutil.h @@ -50,7 +50,7 @@ typedef LSTATUS (APIENTRY *PFN_REGENUMKEYEXW)( __out LPWSTR lpName, __inout LPDWORD lpcName, __reserved LPDWORD lpReserved, - __inout LPWSTR lpClass, + __inout_opt LPWSTR lpClass, __inout_opt LPDWORD lpcClass, __out_opt PFILETIME lpftLastWriteTime ); @@ -66,7 +66,7 @@ typedef LSTATUS (APIENTRY *PFN_REGENUMVALUEW)( ); typedef LSTATUS (APIENTRY *PFN_REGQUERYINFOKEYW)( __in HKEY hKey, - __out LPWSTR lpClass, + __out_opt LPWSTR lpClass, __inout_opt LPDWORD lpcClass, __reserved LPDWORD lpReserved, __out_opt LPDWORD lpcSubKeys, @@ -170,7 +170,7 @@ HRESULT DAPI RegReadString( HRESULT DAPI RegReadStringArray( __in HKEY hk, __in_z_opt LPCWSTR wzName, - __deref_out_ecount_opt(pcStrings) LPWSTR** prgsczStrings, + __deref_out_ecount_opt(*pcStrings) LPWSTR** prgsczStrings, __out DWORD *pcStrings ); HRESULT DAPI RegReadVersion( @@ -202,7 +202,7 @@ HRESULT DAPI RegWriteString( HRESULT DAPI RegWriteStringArray( __in HKEY hk, __in_z_opt LPCWSTR wzName, - __in_ecount(cValues) LPWSTR *rgwzStrings, + __in_ecount(cStrings) LPWSTR *rgwzStrings, __in DWORD cStrings ); HRESULT DAPI RegWriteStringFormatted( diff --git a/src/dutil/inc/shelutil.h b/src/dutil/inc/shelutil.h index 21e82672..0b9f539d 100644 --- a/src/dutil/inc/shelutil.h +++ b/src/dutil/inc/shelutil.h @@ -19,9 +19,9 @@ void DAPI ShelFunctionOverride( ); HRESULT DAPI ShelExec( __in_z LPCWSTR wzTargetPath, - __in_opt LPCWSTR wzParameters, - __in_opt LPCWSTR wzVerb, - __in_opt LPCWSTR wzWorkingDirectory, + __in_z_opt LPCWSTR wzParameters, + __in_z_opt LPCWSTR wzVerb, + __in_z_opt LPCWSTR wzWorkingDirectory, __in int nShowCmd, __in_opt HWND hwndParent, __out_opt HANDLE* phProcess diff --git a/src/dutil/inc/strutil.h b/src/dutil/inc/strutil.h index 187bfda8..cf8c751c 100644 --- a/src/dutil/inc/strutil.h +++ b/src/dutil/inc/strutil.h @@ -198,7 +198,7 @@ HRESULT DAPI StrAllocBase85Decode( HRESULT DAPI MultiSzLen( __in_ecount(*pcch) __nullnullterminated LPCWSTR pwzMultiSz, - __out SIZE_T* pcbch + __out SIZE_T* pcch ); HRESULT DAPI MultiSzPrepend( __deref_inout_ecount(*pcchMultiSz) __nullnullterminated LPWSTR* ppwzMultiSz, @@ -222,7 +222,7 @@ HRESULT DAPI MultiSzRemoveString( __in DWORD_PTR dwIndex ); HRESULT DAPI MultiSzInsertString( - __deref_inout_z LPWSTR* ppwzMultiSz, + __deref_inout __nullnullterminated LPWSTR* ppwzMultiSz, __inout_opt SIZE_T* pcchMultiSz, __in DWORD_PTR dwIndex, __in_z LPCWSTR pwzInsert diff --git a/src/dutil/inc/thmutil.h b/src/dutil/inc/thmutil.h index 11eac9c2..d3dd6d21 100644 --- a/src/dutil/inc/thmutil.h +++ b/src/dutil/inc/thmutil.h @@ -737,7 +737,7 @@ HRESULT DAPI ThemeSetTextControlEx( HRESULT DAPI ThemeGetTextControl( __in const THEME* pTheme, __in DWORD dwControl, - __out_z LPWSTR* psczText + __inout_z LPWSTR* psczText ); /******************************************************************** diff --git a/src/dutil/inc/uriutil.h b/src/dutil/inc/uriutil.h index 52e78308..d6dfdd6b 100644 --- a/src/dutil/inc/uriutil.h +++ b/src/dutil/inc/uriutil.h @@ -91,7 +91,7 @@ HRESULT DAPI UriResolve( __in_z LPCWSTR wzUri, __in_opt LPCWSTR wzBaseUri, __out LPWSTR* ppwzResolvedUri, - __out_opt const URI_PROTOCOL* pResolvedProtocol + __out_opt URI_PROTOCOL* pResolvedProtocol ); #ifdef __cplusplus diff --git a/src/dutil/inc/wiutil.h b/src/dutil/inc/wiutil.h index 10d003b0..9c2de209 100644 --- a/src/dutil/inc/wiutil.h +++ b/src/dutil/inc/wiutil.h @@ -330,7 +330,7 @@ HRESULT DAPI WiuEnumRelatedProducts( ); HRESULT DAPI WiuEnumRelatedProductCodes( __in_z LPCWSTR wzUpgradeCode, - __deref_out_ecount_opt(pcRelatedProducts) LPWSTR** prgsczProductCodes, + __deref_out_ecount_opt(*pcRelatedProducts) LPWSTR** prgsczProductCodes, __out DWORD* pcRelatedProducts, __in BOOL fReturnHighestVersionOnly ); diff --git a/src/dutil/inetutil.cpp b/src/dutil/inetutil.cpp index 69a0176a..f75849f6 100644 --- a/src/dutil/inetutil.cpp +++ b/src/dutil/inetutil.cpp @@ -3,6 +3,21 @@ #include "precomp.h" +// Exit macros +#define InetExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_INETUTIL, x, s, __VA_ARGS__) +#define InetExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_INETUTIL, x, s, __VA_ARGS__) +#define InetExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_INETUTIL, x, s, __VA_ARGS__) +#define InetExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_INETUTIL, x, s, __VA_ARGS__) +#define InetExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_INETUTIL, x, s, __VA_ARGS__) +#define InetExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_INETUTIL, x, s, __VA_ARGS__) +#define InetExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_INETUTIL, p, x, e, s, __VA_ARGS__) +#define InetExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_INETUTIL, p, x, s, __VA_ARGS__) +#define InetExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_INETUTIL, p, x, e, s, __VA_ARGS__) +#define InetExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_INETUTIL, p, x, s, __VA_ARGS__) +#define InetExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_INETUTIL, e, x, s, __VA_ARGS__) +#define InetExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_INETUTIL, g, x, s, __VA_ARGS__) + + /******************************************************************* InternetGetSizeByHandle - returns size of file by url handle @@ -15,13 +30,13 @@ extern "C" HRESULT DAPI InternetGetSizeByHandle( Assert(pllSize); HRESULT hr = S_OK; - DWORD dwSize; - DWORD cb; + DWORD dwSize = 0; + DWORD cb = 0; cb = sizeof(dwSize); if (!::HttpQueryInfoW(hiFile, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, reinterpret_cast(&dwSize), &cb, NULL)) { - ExitOnLastError(hr, "Failed to get size for internet file handle"); + InetExitOnLastError(hr, "Failed to get size for internet file handle"); } *pllSize = dwSize; @@ -47,12 +62,12 @@ extern "C" HRESULT DAPI InternetGetCreateTimeByHandle( if (!::HttpQueryInfoW(hiFile, HTTP_QUERY_LAST_MODIFIED | HTTP_QUERY_FLAG_SYSTEMTIME, reinterpret_cast(&st), &cb, NULL)) { - ExitWithLastError(hr, "failed to get create time for internet file handle"); + InetExitWithLastError(hr, "failed to get create time for internet file handle"); } if (!::SystemTimeToFileTime(&st, pft)) { - ExitWithLastError(hr, "failed to convert system time to file time"); + InetExitWithLastError(hr, "failed to convert system time to file time"); } LExit: @@ -78,11 +93,11 @@ extern "C" HRESULT DAPI InternetQueryInfoString( if (!*psczValue) { hr = StrAlloc(psczValue, 64); - ExitOnFailure(hr, "Failed to allocate memory for value."); + InetExitOnFailure(hr, "Failed to allocate memory for value."); } hr = StrSize(*psczValue, &cbValue); - ExitOnFailure(hr, "Failed to get size of value."); + InetExitOnFailure(hr, "Failed to get size of value."); if (!::HttpQueryInfoW(hRequest, dwInfo, static_cast(*psczValue), reinterpret_cast(&cbValue), &dwIndex)) { @@ -92,7 +107,7 @@ extern "C" HRESULT DAPI InternetQueryInfoString( cbValue += sizeof(WCHAR); // add one character for the null terminator. hr = StrAlloc(psczValue, cbValue / sizeof(WCHAR)); - ExitOnFailure(hr, "Failed to allocate value."); + InetExitOnFailure(hr, "Failed to allocate value."); if (!::HttpQueryInfoW(hRequest, dwInfo, static_cast(*psczValue), reinterpret_cast(&cbValue), &dwIndex)) { @@ -105,7 +120,7 @@ extern "C" HRESULT DAPI InternetQueryInfoString( } hr = HRESULT_FROM_WIN32(er); - ExitOnRootFailure(hr, "Failed to get query information."); + InetExitOnRootFailure(hr, "Failed to get query information."); } LExit: @@ -120,7 +135,7 @@ LExit: extern "C" HRESULT DAPI InternetQueryInfoNumber( __in HINTERNET hRequest, __in DWORD dwInfo, - __out LONG* plInfo + __inout LONG* plInfo ) { HRESULT hr = S_OK; @@ -129,7 +144,7 @@ extern "C" HRESULT DAPI InternetQueryInfoNumber( if (!::HttpQueryInfoW(hRequest, dwInfo | HTTP_QUERY_FLAG_NUMBER, static_cast(plInfo), &cbCode, &dwIndex)) { - ExitWithLastError(hr, "Failed to get query information."); + InetExitWithLastError(hr, "Failed to get query information."); } LExit: diff --git a/src/dutil/iniutil.cpp b/src/dutil/iniutil.cpp index c9ef6c3d..70b62995 100644 --- a/src/dutil/iniutil.cpp +++ b/src/dutil/iniutil.cpp @@ -2,6 +2,21 @@ #include "precomp.h" + +// Exit macros +#define IniExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_INIUTIL, x, s, __VA_ARGS__) +#define IniExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_INIUTIL, x, s, __VA_ARGS__) +#define IniExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_INIUTIL, x, s, __VA_ARGS__) +#define IniExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_INIUTIL, x, s, __VA_ARGS__) +#define IniExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_INIUTIL, x, s, __VA_ARGS__) +#define IniExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_INIUTIL, x, s, __VA_ARGS__) +#define IniExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_INIUTIL, p, x, e, s, __VA_ARGS__) +#define IniExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_INIUTIL, p, x, s, __VA_ARGS__) +#define IniExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_INIUTIL, p, x, e, s, __VA_ARGS__) +#define IniExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_INIUTIL, p, x, s, __VA_ARGS__) +#define IniExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_INIUTIL, e, x, s, __VA_ARGS__) +#define IniExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_INIUTIL, g, x, s, __VA_ARGS__) + const LPCWSTR wzSectionSeparator = L"\\"; struct INI_STRUCT @@ -33,7 +48,7 @@ const int INI_HANDLE_BYTES = sizeof(INI_STRUCT); static HRESULT GetSectionPrefixFromName( __in_z LPCWSTR wzName, - __deref_out_z LPWSTR* psczOutput + __deref_inout_z LPWSTR* psczOutput ); static void UninitializeIniValue( INI_VALUE *pivValue @@ -47,7 +62,7 @@ extern "C" HRESULT DAPI IniInitialize( // Allocate the handle *piHandle = static_cast(MemAlloc(sizeof(INI_STRUCT), TRUE)); - ExitOnNull(*piHandle, hr, E_OUTOFMEMORY, "Failed to allocate ini object"); + IniExitOnNull(*piHandle, hr, E_OUTOFMEMORY, "Failed to allocate ini object"); LExit: return hr; @@ -96,7 +111,7 @@ extern "C" HRESULT DAPI IniSetOpenTag( if (wzOpenTagPrefix) { hr = StrAllocString(&pi->sczOpenTagPrefix, wzOpenTagPrefix, 0); - ExitOnFailure(hr, "Failed to copy open tag prefix to ini struct: %ls", wzOpenTagPrefix); + IniExitOnFailure(hr, "Failed to copy open tag prefix to ini struct: %ls", wzOpenTagPrefix); } else { @@ -106,7 +121,7 @@ extern "C" HRESULT DAPI IniSetOpenTag( if (wzOpenTagPostfix) { hr = StrAllocString(&pi->sczOpenTagPostfix, wzOpenTagPostfix, 0); - ExitOnFailure(hr, "Failed to copy open tag postfix to ini struct: %ls", wzOpenTagPostfix); + IniExitOnFailure(hr, "Failed to copy open tag postfix to ini struct: %ls", wzOpenTagPostfix); } else { @@ -130,7 +145,7 @@ extern "C" HRESULT DAPI IniSetValueStyle( if (wzValuePrefix) { hr = StrAllocString(&pi->sczValuePrefix, wzValuePrefix, 0); - ExitOnFailure(hr, "Failed to copy value prefix to ini struct: %ls", wzValuePrefix); + IniExitOnFailure(hr, "Failed to copy value prefix to ini struct: %ls", wzValuePrefix); } else { @@ -140,7 +155,7 @@ extern "C" HRESULT DAPI IniSetValueStyle( if (wzValueSeparator) { hr = StrAllocString(&pi->sczValueSeparator, wzValueSeparator, 0); - ExitOnFailure(hr, "Failed to copy value separator to ini struct: %ls", wzValueSeparator); + IniExitOnFailure(hr, "Failed to copy value separator to ini struct: %ls", wzValueSeparator); } else { @@ -162,12 +177,12 @@ extern "C" HRESULT DAPI IniSetValueSeparatorException( INI_STRUCT *pi = static_cast(piHandle); hr = MemEnsureArraySize(reinterpret_cast(&pi->rgsczValueSeparatorExceptions), pi->cValueSeparatorExceptions + 1, sizeof(LPWSTR), 5); - ExitOnFailure(hr, "Failed to increase array size for value separator exceptions"); + IniExitOnFailure(hr, "Failed to increase array size for value separator exceptions"); dwInsertedIndex = pi->cValueSeparatorExceptions; ++pi->cValueSeparatorExceptions; hr = StrAllocString(&pi->rgsczValueSeparatorExceptions[dwInsertedIndex], wzValueNamePrefix, 0); - ExitOnFailure(hr, "Failed to copy value separator exception"); + IniExitOnFailure(hr, "Failed to copy value separator exception"); LExit: return hr; @@ -185,7 +200,7 @@ extern "C" HRESULT DAPI IniSetCommentStyle( if (wzLinePrefix) { hr = StrAllocString(&pi->sczCommentLinePrefix, wzLinePrefix, 0); - ExitOnFailure(hr, "Failed to copy comment line prefix to ini struct: %ls", wzLinePrefix); + IniExitOnFailure(hr, "Failed to copy comment line prefix to ini struct: %ls", wzLinePrefix); } else { @@ -226,10 +241,10 @@ extern "C" HRESULT DAPI IniParse( BOOL fValuePrefix = (NULL != pi->sczValuePrefix); hr = StrAllocString(&pi->sczPath, wzPath, 0); - ExitOnFailure(hr, "Failed to copy path to ini struct: %ls", wzPath); + IniExitOnFailure(hr, "Failed to copy path to ini struct: %ls", wzPath); hr = FileToString(pi->sczPath, &sczContents, &pi->feEncoding); - ExitOnFailure(hr, "Failed to convert file to string: %ls", pi->sczPath); + IniExitOnFailure(hr, "Failed to convert file to string: %ls", pi->sczPath); if (pfeEncodingFound) { @@ -244,7 +259,7 @@ extern "C" HRESULT DAPI IniParse( dwValuePrefixLength = lstrlenW(pi->sczValuePrefix); hr = StrSplitAllocArray(&pi->rgsczLines, reinterpret_cast(&pi->cLines), sczContents, L"\n"); - ExitOnFailure(hr, "Failed to split INI file into lines"); + IniExitOnFailure(hr, "Failed to split INI file into lines"); for (DWORD i = 0; i < pi->cLines; ++i) { @@ -324,7 +339,7 @@ extern "C" HRESULT DAPI IniParse( { // There is an section starting here, let's keep track of it and move on hr = StrAllocString(&sczCurrentSection, wzOpenTagPrefix + lstrlenW(pi->sczOpenTagPrefix), wzOpenTagPostfix - (wzOpenTagPrefix + lstrlenW(pi->sczOpenTagPrefix))); - ExitOnFailure(hr, "Failed to record section name for line: %ls of INI file: %ls", pi->rgsczLines[i], pi->sczPath); + IniExitOnFailure(hr, "Failed to record section name for line: %ls of INI file: %ls", pi->rgsczLines[i], pi->sczPath); // Sections will be calculated dynamically after any set operations, so don't include this in the list of lines to remember for output ReleaseNullStr(pi->rgsczLines[i]); @@ -342,28 +357,28 @@ extern "C" HRESULT DAPI IniParse( } hr = MemEnsureArraySize(reinterpret_cast(&pi->rgivValues), pi->cValues + 1, sizeof(INI_VALUE), 100); - ExitOnFailure(hr, "Failed to increase array size for value array"); + IniExitOnFailure(hr, "Failed to increase array size for value array"); if (sczCurrentSection) { hr = StrAllocString(&sczName, sczCurrentSection, 0); - ExitOnFailure(hr, "Failed to copy current section name"); + IniExitOnFailure(hr, "Failed to copy current section name"); hr = StrAllocConcat(&sczName, wzSectionSeparator, 0); - ExitOnFailure(hr, "Failed to copy current section name"); + IniExitOnFailure(hr, "Failed to copy current section name"); } hr = StrAllocConcat(&sczName, wzValueBegin, wzValueSeparator - wzValueBegin); - ExitOnFailure(hr, "Failed to copy name"); + IniExitOnFailure(hr, "Failed to copy name"); hr = StrAllocString(&sczValue, wzValueSeparator + lstrlenW(pi->sczValueSeparator), 0); - ExitOnFailure(hr, "Failed to copy value"); + IniExitOnFailure(hr, "Failed to copy value"); hr = StrTrimWhitespace(&sczNameTrimmed, sczName); - ExitOnFailure(hr, "Failed to trim whitespace from name"); + IniExitOnFailure(hr, "Failed to trim whitespace from name"); hr = StrTrimWhitespace(&sczValueTrimmed, sczValue); - ExitOnFailure(hr, "Failed to trim whitespace from value"); + IniExitOnFailure(hr, "Failed to trim whitespace from value"); pi->rgivValues[pi->cValues].wzName = const_cast(sczNameTrimmed); sczNameTrimmed = NULL; @@ -397,7 +412,7 @@ LExit: extern "C" HRESULT DAPI IniGetValueList( __in_bcount(INI_HANDLE_BYTES) INI_HANDLE piHandle, - __deref_out_ecount_opt(pcValues) INI_VALUE** prgivValues, + __deref_out_ecount_opt(*pcValues) INI_VALUE** prgivValues, __out DWORD *pcValues ) { @@ -434,7 +449,7 @@ extern "C" HRESULT DAPI IniGetValue( if (NULL == pValue) { hr = E_NOTFOUND; - ExitOnFailure(hr, "Failed to check for INI value: %ls", wzValueName); + IniExitOnFailure(hr, "Failed to check for INI value: %ls", wzValueName); } if (NULL == pValue->wzValue) @@ -443,7 +458,7 @@ extern "C" HRESULT DAPI IniGetValue( } hr = StrAllocString(psczValue, pValue->wzValue, 0); - ExitOnFailure(hr, "Failed to make copy of value while looking up INI value named: %ls", wzValueName); + IniExitOnFailure(hr, "Failed to make copy of value while looking up INI value named: %ls", wzValueName); LExit: return hr; @@ -494,7 +509,7 @@ extern "C" HRESULT DAPI IniSetValue( { pi->fModified = TRUE; hr = StrAllocString(const_cast(&pValue->wzValue), wzValue, 0); - ExitOnFailure(hr, "Failed to update value INI value named: %ls", wzValueName); + IniExitOnFailure(hr, "Failed to update value INI value named: %ls", wzValueName); } ExitFunction1(hr = S_OK); @@ -504,7 +519,7 @@ extern "C" HRESULT DAPI IniSetValue( if (wzValueName) { hr = GetSectionPrefixFromName(wzValueName, &sczSectionPrefix); - ExitOnFailure(hr, "Failed to get section prefix from value name: %ls", wzValueName); + IniExitOnFailure(hr, "Failed to get section prefix from value name: %ls", wzValueName); } // If we have a section prefix, figure out the index to insert it (at the end of the section it belongs in) @@ -545,13 +560,13 @@ extern "C" HRESULT DAPI IniSetValue( pi->fModified = TRUE; hr = MemInsertIntoArray(reinterpret_cast(&pi->rgivValues), dwInsertIndex, 1, pi->cValues + 1, sizeof(INI_VALUE), 100); - ExitOnFailure(hr, "Failed to insert value into array"); + IniExitOnFailure(hr, "Failed to insert value into array"); hr = StrAllocString(&sczName, wzValueName, 0); - ExitOnFailure(hr, "Failed to copy name"); + IniExitOnFailure(hr, "Failed to copy name"); hr = StrAllocString(&sczValue, wzValue, 0); - ExitOnFailure(hr, "Failed to copy value"); + IniExitOnFailure(hr, "Failed to copy value"); pi->rgivValues[dwInsertIndex].wzName = const_cast(sczName); sczName = NULL; @@ -611,7 +626,7 @@ extern "C" HRESULT DAPI IniWriteFile( BOOL fSections = (pi->sczOpenTagPrefix) && (pi->sczOpenTagPostfix); hr = StrAllocString(&sczContents, L"", 0); - ExitOnFailure(hr, "Failed to begin contents string as empty string"); + IniExitOnFailure(hr, "Failed to begin contents string as empty string"); // Insert any beginning lines we didn't understand like comments if (0 < pi->cLines) @@ -619,10 +634,10 @@ extern "C" HRESULT DAPI IniWriteFile( while (pi->rgsczLines[dwLineArrayIndex]) { hr = StrAllocConcat(&sczContents, pi->rgsczLines[dwLineArrayIndex], 0); - ExitOnFailure(hr, "Failed to add previous line to ini output buffer in-memory"); + IniExitOnFailure(hr, "Failed to add previous line to ini output buffer in-memory"); hr = StrAllocConcat(&sczContents, L"\r\n", 2); - ExitOnFailure(hr, "Failed to add endline to ini output buffer in-memory"); + IniExitOnFailure(hr, "Failed to add endline to ini output buffer in-memory"); ++dwLineArrayIndex; } @@ -640,23 +655,23 @@ extern "C" HRESULT DAPI IniWriteFile( // First see if we need to write a section line hr = GetSectionPrefixFromName(pi->rgivValues[i].wzName, &sczNewSectionPrefix); - ExitOnFailure(hr, "Failed to get section prefix from name: %ls", pi->rgivValues[i].wzName); + IniExitOnFailure(hr, "Failed to get section prefix from name: %ls", pi->rgivValues[i].wzName); // If the new section prefix is different, write a section out for it if (fSections && sczNewSectionPrefix && (NULL == sczCurrentSectionPrefix || CSTR_EQUAL != ::CompareStringW(LOCALE_INVARIANT, 0, sczNewSectionPrefix, -1, sczCurrentSectionPrefix, -1))) { hr = StrAllocConcat(&sczContents, pi->sczOpenTagPrefix, 0); - ExitOnFailure(hr, "Failed to concat open tag prefix to string"); + IniExitOnFailure(hr, "Failed to concat open tag prefix to string"); // Exclude section separator (i.e. backslash) from new section prefix hr = StrAllocConcat(&sczContents, sczNewSectionPrefix, lstrlenW(sczNewSectionPrefix)-lstrlenW(wzSectionSeparator)); - ExitOnFailure(hr, "Failed to concat section name to string"); + IniExitOnFailure(hr, "Failed to concat section name to string"); hr = StrAllocConcat(&sczContents, pi->sczOpenTagPostfix, 0); - ExitOnFailure(hr, "Failed to concat open tag postfix to string"); + IniExitOnFailure(hr, "Failed to concat open tag postfix to string"); hr = StrAllocConcat(&sczContents, L"\r\n", 2); - ExitOnFailure(hr, "Failed to add endline to ini output buffer in-memory"); + IniExitOnFailure(hr, "Failed to add endline to ini output buffer in-memory"); ReleaseNullStr(sczCurrentSectionPrefix); sczCurrentSectionPrefix = sczNewSectionPrefix; @@ -674,10 +689,10 @@ extern "C" HRESULT DAPI IniWriteFile( } hr = StrAllocConcat(&sczContents, pi->rgsczLines[dwLineArrayIndex++], 0); - ExitOnFailure(hr, "Failed to add previous line to ini output buffer in-memory"); + IniExitOnFailure(hr, "Failed to add previous line to ini output buffer in-memory"); hr = StrAllocConcat(&sczContents, L"\r\n", 2); - ExitOnFailure(hr, "Failed to add endline to ini output buffer in-memory"); + IniExitOnFailure(hr, "Failed to add endline to ini output buffer in-memory"); } wzName = pi->rgivValues[i].wzName; @@ -690,20 +705,20 @@ extern "C" HRESULT DAPI IniWriteFile( if (pi->sczValuePrefix) { hr = StrAllocConcat(&sczContents, pi->sczValuePrefix, 0); - ExitOnFailure(hr, "Failed to concat value prefix to ini output buffer"); + IniExitOnFailure(hr, "Failed to concat value prefix to ini output buffer"); } hr = StrAllocConcat(&sczContents, wzName, 0); - ExitOnFailure(hr, "Failed to concat value name to ini output buffer"); + IniExitOnFailure(hr, "Failed to concat value name to ini output buffer"); hr = StrAllocConcat(&sczContents, pi->sczValueSeparator, 0); - ExitOnFailure(hr, "Failed to concat value separator to ini output buffer"); + IniExitOnFailure(hr, "Failed to concat value separator to ini output buffer"); hr = StrAllocConcat(&sczContents, pi->rgivValues[i].wzValue, 0); - ExitOnFailure(hr, "Failed to concat value to ini output buffer"); + IniExitOnFailure(hr, "Failed to concat value to ini output buffer"); hr = StrAllocConcat(&sczContents, L"\r\n", 2); - ExitOnFailure(hr, "Failed to add endline to ini output buffer in-memory"); + IniExitOnFailure(hr, "Failed to add endline to ini output buffer in-memory"); } // If no path was specified, use the path to the file we parsed @@ -713,7 +728,7 @@ extern "C" HRESULT DAPI IniWriteFile( } hr = FileFromString(wzPath, 0, sczContents, feEncoding); - ExitOnFailure(hr, "Failed to write INI contents out to file: %ls", wzPath); + IniExitOnFailure(hr, "Failed to write INI contents out to file: %ls", wzPath); LExit: ReleaseStr(sczContents); @@ -733,7 +748,7 @@ static void UninitializeIniValue( static HRESULT GetSectionPrefixFromName( __in_z LPCWSTR wzName, - __deref_out_z LPWSTR* psczOutput + __deref_inout_z LPWSTR* psczOutput ) { HRESULT hr = S_OK; @@ -745,7 +760,7 @@ static HRESULT GetSectionPrefixFromName( if (wzSectionDelimiter && wzSectionDelimiter != wzName) { hr = StrAllocString(psczOutput, wzName, wzSectionDelimiter - wzName + 1); - ExitOnFailure(hr, "Failed to copy section prefix"); + IniExitOnFailure(hr, "Failed to copy section prefix"); } LExit: diff --git a/src/dutil/jsonutil.cpp b/src/dutil/jsonutil.cpp index ba088705..3450ba59 100644 --- a/src/dutil/jsonutil.cpp +++ b/src/dutil/jsonutil.cpp @@ -2,6 +2,21 @@ #include "precomp.h" + +// Exit macros +#define JsonExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_JSONUTIL, x, s, __VA_ARGS__) +#define JsonExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_JSONUTIL, x, s, __VA_ARGS__) +#define JsonExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_JSONUTIL, x, s, __VA_ARGS__) +#define JsonExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_JSONUTIL, x, s, __VA_ARGS__) +#define JsonExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_JSONUTIL, x, s, __VA_ARGS__) +#define JsonExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_JSONUTIL, x, s, __VA_ARGS__) +#define JsonExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_JSONUTIL, p, x, e, s, __VA_ARGS__) +#define JsonExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_JSONUTIL, p, x, s, __VA_ARGS__) +#define JsonExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_JSONUTIL, p, x, e, s, __VA_ARGS__) +#define JsonExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_JSONUTIL, p, x, s, __VA_ARGS__) +#define JsonExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_JSONUTIL, e, x, s, __VA_ARGS__) +#define JsonExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_JSONUTIL, g, x, s, __VA_ARGS__) + const DWORD JSON_STACK_INCREMENT = 5; // Prototypes @@ -44,7 +59,7 @@ DAPI_(HRESULT) JsonInitializeReader( ::InitializeCriticalSection(&pReader->cs); hr = StrAllocString(&pReader->sczJson, wzJson, 0); - ExitOnFailure(hr, "Failed to allocate json string."); + JsonExitOnFailure(hr, "Failed to allocate json string."); pReader->pwz = pReader->sczJson; @@ -153,7 +168,7 @@ DAPI_(HRESULT) JsonReadNext( { ExitFunction(); } - ExitOnFailure(hr, "Failed to get next token."); + JsonExitOnFailure(hr, "Failed to get next token."); if (JSON_TOKEN_VALUE == *pToken) { @@ -214,10 +229,10 @@ DAPI_(HRESULT) JsonWriteBool( LPWSTR sczValue = NULL; hr = StrAllocString(&sczValue, fValue ? L"true" : L"false", 0); - ExitOnFailure(hr, "Failed to convert boolean to string."); + JsonExitOnFailure(hr, "Failed to convert boolean to string."); hr = DoValue(pWriter, sczValue); - ExitOnFailure(hr, "Failed to add boolean to JSON."); + JsonExitOnFailure(hr, "Failed to add boolean to JSON."); LExit: ReleaseStr(sczValue); @@ -234,10 +249,10 @@ DAPI_(HRESULT) JsonWriteNumber( LPWSTR sczValue = NULL; hr = StrAllocFormatted(&sczValue, L"%u", dwValue); - ExitOnFailure(hr, "Failed to convert number to string."); + JsonExitOnFailure(hr, "Failed to convert number to string."); hr = DoValue(pWriter, sczValue); - ExitOnFailure(hr, "Failed to add number to JSON."); + JsonExitOnFailure(hr, "Failed to add number to JSON."); LExit: ReleaseStr(sczValue); @@ -254,10 +269,10 @@ DAPI_(HRESULT) JsonWriteString( LPWSTR sczJsonString = NULL; hr = SerializeJsonString(&sczJsonString, wzValue); - ExitOnFailure(hr, "Failed to allocate string JSON."); + JsonExitOnFailure(hr, "Failed to allocate string JSON."); hr = DoValue(pWriter, sczJsonString); - ExitOnFailure(hr, "Failed to add string to JSON."); + JsonExitOnFailure(hr, "Failed to add string to JSON."); LExit: ReleaseStr(sczJsonString); @@ -272,7 +287,7 @@ DAPI_(HRESULT) JsonWriteArrayStart( HRESULT hr = S_OK; hr = DoStart(pWriter, JSON_TOKEN_ARRAY_START, L"["); - ExitOnFailure(hr, "Failed to start JSON array."); + JsonExitOnFailure(hr, "Failed to start JSON array."); LExit: return hr; @@ -286,7 +301,7 @@ DAPI_(HRESULT) JsonWriteArrayEnd( HRESULT hr = S_OK; hr = DoEnd(pWriter, JSON_TOKEN_ARRAY_END, L"]"); - ExitOnFailure(hr, "Failed to end JSON array."); + JsonExitOnFailure(hr, "Failed to end JSON array."); LExit: return hr; @@ -300,7 +315,7 @@ DAPI_(HRESULT) JsonWriteObjectStart( HRESULT hr = S_OK; hr = DoStart(pWriter, JSON_TOKEN_OBJECT_START, L"{"); - ExitOnFailure(hr, "Failed to start JSON object."); + JsonExitOnFailure(hr, "Failed to start JSON object."); LExit: return hr; @@ -316,10 +331,10 @@ DAPI_(HRESULT) JsonWriteObjectKey( LPWSTR sczObjectKey = NULL; hr = StrAllocFormatted(&sczObjectKey, L"\"%ls\":", wzKey); - ExitOnFailure(hr, "Failed to allocate JSON object key."); + JsonExitOnFailure(hr, "Failed to allocate JSON object key."); hr = DoKey(pWriter, sczObjectKey); - ExitOnFailure(hr, "Failed to add object key to JSON."); + JsonExitOnFailure(hr, "Failed to add object key to JSON."); LExit: ReleaseStr(sczObjectKey); @@ -334,7 +349,7 @@ DAPI_(HRESULT) JsonWriteObjectEnd( HRESULT hr = S_OK; hr = DoEnd(pWriter, JSON_TOKEN_OBJECT_END, L"}"); - ExitOnFailure(hr, "Failed to end JSON object."); + JsonExitOnFailure(hr, "Failed to end JSON object."); LExit: return hr; @@ -357,7 +372,7 @@ static HRESULT DoStart( ::EnterCriticalSection(&pWriter->cs); hr = EnsureTokenStack(pWriter); - ExitOnFailure(hr, "Failed to ensure token stack for start."); + JsonExitOnFailure(hr, "Failed to ensure token stack for start."); token = pWriter->rgTokenStack[pWriter->cTokens - 1]; switch (token) @@ -381,16 +396,16 @@ static HRESULT DoStart( hr = E_UNEXPECTED; break; } - ExitOnRootFailure(hr, "Cannot start array or object to JSON serializer now."); + JsonExitOnRootFailure(hr, "Cannot start array or object to JSON serializer now."); if (fNeedComma) { hr = StrAllocConcat(&pWriter->sczJson, L",", 0); - ExitOnFailure(hr, "Failed to add comma for start array or object to JSON."); + JsonExitOnFailure(hr, "Failed to add comma for start array or object to JSON."); } hr = StrAllocConcat(&pWriter->sczJson, wzStartString, 0); - ExitOnFailure(hr, "Failed to start JSON array or object."); + JsonExitOnFailure(hr, "Failed to start JSON array or object."); pWriter->rgTokenStack[pWriter->cTokens - 1] = token; if (fPushToken) @@ -418,7 +433,7 @@ static HRESULT DoEnd( if (!pWriter->rgTokenStack || 0 == pWriter->cTokens) { hr = E_UNEXPECTED; - ExitOnRootFailure(hr, "Failure to pop token because the stack is empty."); + JsonExitOnRootFailure(hr, "Failure to pop token because the stack is empty."); } else { @@ -427,12 +442,12 @@ static HRESULT DoEnd( (JSON_TOKEN_OBJECT_END == tokenEnd && JSON_TOKEN_OBJECT_START != token && JSON_TOKEN_OBJECT_VALUE != token)) { hr = E_UNEXPECTED; - ExitOnRootFailure(hr, "Failure to pop token because the stack did not match the expected token: %d", tokenEnd); + JsonExitOnRootFailure(hr, "Failure to pop token because the stack did not match the expected token: %d", tokenEnd); } } hr = StrAllocConcat(&pWriter->sczJson, wzEndString, 0); - ExitOnFailure(hr, "Failed to end JSON array or object."); + JsonExitOnFailure(hr, "Failed to end JSON array or object."); --pWriter->cTokens; @@ -454,7 +469,7 @@ static HRESULT DoKey( ::EnterCriticalSection(&pWriter->cs); hr = EnsureTokenStack(pWriter); - ExitOnFailure(hr, "Failed to ensure token stack for key."); + JsonExitOnFailure(hr, "Failed to ensure token stack for key."); token = pWriter->rgTokenStack[pWriter->cTokens - 1]; switch (token) @@ -472,16 +487,16 @@ static HRESULT DoKey( hr = E_UNEXPECTED; break; } - ExitOnRootFailure(hr, "Cannot add key to JSON serializer now."); + JsonExitOnRootFailure(hr, "Cannot add key to JSON serializer now."); if (fNeedComma) { hr = StrAllocConcat(&pWriter->sczJson, L",", 0); - ExitOnFailure(hr, "Failed to add comma for key to JSON."); + JsonExitOnFailure(hr, "Failed to add comma for key to JSON."); } hr = StrAllocConcat(&pWriter->sczJson, wzKey, 0); - ExitOnFailure(hr, "Failed to add key to JSON."); + JsonExitOnFailure(hr, "Failed to add key to JSON."); pWriter->rgTokenStack[pWriter->cTokens - 1] = token; @@ -503,7 +518,7 @@ static HRESULT DoValue( ::EnterCriticalSection(&pWriter->cs); hr = EnsureTokenStack(pWriter); - ExitOnFailure(hr, "Failed to ensure token stack for value."); + JsonExitOnFailure(hr, "Failed to ensure token stack for value."); token = pWriter->rgTokenStack[pWriter->cTokens - 1]; switch (token) @@ -528,23 +543,23 @@ static HRESULT DoValue( hr = E_UNEXPECTED; break; } - ExitOnRootFailure(hr, "Cannot add value to JSON serializer now."); + JsonExitOnRootFailure(hr, "Cannot add value to JSON serializer now."); if (fNeedComma) { hr = StrAllocConcat(&pWriter->sczJson, L",", 0); - ExitOnFailure(hr, "Failed to add comma for value to JSON."); + JsonExitOnFailure(hr, "Failed to add comma for value to JSON."); } if (wzValue) { hr = StrAllocConcat(&pWriter->sczJson, wzValue, 0); - ExitOnFailure(hr, "Failed to add value to JSON."); + JsonExitOnFailure(hr, "Failed to add value to JSON."); } else { hr = StrAllocConcat(&pWriter->sczJson, L"null", 0); - ExitOnFailure(hr, "Failed to add null value to JSON."); + JsonExitOnFailure(hr, "Failed to add null value to JSON."); } pWriter->rgTokenStack[pWriter->cTokens - 1] = token; @@ -563,7 +578,7 @@ static HRESULT EnsureTokenStack( DWORD cNumAlloc = pWriter->cTokens != 0 ? pWriter->cTokens : 0; hr = MemEnsureArraySize(reinterpret_cast(&pWriter->rgTokenStack), cNumAlloc, sizeof(JSON_TOKEN), JSON_STACK_INCREMENT); - ExitOnFailure(hr, "Failed to allocate JSON token stack."); + JsonExitOnFailure(hr, "Failed to allocate JSON token stack."); if (0 == pWriter->cTokens) { @@ -596,7 +611,7 @@ static HRESULT SerializeJsonString( } hr = StrAlloc(psczJsonString, cchRequired); - ExitOnFailure(hr, "Failed to allocate space for JSON string."); + JsonExitOnFailure(hr, "Failed to allocate space for JSON string."); LPWSTR pchTarget = *psczJsonString; diff --git a/src/dutil/locutil.cpp b/src/dutil/locutil.cpp index b3cc042c..c4567c03 100644 --- a/src/dutil/locutil.cpp +++ b/src/dutil/locutil.cpp @@ -2,6 +2,21 @@ #include "precomp.h" + +// Exit macros +#define LocExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_LOCUTIL, x, s, __VA_ARGS__) +#define LocExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_LOCUTIL, x, s, __VA_ARGS__) +#define LocExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_LOCUTIL, x, s, __VA_ARGS__) +#define LocExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_LOCUTIL, x, s, __VA_ARGS__) +#define LocExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_LOCUTIL, x, s, __VA_ARGS__) +#define LocExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_LOCUTIL, x, s, __VA_ARGS__) +#define LocExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_LOCUTIL, p, x, e, s, __VA_ARGS__) +#define LocExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_LOCUTIL, p, x, s, __VA_ARGS__) +#define LocExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_LOCUTIL, p, x, e, s, __VA_ARGS__) +#define LocExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_LOCUTIL, p, x, s, __VA_ARGS__) +#define LocExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_LOCUTIL, e, x, s, __VA_ARGS__) +#define LocExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_LOCUTIL, g, x, s, __VA_ARGS__) + // prototypes static HRESULT ParseWxl( __in IXMLDOMDocument* pixd, @@ -63,10 +78,10 @@ extern "C" HRESULT DAPI LocProbeForFile( if (wzLanguage && *wzLanguage) { hr = PathConcat(wzBasePath, wzLanguage, &sczProbePath); - ExitOnFailure(hr, "Failed to concat base path to language."); + LocExitOnFailure(hr, "Failed to concat base path to language."); hr = PathConcat(sczProbePath, wzLocFileName, &sczProbePath); - ExitOnFailure(hr, "Failed to concat loc file name to probe path."); + LocExitOnFailure(hr, "Failed to concat loc file name to probe path."); if (FileExistsEx(sczProbePath, NULL)) { @@ -81,16 +96,16 @@ extern "C" HRESULT DAPI LocProbeForFile( DWORD dwFlags = MUI_LANGUAGE_ID | MUI_MERGE_USER_FALLBACK | MUI_MERGE_SYSTEM_FALLBACK; if (!(*pvfnGetThreadPreferredUILanguages)(dwFlags, &nLangs, NULL, &cchLangs)) { - ExitWithLastError(hr, "GetThreadPreferredUILanguages failed to return buffer size."); + LocExitWithLastError(hr, "GetThreadPreferredUILanguages failed to return buffer size."); } hr = StrAlloc(&sczLangsBuff, cchLangs); - ExitOnFailure(hr, "Failed to allocate buffer for languages"); + LocExitOnFailure(hr, "Failed to allocate buffer for languages"); nLangs = 0; if (!(*pvfnGetThreadPreferredUILanguages)(dwFlags, &nLangs, sczLangsBuff, &cchLangs)) { - ExitWithLastError(hr, "GetThreadPreferredUILanguages failed to return language list."); + LocExitWithLastError(hr, "GetThreadPreferredUILanguages failed to return language list."); } LPWSTR szLangs = sczLangsBuff; @@ -98,14 +113,14 @@ extern "C" HRESULT DAPI LocProbeForFile( { // StrHexDecode assumes low byte is first. We'll need to swap the bytes once we parse out the value. hr = StrHexDecode(szLangs, reinterpret_cast(&langid), sizeof(langid)); - ExitOnFailure(hr, "Failed to parse langId."); + LocExitOnFailure(hr, "Failed to parse langId."); langid = MAKEWORD(HIBYTE(langid), LOBYTE(langid)); hr = StrAllocFormatted(&sczLangIdFile, L"%u\\%ls", langid, wzLocFileName); - ExitOnFailure(hr, "Failed to format user preferred langid."); + LocExitOnFailure(hr, "Failed to format user preferred langid."); hr = PathConcat(wzBasePath, sczLangIdFile, &sczProbePath); - ExitOnFailure(hr, "Failed to concat user preferred langid file name to base path."); + LocExitOnFailure(hr, "Failed to concat user preferred langid file name to base path."); if (FileExistsEx(sczProbePath, NULL)) { @@ -117,10 +132,10 @@ extern "C" HRESULT DAPI LocProbeForFile( langid = ::GetUserDefaultUILanguage(); hr = StrAllocFormatted(&sczLangIdFile, L"%u\\%ls", langid, wzLocFileName); - ExitOnFailure(hr, "Failed to format user langid."); + LocExitOnFailure(hr, "Failed to format user langid."); hr = PathConcat(wzBasePath, sczLangIdFile, &sczProbePath); - ExitOnFailure(hr, "Failed to concat user langid file name to base path."); + LocExitOnFailure(hr, "Failed to concat user langid file name to base path."); if (FileExistsEx(sczProbePath, NULL)) { @@ -132,10 +147,10 @@ extern "C" HRESULT DAPI LocProbeForFile( langid = MAKELANGID(langid & 0x3FF, SUBLANG_DEFAULT); hr = StrAllocFormatted(&sczLangIdFile, L"%u\\%ls", langid, wzLocFileName); - ExitOnFailure(hr, "Failed to format user langid (default sublang)."); + LocExitOnFailure(hr, "Failed to format user langid (default sublang)."); hr = PathConcat(wzBasePath, sczLangIdFile, &sczProbePath); - ExitOnFailure(hr, "Failed to concat user langid file name to base path (default sublang)."); + LocExitOnFailure(hr, "Failed to concat user langid file name to base path (default sublang)."); if (FileExistsEx(sczProbePath, NULL)) { @@ -146,10 +161,10 @@ extern "C" HRESULT DAPI LocProbeForFile( langid = ::GetSystemDefaultUILanguage(); hr = StrAllocFormatted(&sczLangIdFile, L"%u\\%ls", langid, wzLocFileName); - ExitOnFailure(hr, "Failed to format system langid."); + LocExitOnFailure(hr, "Failed to format system langid."); hr = PathConcat(wzBasePath, sczLangIdFile, &sczProbePath); - ExitOnFailure(hr, "Failed to concat system langid file name to base path."); + LocExitOnFailure(hr, "Failed to concat system langid file name to base path."); if (FileExistsEx(sczProbePath, NULL)) { @@ -161,10 +176,10 @@ extern "C" HRESULT DAPI LocProbeForFile( langid = MAKELANGID(langid & 0x3FF, SUBLANG_DEFAULT); hr = StrAllocFormatted(&sczLangIdFile, L"%u\\%ls", langid, wzLocFileName); - ExitOnFailure(hr, "Failed to format user langid (default sublang)."); + LocExitOnFailure(hr, "Failed to format user langid (default sublang)."); hr = PathConcat(wzBasePath, sczLangIdFile, &sczProbePath); - ExitOnFailure(hr, "Failed to concat user langid file name to base path (default sublang)."); + LocExitOnFailure(hr, "Failed to concat user langid file name to base path (default sublang)."); if (FileExistsEx(sczProbePath, NULL)) { @@ -174,7 +189,7 @@ extern "C" HRESULT DAPI LocProbeForFile( // Finally, look for the loc file in the base path. hr = PathConcat(wzBasePath, wzLocFileName, &sczProbePath); - ExitOnFailure(hr, "Failed to concat loc file name to base path."); + LocExitOnFailure(hr, "Failed to concat loc file name to base path."); if (!FileExistsEx(sczProbePath, NULL)) { @@ -203,10 +218,10 @@ extern "C" HRESULT DAPI LocLoadFromFile( IXMLDOMDocument* pixd = NULL; hr = XmlLoadDocumentFromFile(wzWxlFile, &pixd); - ExitOnFailure(hr, "Failed to load WXL file as XML document."); + LocExitOnFailure(hr, "Failed to load WXL file as XML document."); hr = ParseWxl(pixd, ppWixLoc); - ExitOnFailure(hr, "Failed to parse WXL."); + LocExitOnFailure(hr, "Failed to parse WXL."); LExit: ReleaseObject(pixd); @@ -227,16 +242,16 @@ extern "C" HRESULT DAPI LocLoadFromResource( IXMLDOMDocument* pixd = NULL; hr = ResReadData(hModule, szResource, &pvResource, &cbResource); - ExitOnFailure(hr, "Failed to read theme from resource."); + LocExitOnFailure(hr, "Failed to read theme from resource."); hr = StrAllocStringAnsi(&sczXml, reinterpret_cast(pvResource), cbResource, CP_UTF8); - ExitOnFailure(hr, "Failed to convert XML document data from UTF-8 to unicode string."); + LocExitOnFailure(hr, "Failed to convert XML document data from UTF-8 to unicode string."); hr = XmlLoadDocument(sczXml, &pixd); - ExitOnFailure(hr, "Failed to load theme resource as XML document."); + LocExitOnFailure(hr, "Failed to load theme resource as XML document."); hr = ParseWxl(pixd, ppWixLoc); - ExitOnFailure(hr, "Failed to parse WXL."); + LocExitOnFailure(hr, "Failed to parse WXL."); LExit: ReleaseObject(pixd); @@ -280,7 +295,7 @@ extern "C" HRESULT DAPI LocLocalizeString( for (DWORD i = 0; i < pWixLoc->cLocStrings; ++i) { hr = StrReplaceStringAll(ppsczInput, pWixLoc->rgLocStrings[i].wzId, pWixLoc->rgLocStrings[i].wzText); - ExitOnFailure(hr, "Localizing string failed."); + LocExitOnFailure(hr, "Localizing string failed."); } LExit: @@ -348,15 +363,15 @@ extern "C" HRESULT DAPI LocAddString( ++pWixLoc->cLocStrings; pWixLoc->rgLocStrings = static_cast(MemReAlloc(pWixLoc->rgLocStrings, sizeof(LOC_STRING) * pWixLoc->cLocStrings, TRUE)); - ExitOnNull(pWixLoc->rgLocStrings, hr, E_OUTOFMEMORY, "Failed to reallocate memory for localization strings."); + LocExitOnNull(pWixLoc->rgLocStrings, hr, E_OUTOFMEMORY, "Failed to reallocate memory for localization strings."); LOC_STRING* pLocString = pWixLoc->rgLocStrings + (pWixLoc->cLocStrings - 1); hr = StrAllocFormatted(&pLocString->wzId, L"#(loc.%s)", wzId); - ExitOnFailure(hr, "Failed to set localization string Id."); + LocExitOnFailure(hr, "Failed to set localization string Id."); hr = StrAllocString(&pLocString->wzText, wzLocString, 0); - ExitOnFailure(hr, "Failed to set localization string Text."); + LocExitOnFailure(hr, "Failed to set localization string Text."); pLocString->bOverridable = bOverridable; @@ -376,11 +391,11 @@ static HRESULT ParseWxl( WIX_LOCALIZATION* pWixLoc = NULL; pWixLoc = static_cast(MemAlloc(sizeof(WIX_LOCALIZATION), TRUE)); - ExitOnNull(pWixLoc, hr, E_OUTOFMEMORY, "Failed to allocate memory for Wxl file."); + LocExitOnNull(pWixLoc, hr, E_OUTOFMEMORY, "Failed to allocate memory for Wxl file."); // read the WixLocalization tag hr = pixd->get_documentElement(&pWxlElement); - ExitOnFailure(hr, "Failed to get localization element."); + LocExitOnFailure(hr, "Failed to get localization element."); // get the Language attribute if present pWixLoc->dwLangId = WIX_LOCALIZATION_LANGUAGE_NOT_SET; @@ -389,14 +404,14 @@ static HRESULT ParseWxl( { hr = S_OK; } - ExitOnFailure(hr, "Failed to get Language value."); + LocExitOnFailure(hr, "Failed to get Language value."); // store the strings and controls in a node list hr = ParseWxlStrings(pWxlElement, pWixLoc); - ExitOnFailure(hr, "Parsing localization strings failed."); + LocExitOnFailure(hr, "Parsing localization strings failed."); hr = ParseWxlControls(pWxlElement, pWixLoc); - ExitOnFailure(hr, "Parsing localization controls failed."); + LocExitOnFailure(hr, "Parsing localization controls failed."); *ppWixLoc = pWixLoc; pWixLoc = NULL; @@ -420,27 +435,27 @@ static HRESULT ParseWxlStrings( DWORD dwIdx = 0; hr = XmlSelectNodes(pElement, L"String", &pixnl); - ExitOnLastError(hr, "Failed to get String child nodes of Wxl File."); + LocExitOnLastError(hr, "Failed to get String child nodes of Wxl File."); hr = pixnl->get_length(reinterpret_cast(&pWixLoc->cLocStrings)); - ExitOnLastError(hr, "Failed to get number of String child nodes in Wxl File."); + LocExitOnLastError(hr, "Failed to get number of String child nodes in Wxl File."); if (0 < pWixLoc->cLocStrings) { pWixLoc->rgLocStrings = static_cast(MemAlloc(sizeof(LOC_STRING) * pWixLoc->cLocStrings, TRUE)); - ExitOnNull(pWixLoc->rgLocStrings, hr, E_OUTOFMEMORY, "Failed to allocate memory for localization strings."); + LocExitOnNull(pWixLoc->rgLocStrings, hr, E_OUTOFMEMORY, "Failed to allocate memory for localization strings."); while (S_OK == (hr = XmlNextElement(pixnl, &pixn, NULL))) { hr = ParseWxlString(pixn, dwIdx, pWixLoc); - ExitOnFailure(hr, "Failed to parse localization string."); + LocExitOnFailure(hr, "Failed to parse localization string."); ++dwIdx; ReleaseNullObject(pixn); } hr = S_OK; - ExitOnFailure(hr, "Failed to enumerate all localization strings."); + LocExitOnFailure(hr, "Failed to enumerate all localization strings."); } LExit: @@ -472,27 +487,27 @@ static HRESULT ParseWxlControls( DWORD dwIdx = 0; hr = XmlSelectNodes(pElement, L"UI|Control", &pixnl); - ExitOnLastError(hr, "Failed to get UI child nodes of Wxl File."); + LocExitOnLastError(hr, "Failed to get UI child nodes of Wxl File."); hr = pixnl->get_length(reinterpret_cast(&pWixLoc->cLocControls)); - ExitOnLastError(hr, "Failed to get number of UI child nodes in Wxl File."); + LocExitOnLastError(hr, "Failed to get number of UI child nodes in Wxl File."); if (0 < pWixLoc->cLocControls) { pWixLoc->rgLocControls = static_cast(MemAlloc(sizeof(LOC_CONTROL) * pWixLoc->cLocControls, TRUE)); - ExitOnNull(pWixLoc->rgLocControls, hr, E_OUTOFMEMORY, "Failed to allocate memory for localized controls."); + LocExitOnNull(pWixLoc->rgLocControls, hr, E_OUTOFMEMORY, "Failed to allocate memory for localized controls."); while (S_OK == (hr = XmlNextElement(pixnl, &pixn, NULL))) { hr = ParseWxlControl(pixn, dwIdx, pWixLoc); - ExitOnFailure(hr, "Failed to parse localized control."); + LocExitOnFailure(hr, "Failed to parse localized control."); ++dwIdx; ReleaseNullObject(pixn); } hr = S_OK; - ExitOnFailure(hr, "Failed to enumerate all localized controls."); + LocExitOnFailure(hr, "Failed to enumerate all localized controls."); } LExit: @@ -527,16 +542,16 @@ static HRESULT ParseWxlString( // Id hr = XmlGetAttribute(pixn, L"Id", &bstrText); - ExitOnFailure(hr, "Failed to get Xml attribute Id in Wxl file."); + LocExitOnFailure(hr, "Failed to get Xml attribute Id in Wxl file."); hr = StrAllocFormatted(&pLocString->wzId, L"#(loc.%s)", bstrText); - ExitOnFailure(hr, "Failed to duplicate Xml attribute Id in Wxl file."); + LocExitOnFailure(hr, "Failed to duplicate Xml attribute Id in Wxl file."); ReleaseNullBSTR(bstrText); // Overrideable hr = XmlGetAttribute(pixn, L"Overridable", &bstrText); - ExitOnFailure(hr, "Failed to get Xml attribute Overridable."); + LocExitOnFailure(hr, "Failed to get Xml attribute Overridable."); if (S_OK == hr) { @@ -547,10 +562,10 @@ static HRESULT ParseWxlString( // Text hr = XmlGetText(pixn, &bstrText); - ExitOnFailure(hr, "Failed to get Xml text in Wxl file."); + LocExitOnFailure(hr, "Failed to get Xml text in Wxl file."); hr = StrAllocString(&pLocString->wzText, bstrText, 0); - ExitOnFailure(hr, "Failed to duplicate Xml text in Wxl file."); + LocExitOnFailure(hr, "Failed to duplicate Xml text in Wxl file."); LExit: ReleaseBSTR(bstrText); @@ -572,39 +587,39 @@ static HRESULT ParseWxlControl( // Id hr = XmlGetAttribute(pixn, L"Control", &bstrText); - ExitOnFailure(hr, "Failed to get Xml attribute Control in Wxl file."); + LocExitOnFailure(hr, "Failed to get Xml attribute Control in Wxl file."); hr = StrAllocString(&pLocControl->wzControl, bstrText, 0); - ExitOnFailure(hr, "Failed to duplicate Xml attribute Control in Wxl file."); + LocExitOnFailure(hr, "Failed to duplicate Xml attribute Control in Wxl file."); ReleaseNullBSTR(bstrText); // X pLocControl->nX = LOC_CONTROL_NOT_SET; hr = XmlGetAttributeNumber(pixn, L"X", reinterpret_cast(&pLocControl->nX)); - ExitOnFailure(hr, "Failed to get control X attribute."); + LocExitOnFailure(hr, "Failed to get control X attribute."); // Y pLocControl->nY = LOC_CONTROL_NOT_SET; hr = XmlGetAttributeNumber(pixn, L"Y", reinterpret_cast(&pLocControl->nY)); - ExitOnFailure(hr, "Failed to get control Y attribute."); + LocExitOnFailure(hr, "Failed to get control Y attribute."); // Width pLocControl->nWidth = LOC_CONTROL_NOT_SET; hr = XmlGetAttributeNumber(pixn, L"Width", reinterpret_cast(&pLocControl->nWidth)); - ExitOnFailure(hr, "Failed to get control width attribute."); + LocExitOnFailure(hr, "Failed to get control width attribute."); // Height pLocControl->nHeight = LOC_CONTROL_NOT_SET; hr = XmlGetAttributeNumber(pixn, L"Height", reinterpret_cast(&pLocControl->nHeight)); - ExitOnFailure(hr, "Failed to get control height attribute."); + LocExitOnFailure(hr, "Failed to get control height attribute."); // Text hr = XmlGetText(pixn, &bstrText); - ExitOnFailure(hr, "Failed to get control text in Wxl file."); + LocExitOnFailure(hr, "Failed to get control text in Wxl file."); hr = StrAllocString(&pLocControl->wzText, bstrText, 0); - ExitOnFailure(hr, "Failed to duplicate control text in Wxl file."); + LocExitOnFailure(hr, "Failed to duplicate control text in Wxl file."); LExit: ReleaseBSTR(bstrText); diff --git a/src/dutil/logutil.cpp b/src/dutil/logutil.cpp index 438cdbb8..35251274 100644 --- a/src/dutil/logutil.cpp +++ b/src/dutil/logutil.cpp @@ -2,6 +2,21 @@ #include "precomp.h" + +// Exit macros +#define LoguExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_LOGUTIL, x, s, __VA_ARGS__) +#define LoguExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_LOGUTIL, x, s, __VA_ARGS__) +#define LoguExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_LOGUTIL, x, s, __VA_ARGS__) +#define LoguExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_LOGUTIL, x, s, __VA_ARGS__) +#define LoguExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_LOGUTIL, x, s, __VA_ARGS__) +#define LoguExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_LOGUTIL, x, s, __VA_ARGS__) +#define LoguExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_LOGUTIL, p, x, e, s, __VA_ARGS__) +#define LoguExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_LOGUTIL, p, x, s, __VA_ARGS__) +#define LoguExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_LOGUTIL, p, x, e, s, __VA_ARGS__) +#define LoguExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_LOGUTIL, p, x, s, __VA_ARGS__) +#define LoguExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_LOGUTIL, e, x, s, __VA_ARGS__) +#define LoguExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_LOGUTIL, g, x, s, __VA_ARGS__) + // globals static HMODULE LogUtil_hModule = NULL; static BOOL LogUtil_fDisabled = FALSE; @@ -110,23 +125,23 @@ extern "C" HRESULT DAPI LogOpen( if (wzExt && *wzExt) { hr = PathCreateTimeBasedTempFile(wzDirectory, wzLog, wzPostfix, wzExt, &LogUtil_sczLogPath, &LogUtil_hLog); - ExitOnFailure(hr, "Failed to create log based on current system time."); + LoguExitOnFailure(hr, "Failed to create log based on current system time."); } else { hr = PathConcat(wzDirectory, wzLog, &LogUtil_sczLogPath); - ExitOnFailure(hr, "Failed to combine the log path."); + LoguExitOnFailure(hr, "Failed to combine the log path."); hr = PathGetDirectory(LogUtil_sczLogPath, &sczLogDirectory); - ExitOnFailure(hr, "Failed to get log directory."); + LoguExitOnFailure(hr, "Failed to get log directory."); hr = DirEnsureExists(sczLogDirectory, NULL); - ExitOnFailure(hr, "Failed to ensure log file directory exists: %ls", sczLogDirectory); + LoguExitOnFailure(hr, "Failed to ensure log file directory exists: %ls", sczLogDirectory); LogUtil_hLog = ::CreateFileW(LogUtil_sczLogPath, GENERIC_WRITE, FILE_SHARE_READ, NULL, (fAppend) ? OPEN_ALWAYS : CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (INVALID_HANDLE_VALUE == LogUtil_hLog) { - ExitOnLastError(hr, "failed to create log file: %ls", LogUtil_sczLogPath); + LoguExitOnLastError(hr, "failed to create log file: %ls", LogUtil_sczLogPath); } if (fAppend) @@ -152,7 +167,7 @@ extern "C" HRESULT DAPI LogOpen( if (psczLogPath) { hr = StrAllocString(psczLogPath, LogUtil_sczLogPath, 0); - ExitOnFailure(hr, "Failed to copy log path."); + LoguExitOnFailure(hr, "Failed to copy log path."); } LExit: @@ -217,15 +232,15 @@ HRESULT DAPI LogRename( ReleaseFileHandle(LogUtil_hLog); hr = FileEnsureMove(LogUtil_sczLogPath, wzNewPath, TRUE, TRUE); - ExitOnFailure(hr, "Failed to move logfile to new location: %ls", wzNewPath); + LoguExitOnFailure(hr, "Failed to move logfile to new location: %ls", wzNewPath); hr = StrAllocString(&LogUtil_sczLogPath, wzNewPath, 0); - ExitOnFailure(hr, "Failed to store new logfile path: %ls", wzNewPath); + LoguExitOnFailure(hr, "Failed to store new logfile path: %ls", wzNewPath); LogUtil_hLog = ::CreateFileW(LogUtil_sczLogPath, GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (INVALID_HANDLE_VALUE == LogUtil_hLog) { - ExitOnLastError(hr, "failed to create log file: %ls", LogUtil_sczLogPath); + LoguExitOnLastError(hr, "failed to create log file: %ls", LogUtil_sczLogPath); } // Enable "append" mode by moving file pointer to the end @@ -307,7 +322,7 @@ HRESULT DAPI LogSetSpecialParams( else { hr = StrAllocConcat(&LogUtil_sczSpecialBeginLine, wzSpecialBeginLine, 0); - ExitOnFailure(hr, "Failed to allocate copy of special beginline string"); + LoguExitOnFailure(hr, "Failed to allocate copy of special beginline string"); } // Handle special string to be appended to every time stamp @@ -318,7 +333,7 @@ HRESULT DAPI LogSetSpecialParams( else { hr = StrAllocConcat(&LogUtil_sczSpecialAfterTimeStamp, wzSpecialAfterTimeStamp, 0); - ExitOnFailure(hr, "Failed to allocate copy of special post-timestamp string"); + LoguExitOnFailure(hr, "Failed to allocate copy of special post-timestamp string"); } // Handle special string to be appended before every full line @@ -329,7 +344,7 @@ HRESULT DAPI LogSetSpecialParams( else { hr = StrAllocConcat(&LogUtil_sczSpecialEndLine, wzSpecialEndLine, 0); - ExitOnFailure(hr, "Failed to allocate copy of special endline string"); + LoguExitOnFailure(hr, "Failed to allocate copy of special endline string"); } LExit: @@ -597,14 +612,14 @@ extern "C" HRESULT DAPI LogErrorStringArgs( LPWSTR sczMessage = NULL; hr = StrAllocStringAnsi(&sczFormat, szFormat, 0, CP_ACP); - ExitOnFailure(hr, "Failed to convert format string to wide character string"); + LoguExitOnFailure(hr, "Failed to convert format string to wide character string"); // format the string as a unicode string - this is necessary to be able to include // international characters in our output string. This does have the counterintuitive effect // that the caller's "%s" is interpreted differently // (so callers should use %hs for LPSTR and %ls for LPWSTR) hr = StrAllocFormattedArgs(&sczMessage, sczFormat, args); - ExitOnFailure(hr, "Failed to format error message: \"%ls\"", sczFormat); + LoguExitOnFailure(hr, "Failed to format error message: \"%ls\"", sczFormat); hr = LogStringLine(REPORT_ERROR, "Error 0x%x: %ls", hrError, sczMessage); @@ -636,14 +651,14 @@ extern "C" HRESULT DAPI LogErrorIdModule( WORD cStrings = 1; // guaranteed wzError is in the list hr = ::StringCchPrintfW(wzError, countof(wzError), L"0x%08x", hrError); - ExitOnFailure(hr, "failed to format error code: \"0%08x\"", hrError); + LoguExitOnFailure(hr, "failed to format error code: \"0%08x\"", hrError); cStrings += wzString1 ? 1 : 0; cStrings += wzString2 ? 1 : 0; cStrings += wzString3 ? 1 : 0; hr = LogIdModule(REPORT_ERROR, dwLogId, hModule, wzError, wzString1, wzString2, wzString3); - ExitOnFailure(hr, "Failed to log id module."); + LoguExitOnFailure(hr, "Failed to log id module."); LExit: return hr; @@ -771,7 +786,7 @@ extern "C" HRESULT LogStringWorkRaw( if (INVALID_HANDLE_VALUE == LogUtil_hLog) { hr = StrAnsiAllocConcat(&LogUtil_sczPreInitBuffer, szLogData, 0); - ExitOnFailure(hr, "Failed to concatenate string to pre-init buffer"); + LoguExitOnFailure(hr, "Failed to concatenate string to pre-init buffer"); ExitFunction1(hr = S_OK); } @@ -781,7 +796,7 @@ extern "C" HRESULT LogStringWorkRaw( { if (!::WriteFile(LogUtil_hLog, reinterpret_cast(szLogData) + cbTotal, cbLogData - cbTotal, &cbWrote, NULL)) { - ExitOnLastError(hr, "Failed to write output to log: %ls - %ls", LogUtil_sczLogPath, szLogData); + LoguExitOnLastError(hr, "Failed to write output to log: %ls - %hs", LogUtil_sczLogPath, szLogData); } cbTotal += cbWrote; @@ -816,7 +831,7 @@ static HRESULT LogIdWork( if (0 == cch) { - ExitOnLastError(hr, "failed to log id: %d", dwLogId); + LoguExitOnLastError(hr, "failed to log id: %d", dwLogId); } if (2 <= cch && L'\r' == pwz[cch-2] && L'\n' == pwz[cch-1]) @@ -850,14 +865,14 @@ static HRESULT LogStringWorkArgs( LPWSTR sczMessage = NULL; hr = StrAllocStringAnsi(&sczFormat, szFormat, 0, CP_ACP); - ExitOnFailure(hr, "Failed to convert format string to wide character string"); + LoguExitOnFailure(hr, "Failed to convert format string to wide character string"); // format the string as a unicode string hr = StrAllocFormattedArgs(&sczMessage, sczFormat, args); - ExitOnFailure(hr, "Failed to format message: \"%ls\"", sczFormat); + LoguExitOnFailure(hr, "Failed to format message: \"%ls\"", sczFormat); hr = LogStringWork(rl, 0, sczMessage, fLOGUTIL_NEWLINE); - ExitOnFailure(hr, "Failed to write formatted string to log:%ls", sczMessage); + LoguExitOnFailure(hr, "Failed to write formatted string to log:%ls", sczMessage); LExit: ReleaseStr(sczFormat); @@ -909,24 +924,24 @@ static HRESULT LogStringWork( hr = StrAllocFormatted(&scz, L"%ls[%04X:%04X][%04hu-%02hu-%02huT%02hu:%02hu:%02hu]%hs%03d:%ls %ls%ls", LogUtil_sczSpecialBeginLine ? LogUtil_sczSpecialBeginLine : L"", dwProcessId, dwThreadId, st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, szType, dwId, LogUtil_sczSpecialAfterTimeStamp ? LogUtil_sczSpecialAfterTimeStamp : L"", sczString, LogUtil_sczSpecialEndLine ? LogUtil_sczSpecialEndLine : L"\r\n"); - ExitOnFailure(hr, "Failed to format line prefix."); + LoguExitOnFailure(hr, "Failed to format line prefix."); } wzLogData = scz ? scz : sczString; // Convert to UTF-8 before writing out to the log file hr = StrAnsiAllocString(&sczMultiByte, wzLogData, 0, CP_UTF8); - ExitOnFailure(hr, "Failed to convert log string to UTF-8"); + LoguExitOnFailure(hr, "Failed to convert log string to UTF-8"); if (s_vpfLogStringWorkRaw) { hr = s_vpfLogStringWorkRaw(sczMultiByte, s_vpvLogStringWorkRawContext); - ExitOnFailure(hr, "Failed to write string to log using redirected function: %ls", sczString); + LoguExitOnFailure(hr, "Failed to write string to log using redirected function: %ls", sczString); } else { hr = LogStringWorkRaw(sczMultiByte); - ExitOnFailure(hr, "Failed to write string to log using default function: %ls", sczString); + LoguExitOnFailure(hr, "Failed to write string to log using default function: %ls", sczString); } LExit: diff --git a/src/dutil/memutil.cpp b/src/dutil/memutil.cpp index 578c65ee..c805a9c0 100644 --- a/src/dutil/memutil.cpp +++ b/src/dutil/memutil.cpp @@ -1,10 +1,23 @@ -#pragma once // Copyright (c) .NET Foundation and contributors. All rights reserved. Licensed under the Microsoft Reciprocal License. See LICENSE.TXT file in the project root for full license information. - #include "precomp.h" +// Exit macros +#define MemExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_MEMUTIL, x, s, __VA_ARGS__) +#define MemExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_MEMUTIL, x, s, __VA_ARGS__) +#define MemExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_MEMUTIL, x, s, __VA_ARGS__) +#define MemExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_MEMUTIL, x, s, __VA_ARGS__) +#define MemExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_MEMUTIL, x, s, __VA_ARGS__) +#define MemExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_MEMUTIL, x, s, __VA_ARGS__) +#define MemExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_MEMUTIL, p, x, e, s, __VA_ARGS__) +#define MemExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_MEMUTIL, p, x, s, __VA_ARGS__) +#define MemExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_MEMUTIL, p, x, e, s, __VA_ARGS__) +#define MemExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_MEMUTIL, p, x, s, __VA_ARGS__) +#define MemExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_MEMUTIL, e, x, s, __VA_ARGS__) +#define MemExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_MEMUTIL, g, x, s, __VA_ARGS__) + + #if DEBUG static BOOL vfMemInitialized = FALSE; #endif @@ -51,7 +64,7 @@ extern "C" HRESULT DAPI MemReAllocSecure( __in LPVOID pv, __in SIZE_T cbSize, __in BOOL fZero, - __out LPVOID* ppvNew + __deref_out LPVOID* ppvNew ) { // AssertSz(vfMemInitialized, "MemInitialize() not called, this would normally crash"); @@ -72,14 +85,14 @@ extern "C" HRESULT DAPI MemReAllocSecure( const SIZE_T cbCurrent = MemSize(pv); if (-1 == cbCurrent) { - ExitOnFailure(hr = E_INVALIDARG, "Failed to get memory size"); + MemExitOnRootFailure(hr = E_INVALIDARG, "Failed to get memory size"); } // HeapReAlloc may allocate more memory than requested. const SIZE_T cbNew = MemSize(pvNew); if (-1 == cbNew) { - ExitOnFailure(hr = E_INVALIDARG, "Failed to get memory size"); + MemExitOnRootFailure(hr = E_INVALIDARG, "Failed to get memory size"); } cbSize = cbNew; @@ -94,7 +107,7 @@ extern "C" HRESULT DAPI MemReAllocSecure( MemFree(pv); } } - ExitOnNull(pvNew, hr, E_OUTOFMEMORY, "Failed to reallocate memory"); + MemExitOnNull(pvNew, hr, E_OUTOFMEMORY, "Failed to reallocate memory"); *ppvNew = pvNew; pvNew = NULL; @@ -129,10 +142,10 @@ extern "C" HRESULT DAPI MemReAllocArray( SIZE_T cbNew = 0; hr = ::DWordAdd(cArray, dwNewItemCount, &cNew); - ExitOnFailure(hr, "Integer overflow when calculating new element count."); + MemExitOnFailure(hr, "Integer overflow when calculating new element count."); hr = ::SIZETMult(cNew, cbArrayType, &cbNew); - ExitOnFailure(hr, "Integer overflow when calculating new block size."); + MemExitOnFailure(hr, "Integer overflow when calculating new block size."); if (*ppvArray) { @@ -140,7 +153,7 @@ extern "C" HRESULT DAPI MemReAllocArray( if (cbCurrent < cbNew) { pvNew = MemReAlloc(*ppvArray, cbNew, TRUE); - ExitOnNull(pvNew, hr, E_OUTOFMEMORY, "Failed to allocate larger array."); + MemExitOnNull(pvNew, hr, E_OUTOFMEMORY, "Failed to allocate larger array."); *ppvArray = pvNew; } @@ -148,7 +161,7 @@ extern "C" HRESULT DAPI MemReAllocArray( else { pvNew = MemAlloc(cbNew, TRUE); - ExitOnNull(pvNew, hr, E_OUTOFMEMORY, "Failed to allocate new array."); + MemExitOnNull(pvNew, hr, E_OUTOFMEMORY, "Failed to allocate new array."); *ppvArray = pvNew; } @@ -159,7 +172,7 @@ LExit: extern "C" HRESULT DAPI MemEnsureArraySize( - __deref_out_bcount(cArray * cbArrayType) LPVOID* ppvArray, + __deref_inout_bcount(cArray * cbArrayType) LPVOID* ppvArray, __in DWORD cArray, __in SIZE_T cbArrayType, __in DWORD dwGrowthCount @@ -171,10 +184,10 @@ extern "C" HRESULT DAPI MemEnsureArraySize( SIZE_T cbNew = 0; hr = ::DWordAdd(cArray, dwGrowthCount, &cNew); - ExitOnFailure(hr, "Integer overflow when calculating new element count."); + MemExitOnFailure(hr, "Integer overflow when calculating new element count."); hr = ::SIZETMult(cNew, cbArrayType, &cbNew); - ExitOnFailure(hr, "Integer overflow when calculating new block size."); + MemExitOnFailure(hr, "Integer overflow when calculating new block size."); if (*ppvArray) { @@ -183,7 +196,7 @@ extern "C" HRESULT DAPI MemEnsureArraySize( if (cbCurrent < cbUsed) { pvNew = MemReAlloc(*ppvArray, cbNew, TRUE); - ExitOnNull(pvNew, hr, E_OUTOFMEMORY, "Failed to allocate array larger."); + MemExitOnNull(pvNew, hr, E_OUTOFMEMORY, "Failed to allocate array larger."); *ppvArray = pvNew; } @@ -191,7 +204,7 @@ extern "C" HRESULT DAPI MemEnsureArraySize( else { pvNew = MemAlloc(cbNew, TRUE); - ExitOnNull(pvNew, hr, E_OUTOFMEMORY, "Failed to allocate new array."); + MemExitOnNull(pvNew, hr, E_OUTOFMEMORY, "Failed to allocate new array."); *ppvArray = pvNew; } @@ -202,7 +215,7 @@ LExit: extern "C" HRESULT DAPI MemInsertIntoArray( - __deref_out_bcount((cExistingArray + cInsertItems) * cbArrayType) LPVOID* ppvArray, + __deref_inout_bcount((cExistingArray + cInsertItems) * cbArrayType) LPVOID* ppvArray, __in DWORD dwInsertIndex, __in DWORD cInsertItems, __in DWORD cExistingArray, @@ -220,7 +233,7 @@ extern "C" HRESULT DAPI MemInsertIntoArray( } hr = MemEnsureArraySize(ppvArray, cExistingArray + cInsertItems, cbArrayType, dwGrowthCount); - ExitOnFailure(hr, "Failed to resize array while inserting items"); + MemExitOnFailure(hr, "Failed to resize array while inserting items"); pbArray = reinterpret_cast(*ppvArray); for (i = cExistingArray + cInsertItems - 1; i > dwInsertIndex; --i) @@ -236,7 +249,7 @@ LExit: } extern "C" void DAPI MemRemoveFromArray( - __inout_bcount((cExistingArray + cInsertItems) * cbArrayType) LPVOID pvArray, + __inout_bcount((cExistingArray) * cbArrayType) LPVOID pvArray, __in DWORD dwRemoveIndex, __in DWORD cRemoveItems, __in DWORD cExistingArray, @@ -261,7 +274,7 @@ extern "C" void DAPI MemRemoveFromArray( } extern "C" void DAPI MemArraySwapItems( - __inout_bcount((cExistingArray) * cbArrayType) LPVOID pvArray, + __inout_bcount(cbArrayType) LPVOID pvArray, __in DWORD dwIndex1, __in DWORD dwIndex2, __in SIZE_T cbArrayType diff --git a/src/dutil/metautil.cpp b/src/dutil/metautil.cpp index 612b1127..109cd31e 100644 --- a/src/dutil/metautil.cpp +++ b/src/dutil/metautil.cpp @@ -9,6 +9,21 @@ #include "metautil.h" +// Exit macros +#define MetaExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_METAUTIL, x, s, __VA_ARGS__) +#define MetaExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_METAUTIL, x, s, __VA_ARGS__) +#define MetaExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_METAUTIL, x, s, __VA_ARGS__) +#define MetaExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_METAUTIL, x, s, __VA_ARGS__) +#define MetaExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_METAUTIL, x, s, __VA_ARGS__) +#define MetaExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_METAUTIL, x, s, __VA_ARGS__) +#define MetaExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_METAUTIL, p, x, e, s, __VA_ARGS__) +#define MetaExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_METAUTIL, p, x, s, __VA_ARGS__) +#define MetaExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_METAUTIL, p, x, e, s, __VA_ARGS__) +#define MetaExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_METAUTIL, p, x, s, __VA_ARGS__) +#define MetaExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_METAUTIL, e, x, s, __VA_ARGS__) +#define MetaExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_METAUTIL, g, x, s, __VA_ARGS__) + + // prototypes static void Sort( __in_ecount(cArray) DWORD dwArray[], @@ -75,7 +90,7 @@ extern "C" HRESULT DAPI MetaFindWebBase( hr = S_FALSE; // didn't find anything, try next one continue; } - ExitOnFailure(hr, "failed to get key from metabase while searching for web servers"); + MetaExitOnFailure(hr, "failed to get key from metabase while searching for web servers"); // if we have an IIsWebServer store the key if (0 == lstrcmpW(L"IIsWebServer", (LPCWSTR)mr.pbMDData)) @@ -83,7 +98,7 @@ extern "C" HRESULT DAPI MetaFindWebBase( hr = MetaGetValue(piMetabase, METADATA_MASTER_ROOT_HANDLE, wzKey, &mrAddress); if (MD_ERROR_DATA_NOT_FOUND == hr) hr = S_FALSE; - ExitOnFailure(hr, "failed to get address from metabase while searching for web servers"); + MetaExitOnFailure(hr, "failed to get address from metabase while searching for web servers"); // break down the first address into parts pwzIPExists = reinterpret_cast(mrAddress.pbMDData); @@ -111,7 +126,7 @@ extern "C" HRESULT DAPI MetaFindWebBase( { // if the passed in buffer wasn't big enough hr = ::StringCchCopyW(wzWebBase, cchWebBase, wzKey); - ExitOnFailure(hr, "failed to copy in web base: %ls", wzKey); + MetaExitOnFailure(hr, "failed to copy in web base: %ls", wzKey); fFound = TRUE; break; @@ -182,7 +197,7 @@ extern "C" HRESULT DAPI MetaFindFreeWebBase( hr = S_FALSE; // didn't find anything, try next one continue; } - ExitOnFailure(hr, "failed to get key from metabase while searching for free web root"); + MetaExitOnFailure(hr, "failed to get key from metabase while searching for free web root"); // if we have a IIsWebServer get the address information if (0 == lstrcmpW(L"IIsWebServer", reinterpret_cast(mr.pbMDData))) @@ -190,7 +205,7 @@ extern "C" HRESULT DAPI MetaFindFreeWebBase( if (cSubKeys >= countof(dwSubKeys)) { hr = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); - ExitOnFailure(hr, "Insufficient buffer to track all sub-WebSites"); + MetaExitOnFailure(hr, "Insufficient buffer to track all sub-WebSites"); } dwSubKeys[cSubKeys] = wcstol(wzSubkey, NULL, 10); @@ -201,7 +216,7 @@ extern "C" HRESULT DAPI MetaFindFreeWebBase( if (E_NOMOREITEMS == hr) hr = S_OK; - ExitOnFailure(hr, "failed to find free web root"); + MetaExitOnFailure(hr, "failed to find free web root"); // find the lowest free web root dwKey = 1; @@ -270,18 +285,18 @@ extern "C" HRESULT DAPI MetaGetValue( if (!piMetabase) { hr = ::CoInitialize(NULL); - ExitOnFailure(hr, "failed to initialize COM"); + MetaExitOnFailure(hr, "failed to initialize COM"); fInitialized = TRUE; hr = ::CoCreateInstance(CLSID_MSAdminBase, NULL, CLSCTX_ALL, IID_IMSAdminBase, reinterpret_cast(&piMetabase)); - ExitOnFailure(hr, "failed to get IID_IMSAdminBaseW object"); + MetaExitOnFailure(hr, "failed to get IID_IMSAdminBaseW object"); } if (!pmr->pbMDData) { pmr->dwMDDataLen = 256; pmr->pbMDData = static_cast(MemAlloc(pmr->dwMDDataLen, TRUE)); - ExitOnNull(pmr->pbMDData, hr, E_OUTOFMEMORY, "failed to allocate memory for metabase value"); + MetaExitOnNull(pmr->pbMDData, hr, E_OUTOFMEMORY, "failed to allocate memory for metabase value"); } else // set the size of the data to the actual size of the memory pmr->dwMDDataLen = (DWORD)MemSize(pmr->pbMDData); @@ -291,12 +306,12 @@ extern "C" HRESULT DAPI MetaGetValue( { pmr->dwMDDataLen = cbRequired; BYTE* pb = static_cast(MemReAlloc(pmr->pbMDData, pmr->dwMDDataLen, TRUE)); - ExitOnNull(pb, hr, E_OUTOFMEMORY, "failed to reallocate memory for metabase value"); + MetaExitOnNull(pb, hr, E_OUTOFMEMORY, "failed to reallocate memory for metabase value"); pmr->pbMDData = pb; hr = piMetabase->GetData(mhKey, wzKey, pmr, &cbRequired); } - ExitOnFailure(hr, "failed to get metabase data"); + MetaExitOnFailure(hr, "failed to get metabase data"); LExit: if (fInitialized) diff --git a/src/dutil/monutil.cpp b/src/dutil/monutil.cpp index 6f280538..6a7f0596 100644 --- a/src/dutil/monutil.cpp +++ b/src/dutil/monutil.cpp @@ -2,6 +2,21 @@ #include "precomp.h" + +// Exit macros +#define MonExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_MONUTIL, x, s, __VA_ARGS__) +#define MonExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_MONUTIL, x, s, __VA_ARGS__) +#define MonExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_MONUTIL, x, s, __VA_ARGS__) +#define MonExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_MONUTIL, x, s, __VA_ARGS__) +#define MonExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_MONUTIL, x, s, __VA_ARGS__) +#define MonExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_MONUTIL, x, s, __VA_ARGS__) +#define MonExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_MONUTIL, p, x, e, s, __VA_ARGS__) +#define MonExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_MONUTIL, p, x, s, __VA_ARGS__) +#define MonExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_MONUTIL, p, x, e, s, __VA_ARGS__) +#define MonExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_MONUTIL, p, x, s, __VA_ARGS__) +#define MonExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_MONUTIL, e, x, s, __VA_ARGS__) +#define MonExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_MONUTIL, g, x, s, __VA_ARGS__) + const int MON_THREAD_GROWTH = 5; const int MON_ARRAY_GROWTH = 40; const int MON_MAX_MONITORS_PER_THREAD = 63; @@ -218,10 +233,10 @@ static void MonRequestDestroy( __in MON_REQUEST *pRequest ); static void MonAddMessageDestroy( - __in MON_ADD_MESSAGE *pMessage + __in_opt MON_ADD_MESSAGE *pMessage ); static void MonRemoveMessageDestroy( - __in MON_REMOVE_MESSAGE *pMessage + __in_opt MON_REMOVE_MESSAGE *pMessage ); static BOOL GetRecursiveFlag( __in MON_REQUEST *pRequest, @@ -262,7 +277,7 @@ static HRESULT UpdateWaitStatus( __in HRESULT hrNewStatus, __inout MON_WAITER_CONTEXT *pWaiterContext, __in DWORD dwRequestIndex, - __out DWORD *pdwNewRequestIndex + __out_opt DWORD *pdwNewRequestIndex ); extern "C" HRESULT DAPI MonCreate( @@ -277,11 +292,11 @@ extern "C" HRESULT DAPI MonCreate( HRESULT hr = S_OK; DWORD dwRetries = MON_THREAD_INIT_RETRIES; - ExitOnNull(pHandle, hr, E_INVALIDARG, "Pointer to handle not specified while creating monitor"); + MonExitOnNull(pHandle, hr, E_INVALIDARG, "Pointer to handle not specified while creating monitor"); // Allocate the struct *pHandle = static_cast(MemAlloc(sizeof(MON_STRUCT), TRUE)); - ExitOnNull(*pHandle, hr, E_OUTOFMEMORY, "Failed to allocate monitor object"); + MonExitOnNull(*pHandle, hr, E_OUTOFMEMORY, "Failed to allocate monitor object"); MON_STRUCT *pm = static_cast(*pHandle); @@ -294,7 +309,7 @@ extern "C" HRESULT DAPI MonCreate( pm->hCoordinatorThread = ::CreateThread(NULL, 0, CoordinatorThread, pm, 0, &pm->dwCoordinatorThreadId); if (!pm->hCoordinatorThread) { - ExitWithLastError(hr, "Failed to create waiter thread."); + MonExitWithLastError(hr, "Failed to create waiter thread."); } // Ensure the created thread initializes its message queue. It does this first thing, so if it doesn't within 10 seconds, there must be a huge problem. @@ -307,7 +322,7 @@ extern "C" HRESULT DAPI MonCreate( if (0 == dwRetries) { hr = E_UNEXPECTED; - ExitOnFailure(hr, "Waiter thread apparently never initialized its message queue."); + MonExitOnFailure(hr, "Waiter thread apparently never initialized its message queue."); } LExit: @@ -329,13 +344,13 @@ extern "C" HRESULT DAPI MonAddDirectory( MON_ADD_MESSAGE *pMessage = NULL; hr = StrAllocString(&sczOriginalPathRequest, wzDirectory, 0); - ExitOnFailure(hr, "Failed to convert directory string to UNC path"); + MonExitOnFailure(hr, "Failed to convert directory string to UNC path"); hr = PathBackslashTerminate(&sczOriginalPathRequest); - ExitOnFailure(hr, "Failed to ensure directory ends in backslash"); + MonExitOnFailure(hr, "Failed to ensure directory ends in backslash"); pMessage = reinterpret_cast(MemAlloc(sizeof(MON_ADD_MESSAGE), TRUE)); - ExitOnNull(pMessage, hr, E_OUTOFMEMORY, "Failed to allocate memory for message"); + MonExitOnNull(pMessage, hr, E_OUTOFMEMORY, "Failed to allocate memory for message"); if (sczOriginalPathRequest[0] == L'\\' && sczOriginalPathRequest[1] == L'\\') { @@ -356,7 +371,7 @@ extern "C" HRESULT DAPI MonAddDirectory( hr = S_OK; hr = StrAllocString(&sczDirectory, sczOriginalPathRequest, 0); - ExitOnFailure(hr, "Failed to copy original path request: %ls", sczOriginalPathRequest); + MonExitOnFailure(hr, "Failed to copy original path request: %ls", sczOriginalPathRequest); } pMessage->handle = INVALID_HANDLE_VALUE; @@ -369,14 +384,14 @@ extern "C" HRESULT DAPI MonAddDirectory( sczOriginalPathRequest = NULL; hr = PathGetHierarchyArray(sczDirectory, &pMessage->request.rgsczPathHierarchy, reinterpret_cast(&pMessage->request.cPathHierarchy)); - ExitOnFailure(hr, "Failed to get hierarchy array for path %ls", sczDirectory); + MonExitOnFailure(hr, "Failed to get hierarchy array for path %ls", sczDirectory); if (0 < pMessage->request.cPathHierarchy) { pMessage->request.hrStatus = InitiateWait(&pMessage->request, &pMessage->handle); if (!::PostThreadMessageW(pm->dwCoordinatorThreadId, MON_MESSAGE_ADD, reinterpret_cast(pMessage), 0)) { - ExitWithLastError(hr, "Failed to send message to worker thread to add directory wait for path %ls", sczDirectory); + MonExitWithLastError(hr, "Failed to send message to worker thread to add directory wait for path %ls", sczDirectory); } pMessage = NULL; } @@ -405,16 +420,16 @@ extern "C" HRESULT DAPI MonAddRegKey( MON_ADD_MESSAGE *pMessage = NULL; hr = StrAllocString(&sczSubKey, wzSubKey, 0); - ExitOnFailure(hr, "Failed to copy subkey string"); + MonExitOnFailure(hr, "Failed to copy subkey string"); hr = PathBackslashTerminate(&sczSubKey); - ExitOnFailure(hr, "Failed to ensure subkey path ends in backslash"); + MonExitOnFailure(hr, "Failed to ensure subkey path ends in backslash"); pMessage = reinterpret_cast(MemAlloc(sizeof(MON_ADD_MESSAGE), TRUE)); - ExitOnNull(pMessage, hr, E_OUTOFMEMORY, "Failed to allocate memory for message"); + MonExitOnNull(pMessage, hr, E_OUTOFMEMORY, "Failed to allocate memory for message"); pMessage->handle = ::CreateEventW(NULL, TRUE, FALSE, NULL); - ExitOnNullWithLastError(pMessage->handle, hr, "Failed to create anonymous event for regkey monitor"); + MonExitOnNullWithLastError(pMessage->handle, hr, "Failed to create anonymous event for regkey monitor"); pMessage->request.type = MON_REGKEY; pMessage->request.regkey.hkRoot = hkRoot; @@ -425,16 +440,16 @@ extern "C" HRESULT DAPI MonAddRegKey( pMessage->request.pvContext = pvRegKeyContext; hr = PathGetHierarchyArray(sczSubKey, &pMessage->request.rgsczPathHierarchy, reinterpret_cast(&pMessage->request.cPathHierarchy)); - ExitOnFailure(hr, "Failed to get hierarchy array for subkey %ls", sczSubKey); + MonExitOnFailure(hr, "Failed to get hierarchy array for subkey %ls", sczSubKey); if (0 < pMessage->request.cPathHierarchy) { pMessage->request.hrStatus = InitiateWait(&pMessage->request, &pMessage->handle); - ExitOnFailure(hr, "Failed to initiate wait"); + MonExitOnFailure(hr, "Failed to initiate wait"); if (!::PostThreadMessageW(pm->dwCoordinatorThreadId, MON_MESSAGE_ADD, reinterpret_cast(pMessage), 0)) { - ExitWithLastError(hr, "Failed to send message to worker thread to add directory wait for regkey %ls", sczSubKey); + MonExitWithLastError(hr, "Failed to send message to worker thread to add directory wait for regkey %ls", sczSubKey); } pMessage = NULL; } @@ -458,23 +473,23 @@ extern "C" HRESULT DAPI MonRemoveDirectory( MON_REMOVE_MESSAGE *pMessage = NULL; hr = StrAllocString(&sczDirectory, wzDirectory, 0); - ExitOnFailure(hr, "Failed to copy directory string"); + MonExitOnFailure(hr, "Failed to copy directory string"); hr = PathBackslashTerminate(&sczDirectory); - ExitOnFailure(hr, "Failed to ensure directory ends in backslash"); + MonExitOnFailure(hr, "Failed to ensure directory ends in backslash"); pMessage = reinterpret_cast(MemAlloc(sizeof(MON_REMOVE_MESSAGE), TRUE)); - ExitOnNull(pMessage, hr, E_OUTOFMEMORY, "Failed to allocate memory for message"); + MonExitOnNull(pMessage, hr, E_OUTOFMEMORY, "Failed to allocate memory for message"); pMessage->type = MON_DIRECTORY; pMessage->fRecursive = fRecursive; hr = StrAllocString(&pMessage->directory.sczDirectory, sczDirectory, 0); - ExitOnFailure(hr, "Failed to allocate copy of directory string"); + MonExitOnFailure(hr, "Failed to allocate copy of directory string"); if (!::PostThreadMessageW(pm->dwCoordinatorThreadId, MON_MESSAGE_REMOVE, reinterpret_cast(pMessage), 0)) { - ExitWithLastError(hr, "Failed to send message to worker thread to add directory wait for path %ls", sczDirectory); + MonExitWithLastError(hr, "Failed to send message to worker thread to add directory wait for path %ls", sczDirectory); } pMessage = NULL; @@ -498,13 +513,13 @@ extern "C" HRESULT DAPI MonRemoveRegKey( MON_REMOVE_MESSAGE *pMessage = NULL; hr = StrAllocString(&sczSubKey, wzSubKey, 0); - ExitOnFailure(hr, "Failed to copy subkey string"); + MonExitOnFailure(hr, "Failed to copy subkey string"); hr = PathBackslashTerminate(&sczSubKey); - ExitOnFailure(hr, "Failed to ensure subkey path ends in backslash"); + MonExitOnFailure(hr, "Failed to ensure subkey path ends in backslash"); pMessage = reinterpret_cast(MemAlloc(sizeof(MON_REMOVE_MESSAGE), TRUE)); - ExitOnNull(pMessage, hr, E_OUTOFMEMORY, "Failed to allocate memory for message"); + MonExitOnNull(pMessage, hr, E_OUTOFMEMORY, "Failed to allocate memory for message"); pMessage->type = MON_REGKEY; pMessage->regkey.hkRoot = hkRoot; @@ -512,11 +527,11 @@ extern "C" HRESULT DAPI MonRemoveRegKey( pMessage->fRecursive = fRecursive; hr = StrAllocString(&pMessage->regkey.sczSubKey, sczSubKey, 0); - ExitOnFailure(hr, "Failed to allocate copy of directory string"); + MonExitOnFailure(hr, "Failed to allocate copy of directory string"); if (!::PostThreadMessageW(pm->dwCoordinatorThreadId, MON_MESSAGE_REMOVE, reinterpret_cast(pMessage), 0)) { - ExitWithLastError(hr, "Failed to send message to worker thread to add directory wait for path %ls", sczSubKey); + MonExitWithLastError(hr, "Failed to send message to worker thread to add directory wait for path %ls", sczSubKey); } pMessage = NULL; @@ -543,7 +558,7 @@ extern "C" void DAPI MonDestroy( // It already halted, or doesn't exist for some other reason, so let's just ignore it and clean up er = ERROR_SUCCESS; } - ExitOnWin32Error(er, hr, "Failed to send message to background thread to halt"); + MonExitOnWin32Error(er, hr, "Failed to send message to background thread to halt"); } if (pm->hCoordinatorThread) @@ -577,10 +592,10 @@ static void MonRequestDestroy( } static void MonAddMessageDestroy( - __in MON_ADD_MESSAGE *pMessage + __in_opt MON_ADD_MESSAGE *pMessage ) { - if (NULL != pMessage) + if (pMessage) { MonRequestDestroy(&pMessage->request); if (MON_DIRECTORY == pMessage->request.type && INVALID_HANDLE_VALUE != pMessage->handle) @@ -597,10 +612,10 @@ static void MonAddMessageDestroy( } static void MonRemoveMessageDestroy( - __in MON_REMOVE_MESSAGE *pMessage + __in_opt MON_REMOVE_MESSAGE *pMessage ) { - if (NULL != pMessage) + if (pMessage) { switch (pMessage->type) { @@ -642,17 +657,17 @@ static DWORD WINAPI CoordinatorThread( pm->fCoordinatorThreadMessageQueueInitialized = TRUE; hr = CreateMonWindow(pm, &pm->hwnd); - ExitOnFailure(hr, "Failed to create window for status update thread"); + MonExitOnFailure(hr, "Failed to create window for status update thread"); ::WSAStartup(MAKEWORD(2, 2), &wsaData); hr = WaitForNetworkChanges(&hMonitor, pm); - ExitOnFailure(hr, "Failed to wait for network changes"); + MonExitOnFailure(hr, "Failed to wait for network changes"); uTimerSuccessfulNetworkRetry = ::SetTimer(NULL, 1, MON_THREAD_NETWORK_SUCCESSFUL_RETRY_IN_MS, NULL); if (0 == uTimerSuccessfulNetworkRetry) { - ExitWithLastError(hr, "Failed to set timer for network successful retry"); + MonExitWithLastError(hr, "Failed to set timer for network successful retry"); } while (0 != (fRet = ::GetMessageW(&msg, NULL, 0, 0))) @@ -660,7 +675,7 @@ static DWORD WINAPI CoordinatorThread( if (-1 == fRet) { hr = E_UNEXPECTED; - ExitOnRootFailure(hr, "Unexpected return value from message pump."); + MonExitOnRootFailure(hr, "Unexpected return value from message pump."); } else { @@ -684,12 +699,12 @@ static DWORD WINAPI CoordinatorThread( else { hr = MemEnsureArraySize(reinterpret_cast(&pm->rgWaiterThreads), pm->cWaiterThreads + 1, sizeof(MON_WAITER_INFO), MON_THREAD_GROWTH); - ExitOnFailure(hr, "Failed to grow waiter thread array size"); + MonExitOnFailure(hr, "Failed to grow waiter thread array size"); ++pm->cWaiterThreads; dwThreadIndex = pm->cWaiterThreads - 1; pm->rgWaiterThreads[dwThreadIndex].pWaiterContext = reinterpret_cast(MemAlloc(sizeof(MON_WAITER_CONTEXT), TRUE)); - ExitOnNull(pm->rgWaiterThreads[dwThreadIndex].pWaiterContext, hr, E_OUTOFMEMORY, "Failed to allocate waiter context struct"); + MonExitOnNull(pm->rgWaiterThreads[dwThreadIndex].pWaiterContext, hr, E_OUTOFMEMORY, "Failed to allocate waiter context struct"); pWaiterContext = pm->rgWaiterThreads[dwThreadIndex].pWaiterContext; pWaiterContext->dwCoordinatorThreadId = ::GetCurrentThreadId(); pWaiterContext->vpfMonGeneral = pm->vpfMonGeneral; @@ -698,16 +713,16 @@ static DWORD WINAPI CoordinatorThread( pWaiterContext->pvContext = pm->pvContext; hr = MemEnsureArraySize(reinterpret_cast(&pWaiterContext->rgHandles), MON_MAX_MONITORS_PER_THREAD + 1, sizeof(HANDLE), 0); - ExitOnFailure(hr, "Failed to allocate first handle"); + MonExitOnFailure(hr, "Failed to allocate first handle"); pWaiterContext->cHandles = 1; pWaiterContext->rgHandles[0] = ::CreateEventW(NULL, FALSE, FALSE, NULL); - ExitOnNullWithLastError(pWaiterContext->rgHandles[0], hr, "Failed to create general event"); + MonExitOnNullWithLastError(pWaiterContext->rgHandles[0], hr, "Failed to create general event"); pWaiterContext->hWaiterThread = ::CreateThread(NULL, 0, WaiterThread, pWaiterContext, 0, &pWaiterContext->dwWaiterThreadId); if (!pWaiterContext->hWaiterThread) { - ExitWithLastError(hr, "Failed to create waiter thread."); + MonExitWithLastError(hr, "Failed to create waiter thread."); } dwRetries = MON_THREAD_INIT_RETRIES; @@ -720,19 +735,19 @@ static DWORD WINAPI CoordinatorThread( if (0 == dwRetries) { hr = E_UNEXPECTED; - ExitOnFailure(hr, "Waiter thread apparently never initialized its message queue."); + MonExitOnFailure(hr, "Waiter thread apparently never initialized its message queue."); } } ++pm->rgWaiterThreads[dwThreadIndex].cMonitorCount; if (!::PostThreadMessageW(pWaiterContext->dwWaiterThreadId, MON_MESSAGE_ADD, msg.wParam, 0)) { - ExitWithLastError(hr, "Failed to send message to waiter thread to add monitor"); + MonExitWithLastError(hr, "Failed to send message to waiter thread to add monitor"); } if (!::SetEvent(pWaiterContext->rgHandles[0])) { - ExitWithLastError(hr, "Failed to set event to notify waiter thread of incoming message"); + MonExitWithLastError(hr, "Failed to set event to notify waiter thread of incoming message"); } break; @@ -746,17 +761,17 @@ static DWORD WINAPI CoordinatorThread( pRemoveMessage = reinterpret_cast(msg.wParam); hr = DuplicateRemoveMessage(pRemoveMessage, &pTempRemoveMessage); - ExitOnFailure(hr, "Failed to duplicate remove message"); + MonExitOnFailure(hr, "Failed to duplicate remove message"); if (!::PostThreadMessageW(pWaiterContext->dwWaiterThreadId, MON_MESSAGE_REMOVE, reinterpret_cast(pTempRemoveMessage), msg.lParam)) { - ExitWithLastError(hr, "Failed to send message to waiter thread to add monitor"); + MonExitWithLastError(hr, "Failed to send message to waiter thread to add monitor"); } pTempRemoveMessage = NULL; if (!::SetEvent(pWaiterContext->rgHandles[0])) { - ExitWithLastError(hr, "Failed to set event to notify waiter thread of incoming remove message"); + MonExitWithLastError(hr, "Failed to set event to notify waiter thread of incoming remove message"); } } MonRemoveMessageDestroy(pRemoveMessage); @@ -774,7 +789,7 @@ static DWORD WINAPI CoordinatorThread( { if (!::PostThreadMessageW(pm->rgWaiterThreads[i].pWaiterContext->dwWaiterThreadId, MON_MESSAGE_STOP, msg.wParam, msg.lParam)) { - ExitWithLastError(hr, "Failed to send message to waiter thread to stop"); + MonExitWithLastError(hr, "Failed to send message to waiter thread to stop"); } MemRemoveFromArray(reinterpret_cast(pm->rgWaiterThreads), i, 1, pm->cWaiterThreads, sizeof(MON_WAITER_INFO), TRUE); --pm->cWaiterThreads; @@ -790,7 +805,7 @@ static DWORD WINAPI CoordinatorThread( uTimerFailedNetworkRetry = ::SetTimer(NULL, uTimerSuccessfulNetworkRetry + 1, MON_THREAD_NETWORK_FAIL_RETRY_IN_MS, NULL); if (0 == uTimerFailedNetworkRetry) { - ExitWithLastError(hr, "Failed to set timer for network fail retry"); + MonExitWithLastError(hr, "Failed to set timer for network fail retry"); } } ++dwFailingNetworkWaits; @@ -802,7 +817,7 @@ static DWORD WINAPI CoordinatorThread( { if (!::KillTimer(NULL, uTimerFailedNetworkRetry)) { - ExitWithLastError(hr, "Failed to kill timer for network fail retry"); + MonExitWithLastError(hr, "Failed to kill timer for network fail retry"); } uTimerFailedNetworkRetry = 0; } @@ -810,7 +825,7 @@ static DWORD WINAPI CoordinatorThread( case MON_MESSAGE_NETWORK_STATUS_UPDATE: hr = WaitForNetworkChanges(&hMonitor, pm); - ExitOnFailure(hr, "Failed to re-wait for network changes"); + MonExitOnFailure(hr, "Failed to re-wait for network changes"); // Propagate any network status update messages to all waiter threads for (DWORD i = 0; i < pm->cWaiterThreads; ++i) @@ -819,12 +834,12 @@ static DWORD WINAPI CoordinatorThread( if (!::PostThreadMessageW(pWaiterContext->dwWaiterThreadId, MON_MESSAGE_NETWORK_STATUS_UPDATE, 0, 0)) { - ExitWithLastError(hr, "Failed to send message to waiter thread to notify of network status update"); + MonExitWithLastError(hr, "Failed to send message to waiter thread to notify of network status update"); } if (!::SetEvent(pWaiterContext->rgHandles[0])) { - ExitWithLastError(hr, "Failed to set event to notify waiter thread of incoming network status update message"); + MonExitWithLastError(hr, "Failed to set event to notify waiter thread of incoming network status update message"); } } break; @@ -837,12 +852,12 @@ static DWORD WINAPI CoordinatorThread( if (!::PostThreadMessageW(pWaiterContext->dwWaiterThreadId, msg.wParam == uTimerFailedNetworkRetry ? MON_MESSAGE_NETWORK_RETRY_FAILED_NETWORK_WAITS : MON_MESSAGE_NETWORK_RETRY_SUCCESSFUL_NETWORK_WAITS, 0, 0)) { - ExitWithLastError(hr, "Failed to send message to waiter thread to notify of network status update"); + MonExitWithLastError(hr, "Failed to send message to waiter thread to notify of network status update"); } if (!::SetEvent(pWaiterContext->rgHandles[0])) { - ExitWithLastError(hr, "Failed to set event to notify waiter thread of incoming network status update message"); + MonExitWithLastError(hr, "Failed to set event to notify waiter thread of incoming network status update message"); } } break; @@ -861,12 +876,12 @@ static DWORD WINAPI CoordinatorThread( if (!::PostThreadMessageW(pWaiterContext->dwWaiterThreadId, MON_MESSAGE_DRIVE_STATUS_UPDATE, msg.wParam, msg.lParam)) { - ExitWithLastError(hr, "Failed to send message to waiter thread to notify of drive status update"); + MonExitWithLastError(hr, "Failed to send message to waiter thread to notify of drive status update"); } if (!::SetEvent(pWaiterContext->rgHandles[0])) { - ExitWithLastError(hr, "Failed to set event to notify waiter thread of incoming drive status update message"); + MonExitWithLastError(hr, "Failed to set event to notify waiter thread of incoming drive status update message"); } } break; @@ -998,7 +1013,7 @@ static HRESULT InitiateWait( { continue; } - ExitOnWin32Error(er, hr, "Failed to wait on path %ls", pRequest->rgsczPathHierarchy[dwIndex]); + MonExitOnWin32Error(er, hr, "Failed to wait on path %ls", pRequest->rgsczPathHierarchy[dwIndex]); } else { @@ -1013,7 +1028,7 @@ static HRESULT InitiateWait( { continue; } - ExitOnFailure(hr, "Failed to open regkey %ls", pRequest->rgsczPathHierarchy[dwIndex]); + MonExitOnFailure(hr, "Failed to open regkey %ls", pRequest->rgsczPathHierarchy[dwIndex]); er = ::RegNotifyChangeKeyValue(pRequest->regkey.hkSubKey, GetRecursiveFlag(pRequest, dwIndex), REG_NOTIFY_CHANGE_NAME | REG_NOTIFY_CHANGE_LAST_SET | REG_NOTIFY_CHANGE_SECURITY, *pHandle, TRUE); ReleaseRegKey(hk); @@ -1024,7 +1039,7 @@ static HRESULT InitiateWait( } else { - ExitOnWin32Error(er, hr, "Failed to wait on subkey %ls", pRequest->rgsczPathHierarchy[dwIndex]); + MonExitOnWin32Error(er, hr, "Failed to wait on subkey %ls", pRequest->rgsczPathHierarchy[dwIndex]); fHandleFound = TRUE; } @@ -1062,7 +1077,7 @@ static HRESULT InitiateWait( } } while (fRedo); - ExitOnFailure(hr, "Didn't get a successful wait after looping through all available options %ls", pRequest->rgsczPathHierarchy[pRequest->cPathHierarchy - 1]); + MonExitOnFailure(hr, "Didn't get a successful wait after looping through all available options %ls", pRequest->rgsczPathHierarchy[pRequest->cPathHierarchy - 1]); if (MON_DIRECTORY == pRequest->type) { @@ -1141,7 +1156,7 @@ static DWORD WINAPI WaiterThread( } hr = MemInsertIntoArray(reinterpret_cast(&pWaiterContext->rgHandles), dwNewRequestIndex + 1, 1, pWaiterContext->cHandles, sizeof(HANDLE), MON_ARRAY_GROWTH); - ExitOnFailure(hr, "Failed to insert additional handle"); + MonExitOnFailure(hr, "Failed to insert additional handle"); ++pWaiterContext->cHandles; // Ugh - directory types start with INVALID_HANDLE_VALUE instead of NULL @@ -1151,7 +1166,7 @@ static DWORD WINAPI WaiterThread( } hr = MemInsertIntoArray(reinterpret_cast(&pWaiterContext->rgRequests), dwNewRequestIndex, 1, pWaiterContext->cRequests, sizeof(MON_REQUEST), MON_ARRAY_GROWTH); - ExitOnFailure(hr, "Failed to insert additional request struct"); + MonExitOnFailure(hr, "Failed to insert additional request struct"); ++pWaiterContext->cRequests; pWaiterContext->rgRequests[dwNewRequestIndex] = pAddMessage->request; @@ -1172,10 +1187,10 @@ static DWORD WINAPI WaiterThread( } else { - ExitOnFailure(hr, "Failed to find request index for remove message"); + MonExitOnFailure(hr, "Failed to find request index for remove message"); hr = RemoveRequest(pWaiterContext, dwRequestIndex); - ExitOnFailure(hr, "Failed to remove request after request from coordinator thread."); + MonExitOnFailure(hr, "Failed to remove request after request from coordinator thread."); } MonRemoveMessageDestroy(pRemoveMessage); @@ -1204,7 +1219,7 @@ static DWORD WINAPI WaiterThread( hrTemp = InitiateWait(pWaiterContext->rgRequests + i, pWaiterContext->rgHandles + i + 1); hr = UpdateWaitStatus(hrTemp, pWaiterContext, i, &dwNewRequestIndex); - ExitOnFailure(hr, "Failed to update wait status"); + MonExitOnFailure(hr, "Failed to update wait status"); hrTemp = S_OK; if (dwNewRequestIndex != i) @@ -1239,7 +1254,7 @@ static DWORD WINAPI WaiterThread( hrTemp = InitiateWait(pWaiterContext->rgRequests + i, pWaiterContext->rgHandles + i + 1); hr = UpdateWaitStatus(hrTemp, pWaiterContext, i, &dwNewRequestIndex); - ExitOnFailure(hr, "Failed to update wait status"); + MonExitOnFailure(hr, "Failed to update wait status"); hrTemp = S_OK; if (dwNewRequestIndex != i) @@ -1274,7 +1289,7 @@ static DWORD WINAPI WaiterThread( hrTemp = InitiateWait(pWaiterContext->rgRequests + i, pWaiterContext->rgHandles + i + 1); hr = UpdateWaitStatus(hrTemp, pWaiterContext, i, &dwNewRequestIndex); - ExitOnFailure(hr, "Failed to update wait status"); + MonExitOnFailure(hr, "Failed to update wait status"); hrTemp = S_OK; if (dwNewRequestIndex != i) @@ -1311,7 +1326,7 @@ static DWORD WINAPI WaiterThread( } hr = UpdateWaitStatus(hrTemp, pWaiterContext, i, &dwNewRequestIndex); - ExitOnFailure(hr, "Failed to update wait status"); + MonExitOnFailure(hr, "Failed to update wait status"); hrTemp = S_OK; if (dwNewRequestIndex != i) @@ -1354,7 +1369,7 @@ static DWORD WINAPI WaiterThread( hrTemp = E_PATHNOTFOUND; hr = UpdateWaitStatus(hrTemp, pWaiterContext, i, &dwNewRequestIndex); - ExitOnFailure(hr, "Failed to update wait status"); + MonExitOnFailure(hr, "Failed to update wait status"); hrTemp = S_OK; break; } @@ -1385,7 +1400,7 @@ static DWORD WINAPI WaiterThread( // Initiate re-waits before we notify callback, to ensure we don't miss a single update hrTemp = InitiateWait(pWaiterContext->rgRequests + dwRequestIndex, pWaiterContext->rgHandles + dwRequestIndex + 1); hr = UpdateWaitStatus(hrTemp, pWaiterContext, dwRequestIndex, &dwRequestIndex); - ExitOnFailure(hr, "Failed to update wait status"); + MonExitOnFailure(hr, "Failed to update wait status"); hrTemp = S_OK; // If there were no errors and we were already waiting on the right target, or if we weren't yet but are able to now, it's a successful notify @@ -1413,7 +1428,7 @@ static DWORD WINAPI WaiterThread( } else if (WAIT_TIMEOUT != dwRet) { - ExitWithLastError(hr, "Failed to wait for multiple objects with return code %u", dwRet); + MonExitWithLastError(hr, "Failed to wait for multiple objects with return code %u", dwRet); } // OK, now that we've checked all triggered handles (resetting silence period timers appropriately), check for any pending notifications that we can finally fire @@ -1432,7 +1447,7 @@ static DWORD WINAPI WaiterThread( { Assert(FALSE); hr = HRESULT_FROM_WIN32(ERROR_EA_LIST_INCONSISTENT); - ExitOnFailure(hr, "Phantom pending fires were found!"); + MonExitOnFailure(hr, "Phantom pending fires were found!"); } --cRequestsPendingBeforeLoop; @@ -1470,13 +1485,13 @@ static DWORD WINAPI WaiterThread( { Assert(FALSE); hr = HRESULT_FROM_WIN32(PEERDIST_ERROR_MISSING_DATA); - ExitOnFailure(hr, "Missing %u pending fires! Total pending fires: %u, wait: %u", cRequestsPendingBeforeLoop, pWaiterContext->cRequestsPending, dwWait); + MonExitOnFailure(hr, "Missing %u pending fires! Total pending fires: %u, wait: %u", cRequestsPendingBeforeLoop, pWaiterContext->cRequestsPending, dwWait); } if (0 < pWaiterContext->cRequestsPending && DWORD_MAX == dwWait) { Assert(FALSE); hr = HRESULT_FROM_WIN32(ERROR_CANT_WAIT); - ExitOnFailure(hr, "Pending fires exist, but wait was infinite", cRequestsPendingBeforeLoop); + MonExitOnFailure(hr, "Pending fires exist (%u), but wait was infinite", cRequestsPendingBeforeLoop); } } } while (fContinue); @@ -1651,7 +1666,7 @@ static HRESULT RemoveRequest( // Notify coordinator thread that a wait was removed if (!::PostThreadMessageW(pWaiterContext->dwCoordinatorThreadId, MON_MESSAGE_REMOVED, static_cast(::GetCurrentThreadId()), 0)) { - ExitWithLastError(hr, "Failed to send message to coordinator thread to confirm directory was removed."); + MonExitWithLastError(hr, "Failed to send message to coordinator thread to confirm directory was removed."); } LExit: @@ -1684,7 +1699,7 @@ static HRESULT DuplicateRemoveMessage( HRESULT hr = S_OK; *ppMessage = reinterpret_cast(MemAlloc(sizeof(MON_REMOVE_MESSAGE), TRUE)); - ExitOnNull(*ppMessage, hr, E_OUTOFMEMORY, "Failed to allocate copy of remove message"); + MonExitOnNull(*ppMessage, hr, E_OUTOFMEMORY, "Failed to allocate copy of remove message"); (*ppMessage)->type = pMessage->type; (*ppMessage)->fRecursive = pMessage->fRecursive; @@ -1693,13 +1708,13 @@ static HRESULT DuplicateRemoveMessage( { case MON_DIRECTORY: hr = StrAllocString(&(*ppMessage)->directory.sczDirectory, pMessage->directory.sczDirectory, 0); - ExitOnFailure(hr, "Failed to copy directory"); + MonExitOnFailure(hr, "Failed to copy directory"); break; case MON_REGKEY: (*ppMessage)->regkey.hkRoot = pMessage->regkey.hkRoot; (*ppMessage)->regkey.kbKeyBitness = pMessage->regkey.kbKeyBitness; hr = StrAllocString(&(*ppMessage)->regkey.sczSubKey, pMessage->regkey.sczSubKey, 0); - ExitOnFailure(hr, "Failed to copy subkey"); + MonExitOnFailure(hr, "Failed to copy subkey"); break; default: Assert(false); @@ -1764,7 +1779,7 @@ static LRESULT CALLBACK MonWndProc( // This drive had a status update, so send it out to all threads if (!::PostThreadMessageW(::GetCurrentThreadId(), MON_MESSAGE_DRIVE_STATUS_UPDATE, static_cast(chDrive), static_cast(fArrival))) { - ExitWithLastError(hr, "Failed to send drive status update with drive %wc and arrival %ls", chDrive, fArrival ? L"TRUE" : L"FALSE"); + MonExitWithLastError(hr, "Failed to send drive status update with drive %wc and arrival %ls", chDrive, fArrival ? L"TRUE" : L"FALSE"); } } dwUnitMask >>= 1; @@ -1773,7 +1788,7 @@ static LRESULT CALLBACK MonWndProc( if (chDrive == 'z') { hr = E_UNEXPECTED; - ExitOnFailure(hr, "UnitMask showed drives beyond z:. Remaining UnitMask at this point: %u", dwUnitMask); + MonExitOnFailure(hr, "UnitMask showed drives beyond z:. Remaining UnitMask at this point: %u", dwUnitMask); } } } @@ -1785,7 +1800,7 @@ static LRESULT CALLBACK MonWndProc( if (!pm) { hr = E_POINTER; - ExitOnFailure(hr, "DBT_DEVICEQUERYREMOVE message received with no MON_STRUCT pointer, so message was ignored"); + MonExitOnFailure(hr, "DBT_DEVICEQUERYREMOVE message received with no MON_STRUCT pointer, so message was ignored"); } fReturnTrue = TRUE; @@ -1796,7 +1811,7 @@ static LRESULT CALLBACK MonWndProc( // We must wait for the actual wait handle to be released by waiter thread before telling windows to proceed with device removal, otherwise it could fail // due to handles still being open, so use a MON_INTERNAL_TEMPORARY_WAIT struct to send and receive a reply from a waiter thread pm->internalWait.hWait = ::CreateEventW(NULL, TRUE, FALSE, NULL); - ExitOnNullWithLastError(pm->internalWait.hWait, hr, "Failed to create anonymous event for waiter to notify wndproc device can be removed"); + MonExitOnNullWithLastError(pm->internalWait.hWait, hr, "Failed to create anonymous event for waiter to notify wndproc device can be removed"); pHandle = reinterpret_cast(lParam); pm->internalWait.pvContext = pHandle->dbch_handle; @@ -1808,12 +1823,12 @@ static LRESULT CALLBACK MonWndProc( if (!::PostThreadMessageW(pWaiterContext->dwWaiterThreadId, MON_MESSAGE_DRIVE_QUERY_REMOVE, reinterpret_cast(&pm->internalWait), static_cast(pm->internalWait.dwSendIteration))) { - ExitWithLastError(hr, "Failed to send message to waiter thread to notify of drive query remove"); + MonExitWithLastError(hr, "Failed to send message to waiter thread to notify of drive query remove"); } if (!::SetEvent(pWaiterContext->rgHandles[0])) { - ExitWithLastError(hr, "Failed to set event to notify waiter thread of incoming drive query remove message"); + MonExitWithLastError(hr, "Failed to set event to notify waiter thread of incoming drive query remove message"); } } @@ -1833,7 +1848,7 @@ static LRESULT CALLBACK MonWndProc( } else { - ExitWithLastError(hr, "WaitForSingleObject failed with non-timeout reason while waiting for response from waiter thread"); + MonExitWithLastError(hr, "WaitForSingleObject failed with non-timeout reason while waiting for response from waiter thread"); } ++pm->internalWait.dwSendIteration; } @@ -1871,12 +1886,12 @@ static HRESULT CreateMonWindow( { if (ERROR_CLASS_ALREADY_EXISTS != ::GetLastError()) { - ExitWithLastError(hr, "Failed to register MonUtil window class."); + MonExitWithLastError(hr, "Failed to register MonUtil window class."); } } *pHwnd = ::CreateWindowExW(0, wc.lpszClassName, L"", 0, CW_USEDEFAULT, CW_USEDEFAULT, 0, 0, HWND_DESKTOP, NULL, wc.hInstance, pm); - ExitOnNullWithLastError(*pHwnd, hr, "Failed to create window."); + MonExitOnNullWithLastError(*pHwnd, hr, "Failed to create window."); // Rumor has it that drive arrival / removal events can be lost in the rare event that some other application higher up in z-order is hanging if we don't make our window topmost // SWP_NOACTIVATE is important so the currently active window doesn't lose focus @@ -1909,7 +1924,7 @@ static HRESULT WaitForNetworkChanges( if (::WSALookupServiceBegin(&qsRestrictions, LUP_RETURN_ALL, phMonitor)) { hr = HRESULT_FROM_WIN32(::WSAGetLastError()); - ExitOnFailure(hr, "WSALookupServiceBegin() failed"); + MonExitOnFailure(hr, "WSALookupServiceBegin() failed"); } wsaCompletion.Type = NSP_NOTIFY_HWND; @@ -1923,7 +1938,7 @@ static HRESULT WaitForNetworkChanges( { hr = E_FAIL; } - ExitOnFailure(hr, "WSANSPIoctl() failed with return code %i, wsa last error %u", nResult, ::WSAGetLastError()); + MonExitOnFailure(hr, "WSANSPIoctl() failed with return code %i, wsa last error %u", nResult, ::WSAGetLastError()); } LExit: @@ -1960,7 +1975,7 @@ static HRESULT UpdateWaitStatus( // If it's a network wait, notify coordinator thread that a network wait is failing if (pRequest->fNetwork && !::PostThreadMessageW(pWaiterContext->dwCoordinatorThreadId, MON_MESSAGE_NETWORK_WAIT_FAILED, 0, 0)) { - ExitWithLastError(hr, "Failed to send message to coordinator thread to notify a network wait started to fail"); + MonExitWithLastError(hr, "Failed to send message to coordinator thread to notify a network wait started to fail"); } // Move the failing wait to the end of the list of waits and increment cRequestsFailing so WaitForMultipleObjects isn't passed an invalid handle @@ -1981,7 +1996,7 @@ static HRESULT UpdateWaitStatus( // If it's a network wait, notify coordinator thread that a network wait is succeeding again if (pRequest->fNetwork && !::PostThreadMessageW(pWaiterContext->dwCoordinatorThreadId, MON_MESSAGE_NETWORK_WAIT_SUCCEEDED, 0, 0)) { - ExitWithLastError(hr, "Failed to send message to coordinator thread to notify a network wait is succeeding again"); + MonExitWithLastError(hr, "Failed to send message to coordinator thread to notify a network wait is succeeding again"); } --pWaiterContext->cRequestsFailing; diff --git a/src/dutil/osutil.cpp b/src/dutil/osutil.cpp index 8834cd30..880ec3ea 100644 --- a/src/dutil/osutil.cpp +++ b/src/dutil/osutil.cpp @@ -2,6 +2,21 @@ #include "precomp.h" + +// Exit macros +#define OsExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_OSUTIL, x, s, __VA_ARGS__) +#define OsExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_OSUTIL, x, s, __VA_ARGS__) +#define OsExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_OSUTIL, x, s, __VA_ARGS__) +#define OsExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_OSUTIL, x, s, __VA_ARGS__) +#define OsExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_OSUTIL, x, s, __VA_ARGS__) +#define OsExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_OSUTIL, x, s, __VA_ARGS__) +#define OsExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_OSUTIL, p, x, e, s, __VA_ARGS__) +#define OsExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_OSUTIL, p, x, s, __VA_ARGS__) +#define OsExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_OSUTIL, p, x, e, s, __VA_ARGS__) +#define OsExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_OSUTIL, p, x, s, __VA_ARGS__) +#define OsExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_OSUTIL, e, x, s, __VA_ARGS__) +#define OsExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_OSUTIL, g, x, s, __VA_ARGS__) + typedef NTSTATUS(NTAPI* PFN_RTL_GET_VERSION)(_Out_ PRTL_OSVERSIONINFOEXW lpVersionInformation); OS_VERSION vOsVersion = OS_VERSION_UNKNOWN; @@ -127,7 +142,7 @@ extern "C" HRESULT DAPI OsIsRunningPrivileged( if (!::OpenProcessToken(::GetCurrentProcess(), TOKEN_QUERY, &hToken)) { - ExitOnLastError(hr, "Failed to open process token."); + OsExitOnLastError(hr, "Failed to open process token."); } if (::GetTokenInformation(hToken, TokenElevationType, &elevationType, sizeof(TOKEN_ELEVATION_TYPE), &dwSize)) @@ -142,7 +157,7 @@ extern "C" HRESULT DAPI OsIsRunningPrivileged( { er = ERROR_SUCCESS; } - ExitOnWin32Error(er, hr, "Failed to get process token information."); + OsExitOnWin32Error(er, hr, "Failed to get process token information."); // Fallback to this check for some OS's (like XP) *pfPrivileged = ::AllocateAndInitializeSid(&NtAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &AdministratorsGroup); @@ -180,14 +195,14 @@ extern "C" HRESULT DAPI OsIsUacEnabled( { ExitFunction1(hr = S_OK); } - ExitOnFailure(hr, "Failed to open system policy key to detect UAC."); + OsExitOnFailure(hr, "Failed to open system policy key to detect UAC."); hr = RegReadNumber(hk, L"EnableLUA", &dwUacEnabled); if (E_FILENOTFOUND == hr) { ExitFunction1(hr = S_OK); } - ExitOnFailure(hr, "Failed to read registry value to detect UAC."); + OsExitOnFailure(hr, "Failed to read registry value to detect UAC."); *pfUacEnabled = (0 != dwUacEnabled); @@ -215,12 +230,12 @@ HRESULT DAPI OsRtlGetVersion( hr = LoadSystemLibrary(L"ntdll.dll", &hNtdll); if (E_MODNOTFOUND == hr) { - ExitOnRootFailure(hr = E_NOTIMPL, "Failed to load ntdll.dll"); + OsExitOnRootFailure(hr = E_NOTIMPL, "Failed to load ntdll.dll"); } - ExitOnFailure(hr, "Failed to load ntdll.dll."); + OsExitOnFailure(hr, "Failed to load ntdll.dll."); pfnRtlGetVersion = reinterpret_cast(::GetProcAddress(hNtdll, "RtlGetVersion")); - ExitOnNullWithLastError(pfnRtlGetVersion, hr, "Failed to locate RtlGetVersion."); + OsExitOnNullWithLastError(pfnRtlGetVersion, hr, "Failed to locate RtlGetVersion."); hr = static_cast(pfnRtlGetVersion(&vovix)); diff --git a/src/dutil/path2utl.cpp b/src/dutil/path2utl.cpp index 8f5f03a1..ff3a946d 100644 --- a/src/dutil/path2utl.cpp +++ b/src/dutil/path2utl.cpp @@ -3,6 +3,21 @@ #include "precomp.h" +// Exit macros +#define PathExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_PATHUTIL, x, s, __VA_ARGS__) +#define PathExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_PATHUTIL, x, s, __VA_ARGS__) +#define PathExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_PATHUTIL, x, s, __VA_ARGS__) +#define PathExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_PATHUTIL, x, s, __VA_ARGS__) +#define PathExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_PATHUTIL, x, s, __VA_ARGS__) +#define PathExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_PATHUTIL, x, s, __VA_ARGS__) +#define PathExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_PATHUTIL, p, x, e, s, __VA_ARGS__) +#define PathExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_PATHUTIL, p, x, s, __VA_ARGS__) +#define PathExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_PATHUTIL, p, x, e, s, __VA_ARGS__) +#define PathExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_PATHUTIL, p, x, s, __VA_ARGS__) +#define PathExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_PATHUTIL, e, x, s, __VA_ARGS__) +#define PathExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_PATHUTIL, g, x, s, __VA_ARGS__) + + DAPI_(HRESULT) PathCanonicalizePath( __in_z LPCWSTR wzPath, __deref_out_z LPWSTR* psczCanonicalized @@ -12,7 +27,7 @@ DAPI_(HRESULT) PathCanonicalizePath( int cch = MAX_PATH + 1; hr = StrAlloc(psczCanonicalized, cch); - ExitOnFailure(hr, "Failed to allocate string for the canonicalized path."); + PathExitOnFailure(hr, "Failed to allocate string for the canonicalized path."); if (::PathCanonicalizeW(*psczCanonicalized, wzPath)) { @@ -39,10 +54,10 @@ DAPI_(HRESULT) PathDirectoryContainsPath( LPWSTR sczOriginalDirectory = NULL; hr = PathCanonicalizePath(wzPath, &sczOriginalPath); - ExitOnFailure(hr, "Failed to canonicalize the path."); + PathExitOnFailure(hr, "Failed to canonicalize the path."); hr = PathCanonicalizePath(wzDirectory, &sczOriginalDirectory); - ExitOnFailure(hr, "Failed to canonicalize the directory."); + PathExitOnFailure(hr, "Failed to canonicalize the directory."); if (!sczOriginalPath || !*sczOriginalPath) { diff --git a/src/dutil/pathutil.cpp b/src/dutil/pathutil.cpp index d8894756..ec338f71 100644 --- a/src/dutil/pathutil.cpp +++ b/src/dutil/pathutil.cpp @@ -2,11 +2,26 @@ #include "precomp.h" + +// Exit macros +#define PathExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_PATHUTIL, x, s, __VA_ARGS__) +#define PathExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_PATHUTIL, x, s, __VA_ARGS__) +#define PathExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_PATHUTIL, x, s, __VA_ARGS__) +#define PathExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_PATHUTIL, x, s, __VA_ARGS__) +#define PathExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_PATHUTIL, x, s, __VA_ARGS__) +#define PathExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_PATHUTIL, x, s, __VA_ARGS__) +#define PathExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_PATHUTIL, p, x, e, s, __VA_ARGS__) +#define PathExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_PATHUTIL, p, x, s, __VA_ARGS__) +#define PathExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_PATHUTIL, p, x, e, s, __VA_ARGS__) +#define PathExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_PATHUTIL, p, x, s, __VA_ARGS__) +#define PathExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_PATHUTIL, e, x, s, __VA_ARGS__) +#define PathExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_PATHUTIL, g, x, s, __VA_ARGS__) + #define PATH_GOOD_ENOUGH 64 DAPI_(HRESULT) PathCommandLineAppend( - __deref_out_z LPWSTR* psczCommandLine, + __deref_inout_z LPWSTR* psczCommandLine, __in_z LPCWSTR wzArgument ) { @@ -41,7 +56,7 @@ DAPI_(HRESULT) PathCommandLineAppend( if (fRequiresQuoting) { hr = StrAlloc(&sczQuotedArg, dwMaxEscapedSize + 3); // plus three for the start and end quote plus null terminator. - ExitOnFailure(hr, "Failed to allocate argument to be quoted."); + PathExitOnFailure(hr, "Failed to allocate argument to be quoted."); LPCWSTR pwz = wzArgument; LPWSTR pwzQuoted = sczQuotedArg; @@ -94,11 +109,11 @@ DAPI_(HRESULT) PathCommandLineAppend( if (*psczCommandLine && **psczCommandLine) { hr = StrAllocConcat(psczCommandLine, L" ", 0); - ExitOnFailure(hr, "Failed to append space to command line with existing data."); + PathExitOnFailure(hr, "Failed to append space to command line with existing data."); } hr = StrAllocConcat(psczCommandLine, sczQuotedArg ? sczQuotedArg : wzArgument, 0); - ExitOnFailure(hr, "Failed to copy command line argument."); + PathExitOnFailure(hr, "Failed to copy command line argument."); LExit: ReleaseStr(sczQuotedArg); @@ -162,7 +177,7 @@ DAPI_(LPCWSTR) PathExtension( DAPI_(HRESULT) PathGetDirectory( __in_z LPCWSTR wzPath, - __out LPWSTR *psczDirectory + __out_z LPWSTR *psczDirectory ) { HRESULT hr = S_OK; @@ -193,7 +208,7 @@ DAPI_(HRESULT) PathGetDirectory( } hr = StrAllocString(psczDirectory, wzPath, cchDirectory); - ExitOnFailure(hr, "Failed to copy directory."); + PathExitOnFailure(hr, "Failed to copy directory."); LExit: return hr; @@ -223,28 +238,28 @@ DAPI_(HRESULT) PathExpand( cchExpandedPath = PATH_GOOD_ENOUGH; hr = StrAlloc(&sczExpandedPath, cchExpandedPath); - ExitOnFailure(hr, "Failed to allocate space for expanded path."); + PathExitOnFailure(hr, "Failed to allocate space for expanded path."); cch = ::ExpandEnvironmentStringsW(wzRelativePath, sczExpandedPath, cchExpandedPath); if (0 == cch) { - ExitWithLastError(hr, "Failed to expand environment variables in string: %ls", wzRelativePath); + PathExitWithLastError(hr, "Failed to expand environment variables in string: %ls", wzRelativePath); } else if (cchExpandedPath < cch) { cchExpandedPath = cch; hr = StrAlloc(&sczExpandedPath, cchExpandedPath); - ExitOnFailure(hr, "Failed to re-allocate more space for expanded path."); + PathExitOnFailure(hr, "Failed to re-allocate more space for expanded path."); cch = ::ExpandEnvironmentStringsW(wzRelativePath, sczExpandedPath, cchExpandedPath); if (0 == cch) { - ExitWithLastError(hr, "Failed to expand environment variables in string: %ls", wzRelativePath); + PathExitWithLastError(hr, "Failed to expand environment variables in string: %ls", wzRelativePath); } else if (cchExpandedPath < cch) { hr = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); - ExitOnRootFailure(hr, "Failed to allocate buffer for expanded path."); + PathExitOnRootFailure(hr, "Failed to allocate buffer for expanded path."); } } @@ -255,10 +270,10 @@ DAPI_(HRESULT) PathExpand( { hr = S_OK; } - ExitOnFailure(hr, "Failed to prefix long path after expanding environment variables."); + PathExitOnFailure(hr, "Failed to prefix long path after expanding environment variables."); hr = StrMaxLength(sczExpandedPath, reinterpret_cast(&cchExpandedPath)); - ExitOnFailure(hr, "Failed to get max length of expanded path."); + PathExitOnFailure(hr, "Failed to get max length of expanded path."); } } @@ -272,35 +287,35 @@ DAPI_(HRESULT) PathExpand( DWORD cchFullPath = PATH_GOOD_ENOUGH < cchExpandedPath ? cchExpandedPath : PATH_GOOD_ENOUGH; hr = StrAlloc(&sczFullPath, cchFullPath); - ExitOnFailure(hr, "Failed to allocate space for full path."); + PathExitOnFailure(hr, "Failed to allocate space for full path."); cch = ::GetFullPathNameW(wzPath, cchFullPath, sczFullPath, &wzFileName); if (0 == cch) { - ExitWithLastError(hr, "Failed to get full path for string: %ls", wzPath); + PathExitWithLastError(hr, "Failed to get full path for string: %ls", wzPath); } else if (cchFullPath < cch) { cchFullPath = cch < MAX_PATH ? cch : cch + 7; // ensure space for "\\?\UNC" prefix if needed hr = StrAlloc(&sczFullPath, cchFullPath); - ExitOnFailure(hr, "Failed to re-allocate more space for full path."); + PathExitOnFailure(hr, "Failed to re-allocate more space for full path."); cch = ::GetFullPathNameW(wzPath, cchFullPath, sczFullPath, &wzFileName); if (0 == cch) { - ExitWithLastError(hr, "Failed to get full path for string: %ls", wzPath); + PathExitWithLastError(hr, "Failed to get full path for string: %ls", wzPath); } else if (cchFullPath < cch) { hr = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); - ExitOnRootFailure(hr, "Failed to allocate buffer for full path."); + PathExitOnRootFailure(hr, "Failed to allocate buffer for full path."); } } if (MAX_PATH < cch) { hr = PathPrefix(&sczFullPath); - ExitOnFailure(hr, "Failed to prefix long path after expanding."); + PathExitOnFailure(hr, "Failed to prefix long path after expanding."); } } else @@ -310,7 +325,7 @@ DAPI_(HRESULT) PathExpand( } hr = StrAllocString(psczFullPath, sczFullPath? sczFullPath : wzRelativePath, 0); - ExitOnFailure(hr, "Failed to copy relative path into full path."); + PathExitOnFailure(hr, "Failed to copy relative path into full path."); LExit: ReleaseStr(sczFullPath); @@ -336,7 +351,7 @@ DAPI_(HRESULT) PathPrefix( L'\\' == wzFullPath[2]) // normal path { hr = StrAllocPrefix(psczFullPath, L"\\\\?\\", 4); - ExitOnFailure(hr, "Failed to add prefix to file path."); + PathExitOnFailure(hr, "Failed to add prefix to file path."); } else if (L'\\' == wzFullPath[0] && L'\\' == wzFullPath[1]) // UNC { @@ -344,18 +359,18 @@ DAPI_(HRESULT) PathPrefix( if (!(L'?' == wzFullPath[2] && L'\\' == wzFullPath[3])) { hr = StrSize(*psczFullPath, &cbFullPath); - ExitOnFailure(hr, "Failed to get size of full path."); + PathExitOnFailure(hr, "Failed to get size of full path."); memmove_s(wzFullPath, cbFullPath, wzFullPath + 1, cbFullPath - sizeof(WCHAR)); hr = StrAllocPrefix(psczFullPath, L"\\\\?\\UNC", 7); - ExitOnFailure(hr, "Failed to add prefix to UNC path."); + PathExitOnFailure(hr, "Failed to add prefix to UNC path."); } } else { hr = E_INVALIDARG; - ExitOnFailure(hr, "Invalid path provided to prefix: %ls.", wzFullPath); + PathExitOnFailure(hr, "Invalid path provided to prefix: %ls.", wzFullPath); } LExit: @@ -372,7 +387,7 @@ DAPI_(HRESULT) PathFixedBackslashTerminate( size_t cchLength = 0; hr = ::StringCchLengthW(wzPath, cchPath, &cchLength); - ExitOnFailure(hr, "Failed to get length of path."); + PathExitOnFailure(hr, "Failed to get length of path."); if (cchLength >= cchPath) { @@ -400,15 +415,15 @@ DAPI_(HRESULT) PathBackslashTerminate( size_t cchLength = 0; hr = StrMaxLength(*psczPath, &cchPath); - ExitOnFailure(hr, "Failed to get size of path string."); + PathExitOnFailure(hr, "Failed to get size of path string."); hr = ::StringCchLengthW(*psczPath, cchPath, &cchLength); - ExitOnFailure(hr, "Failed to get length of path."); + PathExitOnFailure(hr, "Failed to get length of path."); if (L'\\' != (*psczPath)[cchLength - 1]) { hr = StrAllocConcat(psczPath, L"\\", 1); - ExitOnFailure(hr, "Failed to concat backslash onto string."); + PathExitOnFailure(hr, "Failed to concat backslash onto string."); } LExit: @@ -427,12 +442,12 @@ DAPI_(HRESULT) PathForCurrentProcess( do { hr = StrAlloc(psczFullPath, cch); - ExitOnFailure(hr, "Failed to allocate string for module path."); + PathExitOnFailure(hr, "Failed to allocate string for module path."); DWORD cchRequired = ::GetModuleFileNameW(hModule, *psczFullPath, cch); if (0 == cchRequired) { - ExitWithLastError(hr, "Failed to get path for executing process."); + PathExitWithLastError(hr, "Failed to get path for executing process."); } else if (cchRequired == cch) { @@ -457,15 +472,15 @@ DAPI_(HRESULT) PathRelativeToModule( ) { HRESULT hr = PathForCurrentProcess(psczFullPath, hModule); - ExitOnFailure(hr, "Failed to get current module path."); + PathExitOnFailure(hr, "Failed to get current module path."); hr = PathGetDirectory(*psczFullPath, psczFullPath); - ExitOnFailure(hr, "Failed to get current module directory."); + PathExitOnFailure(hr, "Failed to get current module directory."); if (wzFileName) { hr = PathConcat(*psczFullPath, wzFileName, psczFullPath); - ExitOnFailure(hr, "Failed to append filename."); + PathExitOnFailure(hr, "Failed to append filename."); } LExit: @@ -496,16 +511,16 @@ DAPI_(HRESULT) PathCreateTempFile( if (wzDirectory && *wzDirectory) { hr = StrAllocString(&sczTempPath, wzDirectory, 0); - ExitOnFailure(hr, "Failed to copy temp path."); + PathExitOnFailure(hr, "Failed to copy temp path."); } else { hr = StrAlloc(&sczTempPath, cchTempPath); - ExitOnFailure(hr, "Failed to allocate memory for the temp path."); + PathExitOnFailure(hr, "Failed to allocate memory for the temp path."); if (!::GetTempPathW(cchTempPath, sczTempPath)) { - ExitWithLastError(hr, "Failed to get temp path."); + PathExitWithLastError(hr, "Failed to get temp path."); } } @@ -514,10 +529,10 @@ DAPI_(HRESULT) PathCreateTempFile( for (DWORD i = 1; i <= dwUniqueCount && INVALID_HANDLE_VALUE == hTempFile; ++i) { hr = StrAllocFormatted(&scz, wzFileNameTemplate, i); - ExitOnFailure(hr, "Failed to allocate memory for file template."); + PathExitOnFailure(hr, "Failed to allocate memory for file template."); hr = StrAllocFormatted(&sczTempFile, L"%s%s", sczTempPath, scz); - ExitOnFailure(hr, "Failed to allocate temp file name."); + PathExitOnFailure(hr, "Failed to allocate temp file name."); hTempFile = ::CreateFileW(sczTempFile, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_DELETE, NULL, CREATE_NEW, dwFileAttributes, NULL); if (INVALID_HANDLE_VALUE == hTempFile) @@ -528,7 +543,7 @@ DAPI_(HRESULT) PathCreateTempFile( { hr = S_OK; } - ExitOnFailure(hr, "Failed to create file: %ls", sczTempFile); + PathExitOnFailure(hr, "Failed to create file: %ls", sczTempFile); } } } @@ -538,17 +553,17 @@ DAPI_(HRESULT) PathCreateTempFile( if (INVALID_HANDLE_VALUE == hTempFile) { hr = StrAlloc(&sczTempFile, MAX_PATH); - ExitOnFailure(hr, "Failed to allocate memory for the temp path"); + PathExitOnFailure(hr, "Failed to allocate memory for the temp path"); if (!::GetTempFileNameW(sczTempPath, L"TMP", 0, sczTempFile)) { - ExitWithLastError(hr, "Failed to create new temp file name."); + PathExitWithLastError(hr, "Failed to create new temp file name."); } hTempFile = ::CreateFileW(sczTempFile, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, dwFileAttributes, NULL); if (INVALID_HANDLE_VALUE == hTempFile) { - ExitWithLastError(hr, "Failed to open new temp file: %ls", sczTempFile); + PathExitWithLastError(hr, "Failed to open new temp file: %ls", sczTempFile); } } @@ -556,7 +571,7 @@ DAPI_(HRESULT) PathCreateTempFile( if (psczTempFile) { hr = StrAllocString(psczTempFile, sczTempFile, 0); - ExitOnFailure(hr, "Failed to copy temp file string."); + PathExitOnFailure(hr, "Failed to copy temp file string."); } if (phTempFile) @@ -602,24 +617,24 @@ DAPI_(HRESULT) PathCreateTimeBasedTempFile( if (wzDirectory && *wzDirectory) { hr = PathConcat(wzDirectory, wzPrefix, &sczPrefix); - ExitOnFailure(hr, "Failed to combine directory and log prefix."); + PathExitOnFailure(hr, "Failed to combine directory and log prefix."); } else { if (!::GetTempPathW(countof(wzTempPath), wzTempPath)) { - ExitWithLastError(hr, "Failed to get temp folder."); + PathExitWithLastError(hr, "Failed to get temp folder."); } hr = PathConcat(wzTempPath, wzPrefix, &sczPrefix); - ExitOnFailure(hr, "Failed to concatenate the temp folder and log prefix."); + PathExitOnFailure(hr, "Failed to concatenate the temp folder and log prefix."); } hr = PathGetDirectory(sczPrefix, &sczPrefixFolder); if (S_OK == hr) { hr = DirEnsureExists(sczPrefixFolder, NULL); - ExitOnFailure(hr, "Failed to ensure temp file path exists: %ls", sczPrefixFolder); + PathExitOnFailure(hr, "Failed to ensure temp file path exists: %ls", sczPrefixFolder); } if (!wzPostfix) @@ -636,7 +651,7 @@ DAPI_(HRESULT) PathCreateTimeBasedTempFile( // Log format: pre YYYY MM dd hh mm ss post ext hr = StrAllocFormatted(&sczTempPath, L"%ls_%04u%02u%02u%02u%02u%02u%ls%ls%ls", sczPrefix, time.wYear, time.wMonth, time.wDay, time.wHour, time.wMinute, time.wSecond, wzPostfix, L'.' == *wzExtension ? L"" : L".", wzExtension); - ExitOnFailure(hr, "failed to allocate memory for the temp path"); + PathExitOnFailure(hr, "failed to allocate memory for the temp path"); hTempFile = ::CreateFileW(sczTempPath, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL); if (INVALID_HANDLE_VALUE == hTempFile) @@ -655,14 +670,14 @@ DAPI_(HRESULT) PathCreateTimeBasedTempFile( } hr = HRESULT_FROM_WIN32(er); - ExitOnFailureDebugTrace(hr, "Failed to create temp file: %ls", sczTempPath); + PathExitOnFailureDebugTrace(hr, "Failed to create temp file: %ls", sczTempPath); } } while (fRetry); if (psczTempFile) { hr = StrAllocString(psczTempFile, sczTempPath, 0); - ExitOnFailure(hr, "Failed to copy temp path to return."); + PathExitOnFailure(hr, "Failed to copy temp path to return."); } if (phTempFile) @@ -701,29 +716,29 @@ DAPI_(HRESULT) PathCreateTempDirectory( if (wzDirectory && *wzDirectory) { hr = StrAllocString(&sczTempPath, wzDirectory, 0); - ExitOnFailure(hr, "Failed to copy temp path."); + PathExitOnFailure(hr, "Failed to copy temp path."); hr = PathBackslashTerminate(&sczTempPath); - ExitOnFailure(hr, "Failed to ensure path ends in backslash: %ls", wzDirectory); + PathExitOnFailure(hr, "Failed to ensure path ends in backslash: %ls", wzDirectory); } else { hr = StrAlloc(&sczTempPath, cchTempPath); - ExitOnFailure(hr, "Failed to allocate memory for the temp path."); + PathExitOnFailure(hr, "Failed to allocate memory for the temp path."); if (!::GetTempPathW(cchTempPath, sczTempPath)) { - ExitWithLastError(hr, "Failed to get temp path."); + PathExitWithLastError(hr, "Failed to get temp path."); } } for (DWORD i = 1; i <= dwUniqueCount; ++i) { hr = StrAllocFormatted(&scz, wzDirectoryNameTemplate, i); - ExitOnFailure(hr, "Failed to allocate memory for directory name template."); + PathExitOnFailure(hr, "Failed to allocate memory for directory name template."); hr = StrAllocFormatted(psczTempDirectory, L"%s%s", sczTempPath, scz); - ExitOnFailure(hr, "Failed to allocate temp directory name."); + PathExitOnFailure(hr, "Failed to allocate temp directory name."); if (!::CreateDirectoryW(*psczTempDirectory, NULL)) { @@ -750,10 +765,10 @@ DAPI_(HRESULT) PathCreateTempDirectory( break; } } - ExitOnFailure(hr, "Failed to create temp directory."); + PathExitOnFailure(hr, "Failed to create temp directory."); hr = PathBackslashTerminate(psczTempDirectory); - ExitOnFailure(hr, "Failed to ensure temp directory is backslash terminated."); + PathExitOnFailure(hr, "Failed to ensure temp directory is backslash terminated."); LExit: ReleaseStr(scz); @@ -771,13 +786,13 @@ DAPI_(HRESULT) PathGetKnownFolder( HRESULT hr = S_OK; hr = StrAlloc(psczKnownFolder, MAX_PATH); - ExitOnFailure(hr, "Failed to allocate memory for known folder."); + PathExitOnFailure(hr, "Failed to allocate memory for known folder."); hr = ::SHGetFolderPathW(NULL, csidl, NULL, SHGFP_TYPE_CURRENT, *psczKnownFolder); - ExitOnFailure(hr, "Failed to get known folder path."); + PathExitOnFailure(hr, "Failed to get known folder path."); hr = PathBackslashTerminate(psczKnownFolder); - ExitOnFailure(hr, "Failed to ensure known folder path is backslash terminated."); + PathExitOnFailure(hr, "Failed to ensure known folder path is backslash terminated."); LExit: return hr; @@ -804,23 +819,23 @@ DAPI_(HRESULT) PathConcat( if (!wzPath2 || !*wzPath2) { hr = StrAllocString(psczCombined, wzPath1, 0); - ExitOnFailure(hr, "Failed to copy just path1 to output."); + PathExitOnFailure(hr, "Failed to copy just path1 to output."); } else if (!wzPath1 || !*wzPath1 || PathIsAbsolute(wzPath2)) { hr = StrAllocString(psczCombined, wzPath2, 0); - ExitOnFailure(hr, "Failed to copy just path2 to output."); + PathExitOnFailure(hr, "Failed to copy just path2 to output."); } else { hr = StrAllocString(psczCombined, wzPath1, 0); - ExitOnFailure(hr, "Failed to copy path1 to output."); + PathExitOnFailure(hr, "Failed to copy path1 to output."); hr = PathBackslashTerminate(psczCombined); - ExitOnFailure(hr, "Failed to backslashify."); + PathExitOnFailure(hr, "Failed to backslashify."); hr = StrAllocConcat(psczCombined, wzPath2, 0); - ExitOnFailure(hr, "Failed to append path2 to output."); + PathExitOnFailure(hr, "Failed to append path2 to output."); } LExit: @@ -839,13 +854,13 @@ DAPI_(HRESULT) PathEnsureQuoted( size_t cchPath = 0; hr = ::StringCchLengthW(*ppszPath, STRSAFE_MAX_CCH, &cchPath); - ExitOnFailure(hr, "Failed to get the length of the path."); + PathExitOnFailure(hr, "Failed to get the length of the path."); // Handle simple special cases. if (0 == cchPath || (1 == cchPath && L'"' == (*ppszPath)[0])) { hr = StrAllocString(ppszPath, L"\"\"", 2); - ExitOnFailure(hr, "Failed to allocate a quoted empty string."); + PathExitOnFailure(hr, "Failed to allocate a quoted empty string."); ExitFunction(); } @@ -853,7 +868,7 @@ DAPI_(HRESULT) PathEnsureQuoted( if (L'"' != (*ppszPath)[0]) { hr = StrAllocPrefix(ppszPath, L"\"", 1); - ExitOnFailure(hr, "Failed to allocate an opening quote."); + PathExitOnFailure(hr, "Failed to allocate an opening quote."); // Add a char for the opening quote. ++cchPath; @@ -862,7 +877,7 @@ DAPI_(HRESULT) PathEnsureQuoted( if (L'"' != (*ppszPath)[cchPath - 1]) { hr = StrAllocConcat(ppszPath, L"\"", 1); - ExitOnFailure(hr, "Failed to allocate a closing quote."); + PathExitOnFailure(hr, "Failed to allocate a closing quote."); // Add a char for the closing quote. ++cchPath; @@ -876,7 +891,7 @@ DAPI_(HRESULT) PathEnsureQuoted( (*ppszPath)[cchPath - 1] = L'\\'; hr = StrAllocConcat(ppszPath, L"\"", 1); - ExitOnFailure(hr, "Failed to allocate another closing quote after the backslash."); + PathExitOnFailure(hr, "Failed to allocate another closing quote after the backslash."); } } @@ -897,10 +912,10 @@ DAPI_(HRESULT) PathCompare( LPWSTR sczPath2 = NULL; hr = PathExpand(&sczPath1, wzPath1, PATH_EXPAND_ENVIRONMENT | PATH_EXPAND_FULLPATH); - ExitOnFailure(hr, "Failed to expand path1."); + PathExitOnFailure(hr, "Failed to expand path1."); hr = PathExpand(&sczPath2, wzPath2, PATH_EXPAND_ENVIRONMENT | PATH_EXPAND_FULLPATH); - ExitOnFailure(hr, "Failed to expand path2."); + PathExitOnFailure(hr, "Failed to expand path2."); *pnResult = ::CompareStringW(LOCALE_NEUTRAL, NORM_IGNORECASE, sczPath1, -1, sczPath2, -1); @@ -922,7 +937,7 @@ DAPI_(HRESULT) PathCompress( hPath = ::CreateFileW(wzPath, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); if (INVALID_HANDLE_VALUE == hPath) { - ExitWithLastError(hr, "Failed to open path %ls for compression.", wzPath); + PathExitWithLastError(hr, "Failed to open path %ls for compression.", wzPath); } DWORD dwBytesReturned = 0; @@ -933,7 +948,7 @@ DAPI_(HRESULT) PathCompress( DWORD er = ::GetLastError(); if (ERROR_INVALID_FUNCTION != er) { - ExitOnWin32Error(er, hr, "Failed to set compression state for path %ls.", wzPath); + PathExitOnWin32Error(er, hr, "Failed to set compression state for path %ls.", wzPath); } } @@ -945,7 +960,7 @@ LExit: DAPI_(HRESULT) PathGetHierarchyArray( __in_z LPCWSTR wzPath, - __deref_inout_ecount_opt(*pcStrArray) LPWSTR **prgsczPathArray, + __deref_inout_ecount_opt(*pcPathArray) LPWSTR **prgsczPathArray, __inout LPUINT pcPathArray ) { @@ -975,16 +990,16 @@ DAPI_(HRESULT) PathGetHierarchyArray( Assert(cArraySpacesNeeded >= 1); hr = MemEnsureArraySize(reinterpret_cast(prgsczPathArray), cArraySpacesNeeded, sizeof(LPWSTR), 0); - ExitOnFailure(hr, "Failed to allocate array of size %u for parent directories", cArraySpacesNeeded); + PathExitOnFailure(hr, "Failed to allocate array of size %u for parent directories", cArraySpacesNeeded); *pcPathArray = cArraySpacesNeeded; hr = StrAllocString(&sczPathCopy, wzPath, 0); - ExitOnFailure(hr, "Failed to allocate copy of original path"); + PathExitOnFailure(hr, "Failed to allocate copy of original path"); for (DWORD i = 0; i < cArraySpacesNeeded; ++i) { hr = StrAllocString((*prgsczPathArray) + cArraySpacesNeeded - 1 - i, sczPathCopy, 0); - ExitOnFailure(hr, "Failed to copy path"); + PathExitOnFailure(hr, "Failed to copy path"); // If it ends in a backslash, it's a directory path, so cut off everything the last backslash before we get the directory portion of the path if (wzPath[lstrlenW(sczPathCopy) - 1] == L'\\') @@ -993,7 +1008,7 @@ DAPI_(HRESULT) PathGetHierarchyArray( } hr = PathGetDirectory(sczPathCopy, &sczNewPathCopy); - ExitOnFailure(hr, "Failed to get directory portion of path"); + PathExitOnFailure(hr, "Failed to get directory portion of path"); ReleaseStr(sczPathCopy); sczPathCopy = sczNewPathCopy; diff --git a/src/dutil/perfutil.cpp b/src/dutil/perfutil.cpp index 5c4e0774..bc138d34 100644 --- a/src/dutil/perfutil.cpp +++ b/src/dutil/perfutil.cpp @@ -2,6 +2,21 @@ #include "precomp.h" + +// Exit macros +#define PerfExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_PERFUTIL, x, s, __VA_ARGS__) +#define PerfExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_PERFUTIL, x, s, __VA_ARGS__) +#define PerfExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_PERFUTIL, x, s, __VA_ARGS__) +#define PerfExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_PERFUTIL, x, s, __VA_ARGS__) +#define PerfExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_PERFUTIL, x, s, __VA_ARGS__) +#define PerfExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_PERFUTIL, x, s, __VA_ARGS__) +#define PerfExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_PERFUTIL, p, x, e, s, __VA_ARGS__) +#define PerfExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_PERFUTIL, p, x, s, __VA_ARGS__) +#define PerfExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_PERFUTIL, p, x, e, s, __VA_ARGS__) +#define PerfExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_PERFUTIL, p, x, s, __VA_ARGS__) +#define PerfExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_PERFUTIL, e, x, s, __VA_ARGS__) +#define PerfExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_PERFUTIL, g, x, s, __VA_ARGS__) + static BOOL vfHighPerformanceCounter = TRUE; // assume the system has a high performance counter static double vdFrequency = 1; diff --git a/src/dutil/polcutil.cpp b/src/dutil/polcutil.cpp index 1cc29e61..1fdfa18c 100644 --- a/src/dutil/polcutil.cpp +++ b/src/dutil/polcutil.cpp @@ -2,6 +2,21 @@ #include "precomp.h" + +// Exit macros +#define PolcExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_POLCUTIL, x, s, __VA_ARGS__) +#define PolcExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_POLCUTIL, x, s, __VA_ARGS__) +#define PolcExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_POLCUTIL, x, s, __VA_ARGS__) +#define PolcExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_POLCUTIL, x, s, __VA_ARGS__) +#define PolcExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_POLCUTIL, x, s, __VA_ARGS__) +#define PolcExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_POLCUTIL, x, s, __VA_ARGS__) +#define PolcExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_POLCUTIL, p, x, e, s, __VA_ARGS__) +#define PolcExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_POLCUTIL, p, x, s, __VA_ARGS__) +#define PolcExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_POLCUTIL, p, x, e, s, __VA_ARGS__) +#define PolcExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_POLCUTIL, p, x, s, __VA_ARGS__) +#define PolcExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_POLCUTIL, e, x, s, __VA_ARGS__) +#define PolcExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_POLCUTIL, g, x, s, __VA_ARGS__) + const LPCWSTR REGISTRY_POLICIES_KEY = L"SOFTWARE\\Policies\\"; static HRESULT OpenPolicyKey( @@ -25,14 +40,14 @@ extern "C" HRESULT DAPI PolcReadNumber( { ExitFunction1(hr = S_FALSE); } - ExitOnFailure(hr, "Failed to open policy key: %ls", wzPolicyPath); + PolcExitOnFailure(hr, "Failed to open policy key: %ls", wzPolicyPath); hr = RegReadNumber(hk, wzPolicyName, pdw); if (E_FILENOTFOUND == hr || E_PATHNOTFOUND == hr) { ExitFunction1(hr = S_FALSE); } - ExitOnFailure(hr, "Failed to open policy key: %ls, name: %ls", wzPolicyPath, wzPolicyName); + PolcExitOnFailure(hr, "Failed to open policy key: %ls, name: %ls", wzPolicyPath, wzPolicyName); LExit: ReleaseRegKey(hk); @@ -60,14 +75,14 @@ extern "C" HRESULT DAPI PolcReadString( { ExitFunction1(hr = S_FALSE); } - ExitOnFailure(hr, "Failed to open policy key: %ls", wzPolicyPath); + PolcExitOnFailure(hr, "Failed to open policy key: %ls", wzPolicyPath); hr = RegReadString(hk, wzPolicyName, pscz); if (E_FILENOTFOUND == hr || E_PATHNOTFOUND == hr) { ExitFunction1(hr = S_FALSE); } - ExitOnFailure(hr, "Failed to open policy key: %ls, name: %ls", wzPolicyPath, wzPolicyName); + PolcExitOnFailure(hr, "Failed to open policy key: %ls, name: %ls", wzPolicyPath, wzPolicyName); LExit: ReleaseRegKey(hk); @@ -99,10 +114,10 @@ static HRESULT OpenPolicyKey( LPWSTR sczPath = NULL; hr = PathConcat(REGISTRY_POLICIES_KEY, wzPolicyPath, &sczPath); - ExitOnFailure(hr, "Failed to combine logging path with root path."); + PolcExitOnFailure(hr, "Failed to combine logging path with root path."); hr = RegOpen(HKEY_LOCAL_MACHINE, sczPath, KEY_READ, phk); - ExitOnFailure(hr, "Failed to open policy registry key."); + PolcExitOnFailure(hr, "Failed to open policy registry key."); LExit: ReleaseStr(sczPath); diff --git a/src/dutil/proc2utl.cpp b/src/dutil/proc2utl.cpp index 8a2fd09b..a59d2ffc 100644 --- a/src/dutil/proc2utl.cpp +++ b/src/dutil/proc2utl.cpp @@ -2,6 +2,21 @@ #include "precomp.h" + +// Exit macros +#define ProcExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_PROCUTIL, x, s, __VA_ARGS__) +#define ProcExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_PROCUTIL, x, s, __VA_ARGS__) +#define ProcExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_PROCUTIL, x, s, __VA_ARGS__) +#define ProcExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_PROCUTIL, x, s, __VA_ARGS__) +#define ProcExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_PROCUTIL, x, s, __VA_ARGS__) +#define ProcExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_PROCUTIL, x, s, __VA_ARGS__) +#define ProcExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_PROCUTIL, p, x, e, s, __VA_ARGS__) +#define ProcExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_PROCUTIL, p, x, s, __VA_ARGS__) +#define ProcExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_PROCUTIL, p, x, e, s, __VA_ARGS__) +#define ProcExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_PROCUTIL, p, x, s, __VA_ARGS__) +#define ProcExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_PROCUTIL, e, x, s, __VA_ARGS__) +#define ProcExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_PROCUTIL, g, x, s, __VA_ARGS__) + /******************************************************************** ProcFindAllIdsFromExeName() - returns an array of process ids that are running specified executable. @@ -21,7 +36,7 @@ extern "C" HRESULT DAPI ProcFindAllIdsFromExeName( hSnap = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (INVALID_HANDLE_VALUE == hSnap) { - ExitWithLastError(hr, "Failed to create snapshot of processes on system"); + ProcExitWithLastError(hr, "Failed to create snapshot of processes on system"); } fContinue = ::Process32FirstW(hSnap, &peData); @@ -33,13 +48,13 @@ extern "C" HRESULT DAPI ProcFindAllIdsFromExeName( if (!*ppdwProcessIds) { *ppdwProcessIds = static_cast(MemAlloc(sizeof(DWORD), TRUE)); - ExitOnNull(ppdwProcessIds, hr, E_OUTOFMEMORY, "Failed to allocate array for returned process IDs."); + ProcExitOnNull(ppdwProcessIds, hr, E_OUTOFMEMORY, "Failed to allocate array for returned process IDs."); } else { DWORD* pdwReAllocReturnedPids = NULL; pdwReAllocReturnedPids = static_cast(MemReAlloc(*ppdwProcessIds, sizeof(DWORD) * ((*pcProcessIds) + 1), TRUE)); - ExitOnNull(pdwReAllocReturnedPids, hr, E_OUTOFMEMORY, "Failed to re-allocate array for returned process IDs."); + ProcExitOnNull(pdwReAllocReturnedPids, hr, E_OUTOFMEMORY, "Failed to re-allocate array for returned process IDs."); *ppdwProcessIds = pdwReAllocReturnedPids; } diff --git a/src/dutil/proc3utl.cpp b/src/dutil/proc3utl.cpp index 038f002b..6d3cbc67 100644 --- a/src/dutil/proc3utl.cpp +++ b/src/dutil/proc3utl.cpp @@ -2,6 +2,21 @@ #include "precomp.h" + +// Exit macros +#define ProcExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_PROCUTIL, x, s, __VA_ARGS__) +#define ProcExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_PROCUTIL, x, s, __VA_ARGS__) +#define ProcExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_PROCUTIL, x, s, __VA_ARGS__) +#define ProcExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_PROCUTIL, x, s, __VA_ARGS__) +#define ProcExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_PROCUTIL, x, s, __VA_ARGS__) +#define ProcExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_PROCUTIL, x, s, __VA_ARGS__) +#define ProcExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_PROCUTIL, p, x, e, s, __VA_ARGS__) +#define ProcExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_PROCUTIL, p, x, s, __VA_ARGS__) +#define ProcExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_PROCUTIL, p, x, e, s, __VA_ARGS__) +#define ProcExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_PROCUTIL, p, x, s, __VA_ARGS__) +#define ProcExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_PROCUTIL, e, x, s, __VA_ARGS__) +#define ProcExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_PROCUTIL, g, x, s, __VA_ARGS__) + static HRESULT GetActiveSessionUserToken( __out HANDLE *phToken ); @@ -25,20 +40,20 @@ extern "C" HRESULT DAPI ProcExecuteAsInteractiveUser( PROCESS_INFORMATION pi = { }; hr = GetActiveSessionUserToken(&hToken); - ExitOnFailure(hr, "Failed to get active session user token."); + ProcExitOnFailure(hr, "Failed to get active session user token."); if (!::CreateEnvironmentBlock(&pEnvironment, hToken, FALSE)) { - ExitWithLastError(hr, "Failed to create environment block for UI process."); + ProcExitWithLastError(hr, "Failed to create environment block for UI process."); } hr = StrAllocFormatted(&sczFullCommandLine, L"\"%ls\" %ls", wzExecutablePath, wzCommandLine); - ExitOnFailure(hr, "Failed to allocate full command-line."); + ProcExitOnFailure(hr, "Failed to allocate full command-line."); si.cb = sizeof(si); if (!::CreateProcessAsUserW(hToken, wzExecutablePath, sczFullCommandLine, NULL, NULL, FALSE, CREATE_UNICODE_ENVIRONMENT, pEnvironment, NULL, &si, &pi)) { - ExitWithLastError(hr, "Failed to create UI process: %ls", sczFullCommandLine); + ProcExitWithLastError(hr, "Failed to create UI process: %ls", sczFullCommandLine); } *phProcess = pi.hProcess; @@ -74,7 +89,7 @@ static HRESULT GetActiveSessionUserToken( // Loop through the sessions looking for the active one. if (!::WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE, 0, 1, &pSessionInfo, &cSessions)) { - ExitWithLastError(hr, "Failed to enumerate sessions."); + ProcExitWithLastError(hr, "Failed to enumerate sessions."); } for (DWORD i = 0; i < cSessions; ++i) @@ -96,7 +111,7 @@ static HRESULT GetActiveSessionUserToken( // Get the user token from the active session. if (!::WTSQueryUserToken(dwSessionId, &hToken)) { - ExitWithLastError(hr, "Failed to get active session user token."); + ProcExitWithLastError(hr, "Failed to get active session user token."); } *phToken = hToken; diff --git a/src/dutil/procutil.cpp b/src/dutil/procutil.cpp index 9833d0ec..6bfe5017 100644 --- a/src/dutil/procutil.cpp +++ b/src/dutil/procutil.cpp @@ -3,6 +3,21 @@ #include "precomp.h" +// Exit macros +#define ProcExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_PROCUTIL, x, s, __VA_ARGS__) +#define ProcExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_PROCUTIL, x, s, __VA_ARGS__) +#define ProcExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_PROCUTIL, x, s, __VA_ARGS__) +#define ProcExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_PROCUTIL, x, s, __VA_ARGS__) +#define ProcExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_PROCUTIL, x, s, __VA_ARGS__) +#define ProcExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_PROCUTIL, x, s, __VA_ARGS__) +#define ProcExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_PROCUTIL, p, x, e, s, __VA_ARGS__) +#define ProcExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_PROCUTIL, p, x, s, __VA_ARGS__) +#define ProcExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_PROCUTIL, p, x, e, s, __VA_ARGS__) +#define ProcExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_PROCUTIL, p, x, s, __VA_ARGS__) +#define ProcExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_PROCUTIL, e, x, s, __VA_ARGS__) +#define ProcExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_PROCUTIL, g, x, s, __VA_ARGS__) + + // private functions static HRESULT CreatePipes( __out HANDLE *phOutRead, @@ -30,7 +45,7 @@ extern "C" HRESULT DAPI ProcElevated( if (!::OpenProcessToken(hProcess, TOKEN_QUERY, &hToken)) { - ExitWithLastError(hr, "Failed to open process token."); + ProcExitWithLastError(hr, "Failed to open process token."); } if (::GetTokenInformation(hToken, TokenElevation, &tokenElevated, sizeof(TOKEN_ELEVATION), &cbToken)) @@ -50,7 +65,7 @@ extern "C" HRESULT DAPI ProcElevated( } else { - ExitOnRootFailure(hr, "Failed to get elevation token from process."); + ProcExitOnRootFailure(hr, "Failed to get elevation token from process."); } } @@ -76,7 +91,7 @@ extern "C" HRESULT DAPI ProcWow64( USHORT pProcessMachine = IMAGE_FILE_MACHINE_UNKNOWN; if (!pfnIsWow64Process2(hProcess, &pProcessMachine, nullptr)) { - ExitWithLastError(hr, "Failed to check WOW64 process - IsWow64Process2."); + ProcExitWithLastError(hr, "Failed to check WOW64 process - IsWow64Process2."); } if (pProcessMachine != IMAGE_FILE_MACHINE_UNKNOWN) @@ -93,7 +108,7 @@ extern "C" HRESULT DAPI ProcWow64( { if (!pfnIsWow64Process(hProcess, &fIsWow64)) { - ExitWithLastError(hr, "Failed to check WOW64 process - IsWow64Process."); + ProcExitWithLastError(hr, "Failed to check WOW64 process - IsWow64Process."); } } } @@ -121,7 +136,7 @@ extern "C" HRESULT DAPI ProcDisableWowFileSystemRedirection( if (!pfnWow64DisableWow64FsRedirection(&pfsr->pvRevertState)) { - ExitWithLastError(hr, "Failed to disable file system redirection."); + ProcExitWithLastError(hr, "Failed to disable file system redirection."); } pfsr->fDisabled = TRUE; @@ -143,7 +158,7 @@ extern "C" HRESULT DAPI ProcRevertWowFileSystemRedirection( if (!pfnWow64RevertWow64FsRedirection(pfsr->pvRevertState)) { - ExitWithLastError(hr, "Failed to revert file system redirection."); + ProcExitWithLastError(hr, "Failed to revert file system redirection."); } pfsr->fDisabled = FALSE; @@ -168,13 +183,13 @@ extern "C" HRESULT DAPI ProcExec( PROCESS_INFORMATION pi = { }; hr = StrAllocFormatted(&sczFullCommandLine, L"\"%ls\" %ls", wzExecutablePath, wzCommandLine ? wzCommandLine : L""); - ExitOnFailure(hr, "Failed to allocate full command-line."); + ProcExitOnFailure(hr, "Failed to allocate full command-line."); si.cb = sizeof(si); si.wShowWindow = static_cast(nCmdShow); if (!::CreateProcessW(wzExecutablePath, sczFullCommandLine, NULL, NULL, FALSE, 0, 0, NULL, &si, &pi)) { - ExitWithLastError(hr, "Failed to create process: %ls", sczFullCommandLine); + ProcExitWithLastError(hr, "Failed to create process: %ls", sczFullCommandLine); } *phProcess = pi.hProcess; @@ -213,7 +228,7 @@ extern "C" HRESULT DAPI ProcExecute( // Create redirect pipes. hr = CreatePipes(&hOutRead, &hOutWrite, &hErrWrite, &hInRead, &hInWrite); - ExitOnFailure(hr, "failed to create output pipes"); + ProcExitOnFailure(hr, "failed to create output pipes"); // Set up startup structure. si.cb = sizeof(STARTUPINFOW); @@ -249,7 +264,7 @@ extern "C" HRESULT DAPI ProcExecute( } else { - ExitWithLastError(hr, "Process failed to execute."); + ProcExitWithLastError(hr, "Process failed to execute."); } *phProcess = pi.hProcess; @@ -305,7 +320,7 @@ extern "C" HRESULT DAPI ProcWaitForCompletion( er = ::WaitForSingleObject(hProcess, dwTimeout); if (WAIT_FAILED == er) { - ExitWithLastError(hr, "Failed to wait for process to complete."); + ProcExitWithLastError(hr, "Failed to wait for process to complete."); } else if (WAIT_TIMEOUT == er) { @@ -314,7 +329,7 @@ extern "C" HRESULT DAPI ProcWaitForCompletion( if (!::GetExitCodeProcess(hProcess, &er)) { - ExitWithLastError(hr, "Failed to get process return code."); + ProcExitWithLastError(hr, "Failed to get process return code."); } *pReturnCode = er; @@ -340,7 +355,7 @@ extern "C" HRESULT DAPI ProcWaitForIds( DWORD cProcesses = 0; rghProcesses = static_cast(MemAlloc(sizeof(DWORD) * cProcessIds, TRUE)); - ExitOnNull(rgdwProcessIds, hr, E_OUTOFMEMORY, "Failed to allocate array for process ID Handles."); + ProcExitOnNull(rgdwProcessIds, hr, E_OUTOFMEMORY, "Failed to allocate array for process ID Handles."); for (DWORD i = 0; i < cProcessIds; ++i) { @@ -354,11 +369,11 @@ extern "C" HRESULT DAPI ProcWaitForIds( er = ::WaitForMultipleObjects(cProcesses, rghProcesses, TRUE, dwMilliseconds); if (WAIT_FAILED == er) { - ExitWithLastError(hr, "Failed to wait for process to complete."); + ProcExitWithLastError(hr, "Failed to wait for process to complete."); } else if (WAIT_TIMEOUT == er) { - ExitOnWin32Error(er, hr, "Timed out while waiting for process to complete."); + ProcExitOnWin32Error(er, hr, "Timed out while waiting for process to complete."); } LExit: @@ -393,7 +408,7 @@ extern "C" HRESULT DAPI ProcCloseIds( { if (!::EnumWindows(&CloseWindowEnumCallback, pdwProcessIds[i])) { - ExitWithLastError(hr, "Failed to enumerate windows."); + ProcExitWithLastError(hr, "Failed to enumerate windows."); } } @@ -430,30 +445,30 @@ static HRESULT CreatePipes( // Create pipes if (!::CreatePipe(&hOutTemp, &hOutWrite, &sa, 0)) { - ExitWithLastError(hr, "failed to create output pipe"); + ProcExitWithLastError(hr, "failed to create output pipe"); } if (!::CreatePipe(&hInRead, &hInTemp, &sa, 0)) { - ExitWithLastError(hr, "failed to create input pipe"); + ProcExitWithLastError(hr, "failed to create input pipe"); } // Duplicate output pipe so standard error and standard output write to the same pipe. if (!::DuplicateHandle(::GetCurrentProcess(), hOutWrite, ::GetCurrentProcess(), &hErrWrite, 0, TRUE, DUPLICATE_SAME_ACCESS)) { - ExitWithLastError(hr, "failed to duplicate write handle"); + ProcExitWithLastError(hr, "failed to duplicate write handle"); } // We need to create new "output read" and "input write" handles that are non inheritable. Otherwise CreateProcess will creates handles in // the child process that can't be closed. if (!::DuplicateHandle(::GetCurrentProcess(), hOutTemp, ::GetCurrentProcess(), &hOutRead, 0, FALSE, DUPLICATE_SAME_ACCESS)) { - ExitWithLastError(hr, "failed to duplicate output pipe"); + ProcExitWithLastError(hr, "failed to duplicate output pipe"); } if (!::DuplicateHandle(::GetCurrentProcess(), hInTemp, ::GetCurrentProcess(), &hInWrite, 0, FALSE, DUPLICATE_SAME_ACCESS)) { - ExitWithLastError(hr, "failed to duplicate input pipe"); + ProcExitWithLastError(hr, "failed to duplicate input pipe"); } // now that everything has succeeded, assign to the outputs diff --git a/src/dutil/regutil.cpp b/src/dutil/regutil.cpp index 1b13af81..e1ef19e8 100644 --- a/src/dutil/regutil.cpp +++ b/src/dutil/regutil.cpp @@ -2,6 +2,21 @@ #include "precomp.h" + +// Exit macros +#define RegExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_REGUTIL, x, s, __VA_ARGS__) +#define RegExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_REGUTIL, x, s, __VA_ARGS__) +#define RegExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_REGUTIL, x, s, __VA_ARGS__) +#define RegExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_REGUTIL, x, s, __VA_ARGS__) +#define RegExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_REGUTIL, x, s, __VA_ARGS__) +#define RegExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_REGUTIL, x, s, __VA_ARGS__) +#define RegExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_REGUTIL, p, x, e, s, __VA_ARGS__) +#define RegExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_REGUTIL, p, x, s, __VA_ARGS__) +#define RegExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_REGUTIL, p, x, e, s, __VA_ARGS__) +#define RegExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_REGUTIL, p, x, s, __VA_ARGS__) +#define RegExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_REGUTIL, e, x, s, __VA_ARGS__) +#define RegExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_REGUTIL, g, x, s, __VA_ARGS__) + static PFN_REGCREATEKEYEXW vpfnRegCreateKeyExW = ::RegCreateKeyExW; static PFN_REGOPENKEYEXW vpfnRegOpenKeyExW = ::RegOpenKeyExW; static PFN_REGDELETEKEYEXW vpfnRegDeleteKeyExW = NULL; @@ -34,7 +49,7 @@ extern "C" HRESULT DAPI RegInitialize( HRESULT hr = S_OK; hr = LoadSystemLibrary(L"AdvApi32.dll", &vhAdvApi32Dll); - ExitOnFailure(hr, "Failed to load AdvApi32.dll"); + RegExitOnFailure(hr, "Failed to load AdvApi32.dll"); // ignore failures - if this doesn't exist, we'll fall back to RegDeleteKeyW vpfnRegDeleteKeyExWFromLibrary = reinterpret_cast(::GetProcAddress(vhAdvApi32Dll, "RegDeleteKeyExW")); @@ -114,7 +129,7 @@ extern "C" HRESULT DAPI RegCreate( DWORD er = ERROR_SUCCESS; er = vpfnRegCreateKeyExW(hkRoot, wzSubKey, 0, NULL, REG_OPTION_NON_VOLATILE, dwAccess, NULL, phk, NULL); - ExitOnWin32Error(er, hr, "Failed to create registry key."); + RegExitOnWin32Error(er, hr, "Failed to create registry key."); LExit: return hr; @@ -140,7 +155,7 @@ HRESULT DAPI RegCreateEx( DWORD dwDisposition; er = vpfnRegCreateKeyExW(hkRoot, wzSubKey, 0, NULL, fVolatile ? REG_OPTION_VOLATILE : REG_OPTION_NON_VOLATILE, dwAccess, pSecurityAttributes, phk, &dwDisposition); - ExitOnWin32Error(er, hr, "Failed to create registry key."); + RegExitOnWin32Error(er, hr, "Failed to create registry key."); if (pfCreated) { @@ -171,7 +186,7 @@ extern "C" HRESULT DAPI RegOpen( { ExitFunction1(hr = E_FILENOTFOUND); } - ExitOnWin32Error(er, hr, "Failed to open registry key."); + RegExitOnWin32Error(er, hr, "Failed to open registry key."); LExit: return hr; @@ -199,7 +214,7 @@ extern "C" HRESULT DAPI RegDelete( if (!vfRegInitialized && REG_KEY_DEFAULT != kbKeyBitness) { hr = E_INVALIDARG; - ExitOnFailure(hr, "RegInitialize must be called first in order to RegDelete() a key with non-default bit attributes!"); + RegExitOnFailure(hr, "RegInitialize must be called first in order to RegDelete() a key with non-default bit attributes!"); } switch (kbKeyBitness) @@ -222,18 +237,18 @@ extern "C" HRESULT DAPI RegDelete( { ExitFunction1(hr = S_OK); } - ExitOnFailure(hr, "Failed to open this key for enumerating subkeys", wzSubKey); + RegExitOnFailure(hr, "Failed to open this key for enumerating subkeys: %ls", wzSubKey); // Yes, keep enumerating the 0th item, because we're deleting it every time while (E_NOMOREITEMS != (hr = RegKeyEnum(hkKey, 0, &pszEnumeratedSubKey))) { - ExitOnFailure(hr, "Failed to enumerate key 0"); + RegExitOnFailure(hr, "Failed to enumerate key 0"); hr = PathConcat(wzSubKey, pszEnumeratedSubKey, &pszRecursiveSubKey); - ExitOnFailure(hr, "Failed to concatenate paths while recursively deleting subkeys. Path1: %ls, Path2: %ls", wzSubKey, pszEnumeratedSubKey); + RegExitOnFailure(hr, "Failed to concatenate paths while recursively deleting subkeys. Path1: %ls, Path2: %ls", wzSubKey, pszEnumeratedSubKey); hr = RegDelete(hkRoot, pszRecursiveSubKey, kbKeyBitness, fDeleteTree); - ExitOnFailure(hr, "Failed to recursively delete subkey: %ls", pszRecursiveSubKey); + RegExitOnFailure(hr, "Failed to recursively delete subkey: %ls", pszRecursiveSubKey); } hr = S_OK; @@ -246,7 +261,7 @@ extern "C" HRESULT DAPI RegDelete( { ExitFunction1(hr = E_FILENOTFOUND); } - ExitOnWin32Error(er, hr, "Failed to delete registry key (ex)."); + RegExitOnWin32Error(er, hr, "Failed to delete registry key (ex)."); } else { @@ -255,7 +270,7 @@ extern "C" HRESULT DAPI RegDelete( { ExitFunction1(hr = E_FILENOTFOUND); } - ExitOnWin32Error(er, hr, "Failed to delete registry key."); + RegExitOnWin32Error(er, hr, "Failed to delete registry key."); } LExit: @@ -284,7 +299,7 @@ extern "C" HRESULT DAPI RegKeyEnum( if (psczKey && *psczKey) { hr = StrMaxLength(*psczKey, reinterpret_cast(&cch)); - ExitOnFailure(hr, "Failed to determine length of string."); + RegExitOnFailure(hr, "Failed to determine length of string."); } if (2 > cch) @@ -292,18 +307,18 @@ extern "C" HRESULT DAPI RegKeyEnum( cch = 2; hr = StrAlloc(psczKey, cch); - ExitOnFailure(hr, "Failed to allocate string to minimum size."); + RegExitOnFailure(hr, "Failed to allocate string to minimum size."); } er = vpfnRegEnumKeyExW(hk, dwIndex, *psczKey, &cch, NULL, NULL, NULL, NULL); if (ERROR_MORE_DATA == er) { er = vpfnRegQueryInfoKeyW(hk, NULL, NULL, NULL, NULL, &cch, NULL, NULL, NULL, NULL, NULL, NULL); - ExitOnWin32Error(er, hr, "Failed to get max size of subkey name under registry key."); + RegExitOnWin32Error(er, hr, "Failed to get max size of subkey name under registry key."); ++cch; // add one because RegQueryInfoKeyW() returns the length of the subkeys without the null terminator. hr = StrAlloc(psczKey, cch); - ExitOnFailure(hr, "Failed to allocate string bigger for enum registry key."); + RegExitOnFailure(hr, "Failed to allocate string bigger for enum registry key."); er = vpfnRegEnumKeyExW(hk, dwIndex, *psczKey, &cch, NULL, NULL, NULL, NULL); } @@ -311,7 +326,7 @@ extern "C" HRESULT DAPI RegKeyEnum( { ExitFunction1(hr = E_NOMOREITEMS); } - ExitOnWin32Error(er, hr, "Failed to enum registry key."); + RegExitOnWin32Error(er, hr, "Failed to enum registry key."); // Always ensure the registry key name is null terminated. #pragma prefast(push) @@ -340,20 +355,20 @@ HRESULT DAPI RegValueEnum( DWORD cbValueName = 0; er = vpfnRegQueryInfoKeyW(hk, NULL, NULL, NULL, NULL, NULL, NULL, NULL, &cbValueName, NULL, NULL, NULL); - ExitOnWin32Error(er, hr, "Failed to get max size of value name under registry key."); + RegExitOnWin32Error(er, hr, "Failed to get max size of value name under registry key."); // Add one for null terminator ++cbValueName; hr = StrAlloc(psczName, cbValueName); - ExitOnFailure(hr, "Failed to allocate array for registry value name"); + RegExitOnFailure(hr, "Failed to allocate array for registry value name"); er = vpfnRegEnumValueW(hk, dwIndex, *psczName, &cbValueName, NULL, pdwType, NULL, NULL); if (ERROR_NO_MORE_ITEMS == er) { ExitFunction1(hr = E_NOMOREITEMS); } - ExitOnWin32Error(er, hr, "Failed to enumerate registry value"); + RegExitOnWin32Error(er, hr, "Failed to enumerate registry value"); LExit: return hr; @@ -376,7 +391,7 @@ HRESULT DAPI RegGetType( { ExitFunction1(hr = E_FILENOTFOUND); } - ExitOnWin32Error(er, hr, "Failed to read registry value."); + RegExitOnWin32Error(er, hr, "Failed to read registry value."); LExit: return hr; @@ -400,20 +415,20 @@ HRESULT DAPI RegReadBinary( DWORD dwType = 0; er = vpfnRegQueryValueExW(hk, wzName, NULL, &dwType, NULL, &cb); - ExitOnWin32Error(er, hr, "Failed to get size of registry value."); + RegExitOnWin32Error(er, hr, "Failed to get size of registry value."); // Zero-length binary values can exist if (0 < cb) { pbBuffer = static_cast(MemAlloc(cb, FALSE)); - ExitOnNull(pbBuffer, hr, E_OUTOFMEMORY, "Failed to allocate buffer for binary registry value."); + RegExitOnNull(pbBuffer, hr, E_OUTOFMEMORY, "Failed to allocate buffer for binary registry value."); er = vpfnRegQueryValueExW(hk, wzName, NULL, &dwType, pbBuffer, &cb); if (E_FILENOTFOUND == HRESULT_FROM_WIN32(er)) { ExitFunction1(hr = E_FILENOTFOUND); } - ExitOnWin32Error(er, hr, "Failed to read registry value."); + RegExitOnWin32Error(er, hr, "Failed to read registry value."); } if (REG_BINARY == dwType) @@ -425,7 +440,7 @@ HRESULT DAPI RegReadBinary( else { hr = HRESULT_FROM_WIN32(ERROR_INVALID_DATATYPE); - ExitOnRootFailure(hr, "Error reading binary registry value due to unexpected data type: %u", dwType); + RegExitOnRootFailure(hr, "Error reading binary registry value due to unexpected data type: %u", dwType); } LExit: @@ -455,7 +470,7 @@ extern "C" HRESULT DAPI RegReadString( if (psczValue && *psczValue) { hr = StrMaxLength(*psczValue, reinterpret_cast(&cch)); - ExitOnFailure(hr, "Failed to determine length of string."); + RegExitOnFailure(hr, "Failed to determine length of string."); } if (2 > cch) @@ -463,7 +478,7 @@ extern "C" HRESULT DAPI RegReadString( cch = 2; hr = StrAlloc(psczValue, cch); - ExitOnFailure(hr, "Failed to allocate string to minimum size."); + RegExitOnFailure(hr, "Failed to allocate string to minimum size."); } cb = sizeof(WCHAR) * (cch - 1); // subtract one to ensure there will be a space at the end of the string for the null terminator. @@ -472,7 +487,7 @@ extern "C" HRESULT DAPI RegReadString( { cch = cb / sizeof(WCHAR) + 1; // add one to ensure there will be space at the end for the null terminator hr = StrAlloc(psczValue, cch); - ExitOnFailure(hr, "Failed to allocate string bigger for registry value."); + RegExitOnFailure(hr, "Failed to allocate string bigger for registry value."); er = vpfnRegQueryValueExW(hk, wzName, NULL, &dwType, reinterpret_cast(*psczValue), &cb); } @@ -480,7 +495,7 @@ extern "C" HRESULT DAPI RegReadString( { ExitFunction1(hr = E_FILENOTFOUND); } - ExitOnWin32Error(er, hr, "Failed to read registry key."); + RegExitOnWin32Error(er, hr, "Failed to read registry key."); if (REG_SZ == dwType || REG_EXPAND_SZ == dwType) { @@ -490,16 +505,16 @@ extern "C" HRESULT DAPI RegReadString( if (REG_EXPAND_SZ == dwType) { hr = StrAllocString(&sczExpand, *psczValue, 0); - ExitOnFailure(hr, "Failed to copy registry value to expand."); + RegExitOnFailure(hr, "Failed to copy registry value to expand."); hr = PathExpand(psczValue, sczExpand, PATH_EXPAND_ENVIRONMENT); - ExitOnFailure(hr, "Failed to expand registry value: %ls", *psczValue); + RegExitOnFailure(hr, "Failed to expand registry value: %ls", *psczValue); } } else { hr = HRESULT_FROM_WIN32(ERROR_INVALID_DATATYPE); - ExitOnRootFailure(hr, "Error reading string registry value due to unexpected data type: %u", dwType); + RegExitOnRootFailure(hr, "Error reading string registry value due to unexpected data type: %u", dwType); } LExit: @@ -516,7 +531,7 @@ LExit: HRESULT DAPI RegReadStringArray( __in HKEY hk, __in_z_opt LPCWSTR wzName, - __deref_out_ecount_opt(pcStrings) LPWSTR** prgsczStrings, + __deref_out_ecount_opt(*pcStrings) LPWSTR** prgsczStrings, __out DWORD *pcStrings ) { @@ -534,7 +549,7 @@ HRESULT DAPI RegReadStringArray( { cch = cb / sizeof(WCHAR); hr = StrAlloc(&sczValue, cch); - ExitOnFailure(hr, "Failed to allocate string for registry value."); + RegExitOnFailure(hr, "Failed to allocate string for registry value."); er = vpfnRegQueryValueExW(hk, wzName, NULL, &dwType, reinterpret_cast(sczValue), &cb); } @@ -542,18 +557,18 @@ HRESULT DAPI RegReadStringArray( { ExitFunction1(hr = E_FILENOTFOUND); } - ExitOnWin32Error(er, hr, "Failed to read registry key."); + RegExitOnWin32Error(er, hr, "Failed to read registry key."); if (cb / sizeof(WCHAR) != cch) { hr = E_UNEXPECTED; - ExitOnFailure(hr, "The size of registry value %ls unexpected changed between 2 reads", wzName); + RegExitOnFailure(hr, "The size of registry value %ls unexpected changed between 2 reads", wzName); } if (REG_MULTI_SZ != dwType) { hr = HRESULT_FROM_WIN32(ERROR_INVALID_DATATYPE); - ExitOnRootFailure(hr, "Tried to read string array, but registry value %ls is of an incorrect type", wzName); + RegExitOnRootFailure(hr, "Tried to read string array, but registry value %ls is of an incorrect type", wzName); } // Value exists, but is empty, so no strings to return. @@ -568,7 +583,7 @@ HRESULT DAPI RegReadStringArray( if (L'\0' != sczValue[cch-1] || L'\0' != sczValue[cch-2]) { hr = E_INVALIDARG; - ExitOnFailure(hr, "Tried to read string array, but registry value %ls is invalid (isn't double-null-terminated)", wzName); + RegExitOnFailure(hr, "Tried to read string array, but registry value %ls is invalid (isn't double-null-terminated)", wzName); } cch = cb / sizeof(WCHAR); @@ -583,7 +598,7 @@ HRESULT DAPI RegReadStringArray( // There's one string for every null character encountered (except the extra 1 at the end of the string) *pcStrings = dwNullCharacters - 1; hr = MemEnsureArraySize(reinterpret_cast(prgsczStrings), *pcStrings, sizeof(LPWSTR), 0); - ExitOnFailure(hr, "Failed to resize array while reading REG_MULTI_SZ value"); + RegExitOnFailure(hr, "Failed to resize array while reading REG_MULTI_SZ value"); #pragma prefast(push) #pragma prefast(disable:26010) @@ -591,7 +606,7 @@ HRESULT DAPI RegReadStringArray( for (DWORD i = 0; i < *pcStrings; ++i) { hr = StrAllocString(&(*prgsczStrings)[i], wzSource, 0); - ExitOnFailure(hr, "Failed to allocate copy of string"); + RegExitOnFailure(hr, "Failed to allocate copy of string"); // Skip past this string wzSource += lstrlenW(wzSource) + 1; @@ -630,19 +645,19 @@ extern "C" HRESULT DAPI RegReadVersion( if (REG_SZ == dwType || REG_EXPAND_SZ == dwType) { hr = RegReadString(hk, wzName, &sczVersion); - ExitOnFailure(hr, "Failed to read registry version as string."); + RegExitOnFailure(hr, "Failed to read registry version as string."); hr = FileVersionFromStringEx(sczVersion, 0, pdw64Version); - ExitOnFailure(hr, "Failed to convert registry string to version."); + RegExitOnFailure(hr, "Failed to convert registry string to version."); } else if (REG_QWORD == dwType) { - ExitOnWin32Error(er, hr, "Failed to read registry key."); + RegExitOnWin32Error(er, hr, "Failed to read registry key."); } else // unexpected data type { hr = HRESULT_FROM_WIN32(ERROR_INVALID_DATATYPE); - ExitOnRootFailure(hr, "Error reading version registry value due to unexpected data type: %u", dwType); + RegExitOnRootFailure(hr, "Error reading version registry value due to unexpected data type: %u", dwType); } LExit: @@ -672,12 +687,12 @@ extern "C" HRESULT DAPI RegReadNumber( { ExitFunction1(hr = E_FILENOTFOUND); } - ExitOnWin32Error(er, hr, "Failed to query registry key value."); + RegExitOnWin32Error(er, hr, "Failed to query registry key value."); if (REG_DWORD != dwType) { hr = HRESULT_FROM_WIN32(ERROR_INVALID_DATATYPE); - ExitOnRootFailure(hr, "Error reading version registry value due to unexpected data type: %u", dwType); + RegExitOnRootFailure(hr, "Error reading version registry value due to unexpected data type: %u", dwType); } LExit: @@ -705,12 +720,12 @@ extern "C" HRESULT DAPI RegReadQword( { ExitFunction1(hr = E_FILENOTFOUND); } - ExitOnWin32Error(er, hr, "Failed to query registry key value."); + RegExitOnWin32Error(er, hr, "Failed to query registry key value."); if (REG_QWORD != dwType) { hr = HRESULT_FROM_WIN32(ERROR_INVALID_DATATYPE); - ExitOnRootFailure(hr, "Error reading version registry value due to unexpected data type: %u", dwType); + RegExitOnRootFailure(hr, "Error reading version registry value due to unexpected data type: %u", dwType); } LExit: @@ -733,7 +748,7 @@ HRESULT DAPI RegWriteBinary( DWORD er = ERROR_SUCCESS; er = vpfnRegSetValueExW(hk, wzName, 0, REG_BINARY, pbBuffer, cbBuffer); - ExitOnWin32Error(er, hr, "Failed to write binary registry value with name: %ls", wzName); + RegExitOnWin32Error(er, hr, "Failed to write binary registry value with name: %ls", wzName); LExit: return hr; @@ -788,7 +803,7 @@ extern "C" HRESULT DAPI RegWriteStringFormatted( va_start(args, szFormat); hr = StrAllocFormattedArgs(&sczValue, szFormat, args); va_end(args); - ExitOnFailure(hr, "Failed to allocate %ls value.", wzName); + RegExitOnFailure(hr, "Failed to allocate %ls value.", wzName); hr = WriteStringToRegistry(hk, wzName, sczValue, REG_SZ); @@ -832,18 +847,18 @@ HRESULT DAPI RegWriteStringArray( { dwTemp = dwTotalStringSize; hr = ::DWordAdd(dwTemp, 1 + lstrlenW(rgwzValues[i]), &dwTotalStringSize); - ExitOnFailure(hr, "DWORD Overflow while adding length of string to write REG_MULTI_SZ"); + RegExitOnFailure(hr, "DWORD Overflow while adding length of string to write REG_MULTI_SZ"); } hr = StrAlloc(&sczWriteValue, dwTotalStringSize); - ExitOnFailure(hr, "Failed to allocate space for string while writing REG_MULTI_SZ"); + RegExitOnFailure(hr, "Failed to allocate space for string while writing REG_MULTI_SZ"); wzCopyDestination = sczWriteValue; dwTemp = dwTotalStringSize; for (DWORD i = 0; i < cValues; ++i) { hr = ::StringCchCopyW(wzCopyDestination, dwTotalStringSize, rgwzValues[i]); - ExitOnFailure(hr, "failed to copy string: %ls", rgwzValues[i]); + RegExitOnFailure(hr, "failed to copy string: %ls", rgwzValues[i]); dwTemp -= lstrlenW(rgwzValues[i]) + 1; wzCopyDestination += lstrlenW(rgwzValues[i]) + 1; @@ -853,10 +868,10 @@ HRESULT DAPI RegWriteStringArray( } hr = ::DWordMult(dwTotalStringSize, sizeof(WCHAR), &cbTotalStringSize); - ExitOnFailure(hr, "Failed to get total string size in bytes"); + RegExitOnFailure(hr, "Failed to get total string size in bytes"); er = vpfnRegSetValueExW(hk, wzName, 0, REG_MULTI_SZ, reinterpret_cast(wzWriteValue), cbTotalStringSize); - ExitOnWin32Error(er, hr, "Failed to set registry value to array of strings (first string of which is): %ls", wzWriteValue); + RegExitOnWin32Error(er, hr, "Failed to set registry value to array of strings (first string of which is): %ls", wzWriteValue); LExit: ReleaseStr(sczWriteValue); @@ -878,7 +893,7 @@ extern "C" HRESULT DAPI RegWriteNumber( DWORD er = ERROR_SUCCESS; er = vpfnRegSetValueExW(hk, wzName, 0, REG_DWORD, reinterpret_cast(&dwValue), sizeof(dwValue)); - ExitOnWin32Error(er, hr, "Failed to set %ls value.", wzName); + RegExitOnWin32Error(er, hr, "Failed to set %ls value.", wzName); LExit: return hr; @@ -898,7 +913,7 @@ extern "C" HRESULT DAPI RegWriteQword( DWORD er = ERROR_SUCCESS; er = vpfnRegSetValueExW(hk, wzName, 0, REG_QWORD, reinterpret_cast(&qwValue), sizeof(qwValue)); - ExitOnWin32Error(er, hr, "Failed to set %ls value.", wzName); + RegExitOnWin32Error(er, hr, "Failed to set %ls value.", wzName); LExit: return hr; @@ -918,7 +933,7 @@ extern "C" HRESULT DAPI RegQueryKey( DWORD er = ERROR_SUCCESS; er = vpfnRegQueryInfoKeyW(hk, NULL, NULL, NULL, pcSubKeys, NULL, NULL, pcValues, NULL, NULL, NULL, NULL); - ExitOnWin32Error(er, hr, "Failed to get the number of subkeys and values under registry key."); + RegExitOnWin32Error(er, hr, "Failed to get the number of subkeys and values under registry key."); LExit: return hr; @@ -938,11 +953,11 @@ static HRESULT WriteStringToRegistry( if (wzValue) { - hr = ::StringCbLengthW(wzValue, DWORD_MAX, reinterpret_cast(&cbValue)); - ExitOnFailure(hr, "Failed to determine length of registry value: %ls", wzName); + hr = ::StringCbLengthW(wzValue, STRSAFE_MAX_CCH * sizeof(TCHAR), reinterpret_cast(&cbValue)); + RegExitOnFailure(hr, "Failed to determine length of registry value: %ls", wzName); er = vpfnRegSetValueExW(hk, wzName, 0, dwType, reinterpret_cast(wzValue), cbValue); - ExitOnWin32Error(er, hr, "Failed to set registry value: %ls", wzName); + RegExitOnWin32Error(er, hr, "Failed to set registry value: %ls", wzName); } else { @@ -951,7 +966,7 @@ static HRESULT WriteStringToRegistry( { er = ERROR_SUCCESS; } - ExitOnWin32Error(er, hr, "Failed to delete registry value: %ls", wzName); + RegExitOnWin32Error(er, hr, "Failed to delete registry value: %ls", wzName); } LExit: diff --git a/src/dutil/resrutil.cpp b/src/dutil/resrutil.cpp index 1da03ed9..a6a7ee23 100644 --- a/src/dutil/resrutil.cpp +++ b/src/dutil/resrutil.cpp @@ -2,6 +2,21 @@ #include "precomp.h" + +// Exit macros +#define ResrExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_RESRUTIL, x, s, __VA_ARGS__) +#define ResrExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_RESRUTIL, x, s, __VA_ARGS__) +#define ResrExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_RESRUTIL, x, s, __VA_ARGS__) +#define ResrExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_RESRUTIL, x, s, __VA_ARGS__) +#define ResrExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_RESRUTIL, x, s, __VA_ARGS__) +#define ResrExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_RESRUTIL, x, s, __VA_ARGS__) +#define ResrExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_RESRUTIL, p, x, e, s, __VA_ARGS__) +#define ResrExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_RESRUTIL, p, x, s, __VA_ARGS__) +#define ResrExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_RESRUTIL, p, x, e, s, __VA_ARGS__) +#define ResrExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_RESRUTIL, p, x, s, __VA_ARGS__) +#define ResrExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_RESRUTIL, e, x, s, __VA_ARGS__) +#define ResrExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_RESRUTIL, g, x, s, __VA_ARGS__) + #define RES_STRINGS_PER_BLOCK 16 @@ -33,7 +48,7 @@ extern "C" HRESULT DAPI ResGetStringLangId( if (wzPath && *wzPath) { hModule = LoadLibraryExW(wzPath, NULL, DONT_RESOLVE_DLL_REFERENCES | LOAD_LIBRARY_AS_DATAFILE); - ExitOnNullWithLastError(hModule, hr, "Failed to open resource file: %ls", wzPath); + ResrExitOnNullWithLastError(hModule, hr, "Failed to open resource file: %ls", wzPath); } #pragma prefast(push) @@ -41,7 +56,7 @@ extern "C" HRESULT DAPI ResGetStringLangId( if (!::EnumResourceLanguagesA(hModule, RT_STRING, MAKEINTRESOURCE(dwBlockId), static_cast(EnumLangIdProc), reinterpret_cast(&wFoundLangId))) #pragma prefast(pop) { - ExitWithLastError(hr, "Failed to find string language identifier."); + ResrExitWithLastError(hr, "Failed to find string language identifier."); } *pwLangId = wFoundLangId; @@ -76,12 +91,12 @@ extern "C" HRESULT DAPI ResReadString( do { hr = StrAlloc(ppwzString, cch); - ExitOnFailureDebugTrace(hr, "Failed to allocate string for resource id: %d", uID); + ResrExitOnFailureDebugTrace(hr, "Failed to allocate string for resource id: %d", uID); cchReturned = ::LoadStringW(hinst, uID, *ppwzString, cch); if (0 == cchReturned) { - ExitWithLastError(hr, "Failed to load string resource id: %d", uID); + ResrExitWithLastError(hr, "Failed to load string resource id: %d", uID); } // if the returned string count is one character too small, it's likely we have @@ -92,7 +107,7 @@ extern "C" HRESULT DAPI ResReadString( hr = S_FALSE; } } while (S_FALSE == hr); - ExitOnFailure(hr, "Failed to load string resource id: %d", uID); + ResrExitOnFailure(hr, "Failed to load string resource id: %d", uID); LExit: return hr; @@ -119,7 +134,7 @@ extern "C" HRESULT DAPI ResReadStringAnsi( do { hr = StrAnsiAlloc(ppszString, cch); - ExitOnFailureDebugTrace(hr, "Failed to allocate string for resource id: %d", uID); + ResrExitOnFailureDebugTrace(hr, "Failed to allocate string for resource id: %d", uID); #pragma prefast(push) #pragma prefast(disable:25068) @@ -127,7 +142,7 @@ extern "C" HRESULT DAPI ResReadStringAnsi( #pragma prefast(pop) if (0 == cchReturned) { - ExitWithLastError(hr, "Failed to load string resource id: %d", uID); + ResrExitWithLastError(hr, "Failed to load string resource id: %d", uID); } // if the returned string count is one character too small, it's likely we have @@ -138,7 +153,7 @@ extern "C" HRESULT DAPI ResReadStringAnsi( hr = S_FALSE; } } while (S_FALSE == hr); - ExitOnFailure(hr, "failed to load string resource id: %d", uID); + ResrExitOnFailure(hr, "failed to load string resource id: %d", uID); LExit: return hr; @@ -169,19 +184,19 @@ extern "C" HRESULT DAPI ResReadData( #pragma prefast(disable:25068) hRsrc = ::FindResourceExA(hinst, RT_RCDATA, szDataName, MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL)); #pragma prefast(pop) - ExitOnNullWithLastError(hRsrc, hr, "Failed to find resource."); + ResrExitOnNullWithLastError(hRsrc, hr, "Failed to find resource."); hData = ::LoadResource(hinst, hRsrc); - ExitOnNullWithLastError(hData, hr, "Failed to load resource."); + ResrExitOnNullWithLastError(hData, hr, "Failed to load resource."); cbData = ::SizeofResource(hinst, hRsrc); if (!cbData) { - ExitWithLastError(hr, "Failed to get size of resource."); + ResrExitWithLastError(hr, "Failed to get size of resource."); } *ppv = ::LockResource(hData); - ExitOnNullWithLastError(*ppv, hr, "Failed to lock data resource."); + ResrExitOnNullWithLastError(*ppv, hr, "Failed to lock data resource."); *pcb = cbData; LExit: @@ -207,18 +222,18 @@ extern "C" HRESULT DAPI ResExportDataToFile( BOOL bCreatedFile = FALSE; hr = ResReadData(NULL, szDataName, &pData, &cbData); - ExitOnFailure(hr, "Failed to GetData from %s.", szDataName); + ResrExitOnFailure(hr, "Failed to GetData from %s.", szDataName); hFile = ::CreateFileW(wzTargetFile, GENERIC_WRITE, 0, NULL, dwCreationDisposition, FILE_ATTRIBUTE_NORMAL, NULL); if (INVALID_HANDLE_VALUE == hFile) { - ExitWithLastError(hr, "Failed to CreateFileW for %ls.", wzTargetFile); + ResrExitWithLastError(hr, "Failed to CreateFileW for %ls.", wzTargetFile); } bCreatedFile = TRUE; if (!::WriteFile(hFile, pData, cbData, &cbWritten, NULL)) { - ExitWithLastError(hr, "Failed to ::WriteFile for %ls.", wzTargetFile); + ResrExitWithLastError(hr, "Failed to ::WriteFile for %ls.", wzTargetFile); } LExit: diff --git a/src/dutil/reswutil.cpp b/src/dutil/reswutil.cpp index e534fc09..42b49c55 100644 --- a/src/dutil/reswutil.cpp +++ b/src/dutil/reswutil.cpp @@ -2,6 +2,21 @@ #include "precomp.h" + +// Exit macros +#define ReswExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_RESWUTIL, x, s, __VA_ARGS__) +#define ReswExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_RESWUTIL, x, s, __VA_ARGS__) +#define ReswExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_RESWUTIL, x, s, __VA_ARGS__) +#define ReswExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_RESWUTIL, x, s, __VA_ARGS__) +#define ReswExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_RESWUTIL, x, s, __VA_ARGS__) +#define ReswExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_RESWUTIL, x, s, __VA_ARGS__) +#define ReswExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_RESWUTIL, p, x, e, s, __VA_ARGS__) +#define ReswExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_RESWUTIL, p, x, s, __VA_ARGS__) +#define ReswExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_RESWUTIL, p, x, e, s, __VA_ARGS__) +#define ReswExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_RESWUTIL, p, x, s, __VA_ARGS__) +#define ReswExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_RESWUTIL, e, x, s, __VA_ARGS__) +#define ReswExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_RESWUTIL, g, x, s, __VA_ARGS__) + #define RES_STRINGS_PER_BLOCK 16 // Internal data structure format for a string block in a resource table. @@ -66,31 +81,31 @@ extern "C" HRESULT DAPI ResWriteString( DWORD dwStringId = (dwDataId % RES_STRINGS_PER_BLOCK); hModule = LoadLibraryExW(wzResourceFile, NULL, DONT_RESOLVE_DLL_REFERENCES | LOAD_LIBRARY_AS_DATAFILE); - ExitOnNullWithLastError(hModule, hr, "Failed to load library: %ls", wzResourceFile); + ReswExitOnNullWithLastError(hModule, hr, "Failed to load library: %ls", wzResourceFile); hr = StringBlockInitialize(hModule, dwBlockId, wLangId, &StrBlock); - ExitOnFailure(hr, "Failed to get string block to update."); + ReswExitOnFailure(hr, "Failed to get string block to update."); hr = StringBlockChangeString(&StrBlock, dwStringId, wzData); - ExitOnFailure(hr, "Failed to update string block string."); + ReswExitOnFailure(hr, "Failed to update string block string."); hr = StringBlockConvertToResourceData(&StrBlock, &pvData, &cbData); - ExitOnFailure(hr, "Failed to convert string block to resource data."); + ReswExitOnFailure(hr, "Failed to convert string block to resource data."); ::FreeLibrary(hModule); hModule = NULL; hUpdate = ::BeginUpdateResourceW(wzResourceFile, FALSE); - ExitOnNullWithLastError(hUpdate, hr, "Failed to ::BeginUpdateResourcesW."); + ReswExitOnNullWithLastError(hUpdate, hr, "Failed to ::BeginUpdateResourcesW."); if (!::UpdateResourceA(hUpdate, RT_STRING, MAKEINTRESOURCE(dwBlockId), wLangId, pvData, cbData)) { - ExitWithLastError(hr, "Failed to ::UpdateResourceA."); + ReswExitWithLastError(hr, "Failed to ::UpdateResourceA."); } if (!::EndUpdateResource(hUpdate, FALSE)) { - ExitWithLastError(hr, "Failed to ::EndUpdateResourceW."); + ReswExitWithLastError(hr, "Failed to ::EndUpdateResourceW."); } hUpdate = NULL; @@ -134,16 +149,16 @@ extern "C" HRESULT DAPI ResWriteData( HANDLE hUpdate = NULL; hUpdate = ::BeginUpdateResourceW(wzResourceFile, FALSE); - ExitOnNullWithLastError(hUpdate, hr, "Failed to ::BeginUpdateResourcesW."); + ReswExitOnNullWithLastError(hUpdate, hr, "Failed to ::BeginUpdateResourcesW."); if (!::UpdateResourceA(hUpdate, RT_RCDATA, szDataName, MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), pData, cbData)) { - ExitWithLastError(hr, "Failed to ::UpdateResourceA."); + ReswExitWithLastError(hr, "Failed to ::UpdateResourceA."); } if (!::EndUpdateResource(hUpdate, FALSE)) { - ExitWithLastError(hr, "Failed to ::EndUpdateResourceW."); + ReswExitWithLastError(hr, "Failed to ::EndUpdateResourceW."); } hUpdate = NULL; @@ -177,23 +192,23 @@ extern "C" HRESULT DAPI ResImportDataFromFile( hFile = ::CreateFileW(wzSourceFile, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (INVALID_HANDLE_VALUE == hFile) { - ExitWithLastError(hr, "Failed to CreateFileW for %ls.", wzSourceFile); + ReswExitWithLastError(hr, "Failed to CreateFileW for %ls.", wzSourceFile); } cbFile = ::GetFileSize(hFile, NULL); if (!cbFile) { - ExitWithLastError(hr, "Failed to GetFileSize for %ls.", wzSourceFile); + ReswExitWithLastError(hr, "Failed to GetFileSize for %ls.", wzSourceFile); } hMap = ::CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL); - ExitOnNullWithLastError(hMap, hr, "Failed to CreateFileMapping for %ls.", wzSourceFile); + ReswExitOnNullWithLastError(hMap, hr, "Failed to CreateFileMapping for %ls.", wzSourceFile); pv = ::MapViewOfFile(hMap, FILE_MAP_READ, 0, 0, cbFile); - ExitOnNullWithLastError(pv, hr, "Failed to MapViewOfFile for %ls.", wzSourceFile); + ReswExitOnNullWithLastError(pv, hr, "Failed to MapViewOfFile for %ls.", wzSourceFile); hr = ResWriteData(wzTargetFile, szDataName, pv, cbFile); - ExitOnFailure(hr, "Failed to ResSetData %s on file %ls.", szDataName, wzTargetFile); + ReswExitOnFailure(hr, "Failed to ResSetData %s on file %ls.", szDataName, wzTargetFile); LExit: if (pv) @@ -226,25 +241,25 @@ static HRESULT StringBlockInitialize( DWORD cbData = 0; hRsrc = ::FindResourceExA(hModule, RT_STRING, MAKEINTRESOURCE(dwBlockId), wLangId); - ExitOnNullWithLastError(hRsrc, hr, "Failed to ::FindResourceExW."); + ReswExitOnNullWithLastError(hRsrc, hr, "Failed to ::FindResourceExW."); hData = ::LoadResource(hModule, hRsrc); - ExitOnNullWithLastError(hData, hr, "Failed to ::LoadResource."); + ReswExitOnNullWithLastError(hData, hr, "Failed to ::LoadResource."); cbData = ::SizeofResource(hModule, hRsrc); if (!cbData) { - ExitWithLastError(hr, "Failed to ::SizeofResource."); + ReswExitWithLastError(hr, "Failed to ::SizeofResource."); } pvData = ::LockResource(hData); - ExitOnNullWithLastError(pvData, hr, "Failed to lock data resource."); + ReswExitOnNullWithLastError(pvData, hr, "Failed to lock data resource."); pStrBlock->dwBlockId = dwBlockId; pStrBlock->wLangId = wLangId; hr = StringBlockConvertFromResourceData(pStrBlock, pvData, cbData); - ExitOnFailure(hr, "Failed to convert string block from resource data."); + ReswExitOnFailure(hr, "Failed to convert string block from resource data."); LExit: return hr; @@ -276,10 +291,10 @@ static HRESULT StringBlockChangeString( DWORD cchData = lstrlenW(szData); pwzData = static_cast(MemAlloc((cchData + 1) * sizeof(WCHAR), TRUE)); - ExitOnNull(pwzData, hr, E_OUTOFMEMORY, "Failed to allocate new block string."); + ReswExitOnNull(pwzData, hr, E_OUTOFMEMORY, "Failed to allocate new block string."); hr = ::StringCchCopyW(pwzData, cchData + 1, szData); - ExitOnFailure(hr, "Failed to copy new block string."); + ReswExitOnFailure(hr, "Failed to copy new block string."); ReleaseNullMem(pStrBlock->rgwz[dwStringId]); @@ -311,7 +326,7 @@ static HRESULT StringBlockConvertToResourceData( cbData *= sizeof(WCHAR); pvData = MemAlloc(cbData, TRUE); - ExitOnNull(pvData, hr, E_OUTOFMEMORY, "Failed to allocate buffer to convert string block."); + ReswExitOnNull(pvData, hr, E_OUTOFMEMORY, "Failed to allocate buffer to convert string block."); pwz = static_cast(pvData); for (DWORD i = 0; i < RES_STRINGS_PER_BLOCK; ++i) @@ -355,10 +370,10 @@ static HRESULT StringBlockConvertFromResourceData( ++pwzParse; pStrBlock->rgwz[i] = static_cast(MemAlloc((cchParse + 1) * sizeof(WCHAR), TRUE)); - ExitOnNull(pStrBlock->rgwz[i], hr, E_OUTOFMEMORY, "Failed to populate pStrBlock."); + ReswExitOnNull(pStrBlock->rgwz[i], hr, E_OUTOFMEMORY, "Failed to populate pStrBlock."); hr = ::StringCchCopyNExW(pStrBlock->rgwz[i], cchParse + 1, pwzParse, cchParse, NULL, NULL, STRSAFE_FILL_BEHIND_NULL); - ExitOnFailure(hr, "Failed to copy parsed resource data into string block."); + ReswExitOnFailure(hr, "Failed to copy parsed resource data into string block."); pwzParse += cchParse; } diff --git a/src/dutil/rexutil.cpp b/src/dutil/rexutil.cpp index 73500630..155ca714 100644 --- a/src/dutil/rexutil.cpp +++ b/src/dutil/rexutil.cpp @@ -3,6 +3,21 @@ #include "precomp.h" #include "rexutil.h" + +// Exit macros +#define RexExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_REXUTIL, x, s, __VA_ARGS__) +#define RexExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_REXUTIL, x, s, __VA_ARGS__) +#define RexExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_REXUTIL, x, s, __VA_ARGS__) +#define RexExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_REXUTIL, x, s, __VA_ARGS__) +#define RexExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_REXUTIL, x, s, __VA_ARGS__) +#define RexExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_REXUTIL, x, s, __VA_ARGS__) +#define RexExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_REXUTIL, p, x, e, s, __VA_ARGS__) +#define RexExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_REXUTIL, p, x, s, __VA_ARGS__) +#define RexExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_REXUTIL, p, x, e, s, __VA_ARGS__) +#define RexExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_REXUTIL, p, x, s, __VA_ARGS__) +#define RexExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_REXUTIL, e, x, s, __VA_ARGS__) +#define RexExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_REXUTIL, g, x, s, __VA_ARGS__) + // // static globals // @@ -60,7 +75,7 @@ extern "C" HRESULT RexInitialize() if (!vhfdi) { hr = E_FAIL; - ExitOnFailure(hr, "failed to initialize cabinet.dll"); // TODO: put verf info in trace message here + RexExitOnFailure(hr, "failed to initialize cabinet.dll"); // TODO: put verf info in trace message here } ::ZeroMemory(vrgffFileTable, sizeof(vrgffFileTable)); @@ -123,12 +138,12 @@ extern "C" HRESULT RexExtract( // load the cabinet resource // hResInfo = ::FindResourceExA(NULL, RT_RCDATA, szResource, MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL)); - ExitOnNullWithLastError(hResInfo, hr, "Failed to find resource."); + RexExitOnNullWithLastError(hResInfo, hr, "Failed to find resource."); //hResInfo = ::FindResourceW(NULL, wzResource, /*RT_RCDATA*/MAKEINTRESOURCEW(10)); //ExitOnNullWithLastError(hResInfo, hr, "failed to load resource info"); hRes = ::LoadResource(NULL, hResInfo); - ExitOnNullWithLastError(hRes, hr, "failed to load resource"); + RexExitOnNullWithLastError(hRes, hr, "failed to load resource"); vcbRes = ::SizeofResource(NULL, hResInfo); vpbRes = (const BYTE*)::LockResource(hRes); @@ -140,11 +155,11 @@ extern "C" HRESULT RexExtract( // //if (!::WideCharToMultiByte(CP_ACP, 0, wzResource, -1, vszResource, countof(vszResource), NULL, NULL)) //{ - // ExitOnLastError(hr, "failed to convert cabinet resource name to ASCII: %ls", wzResource); + // RexExitOnLastError(hr, "failed to convert cabinet resource name to ASCII: %ls", wzResource); //} hr = ::StringCchCopyA(vszResource, countof(vszResource), szResource); - ExitOnFailure(hr, "Failed to copy resource name to global."); + RexExitOnFailure(hr, "Failed to copy resource name to global."); // // iterate through files in cabinet extracting them to the callback function @@ -193,7 +208,7 @@ static __callback INT_PTR FAR DIAMONDAPI RexOpen(__in_z char FAR *pszFile, int o if ((oflag != (/*_O_BINARY*/ 0x8000 | /*_O_RDONLY*/ 0x0000)) || (pmode != (_S_IREAD | _S_IWRITE))) { hr = E_OUTOFMEMORY; - ExitOnFailure(hr, "FDI asked for to create a scratch file, which is unusual"); + RexExitOnFailure(hr, "FDI asked for to create a scratch file, which is unusual"); } // find an empty spot in the fake file table @@ -209,7 +224,7 @@ static __callback INT_PTR FAR DIAMONDAPI RexOpen(__in_z char FAR *pszFile, int o if (FILETABLESIZE <= i) { hr = E_OUTOFMEMORY; - ExitOnFailure(hr, "File table exceeded"); + RexExitOnFailure(hr, "File table exceeded"); } if (0 == lstrcmpA(vszResource, pszFile)) @@ -225,7 +240,7 @@ static __callback INT_PTR FAR DIAMONDAPI RexOpen(__in_z char FAR *pszFile, int o hFile = ::CreateFileA(pszFile, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (INVALID_HANDLE_VALUE == hFile) { - ExitWithLastError(hr, "failed to open file: %s", pszFile); + RexExitWithLastError(hr, "failed to open file: %s", pszFile); } vrgffFileTable[i].fUsed = TRUE; @@ -267,7 +282,7 @@ static __callback UINT FAR DIAMONDAPI RexRead(INT_PTR hf, __out_bcount(cb) void if (!::ReadFile(vrgffFileTable[hf].hFile, pv, cb, &cbRead, NULL)) { - ExitWithLastError(hr, "failed to read during cabinet extraction"); + RexExitWithLastError(hr, "failed to read during cabinet extraction"); } } @@ -292,7 +307,7 @@ static __callback UINT FAR DIAMONDAPI RexWrite(INT_PTR hf, __in_bcount(cb) void Assert(vrgffFileTable[hf].hFile && vrgffFileTable[hf].hFile != INVALID_HANDLE_VALUE); if (!::WriteFile(reinterpret_cast(vrgffFileTable[hf].hFile), pv, cb, &cbWrite, NULL)) { - ExitWithLastError(hr, "failed to write during cabinet extraction"); + RexExitWithLastError(hr, "failed to write during cabinet extraction"); } // call the writer callback if defined @@ -333,7 +348,7 @@ static __callback long FAR DIAMONDAPI RexSeek(INT_PTR hf, long dist, int seektyp default : dwMoveMethod = 0; hr = E_UNEXPECTED; - ExitOnFailure(hr, "unexpected seektype in FDISeek(): %d", seektype); + RexExitOnFailure(hr, "unexpected seektype in FDISeek(): %d", seektype); } if (MEMORY_FILE == vrgffFileTable[hf].fftType) @@ -362,7 +377,7 @@ static __callback long FAR DIAMONDAPI RexSeek(INT_PTR hf, long dist, int seektyp lMove = ::SetFilePointer(vrgffFileTable[hf].hFile, dist, NULL, dwMoveMethod); if (0xFFFFFFFF == lMove) { - ExitWithLastError(hr, "failed to move file pointer %d bytes", dist); + RexExitWithLastError(hr, "failed to move file pointer %d bytes", dist); } } @@ -394,7 +409,7 @@ __callback int FAR DIAMONDAPI RexClose(INT_PTR hf) if (!::CloseHandle(vrgffFileTable[hf].hFile)) { - ExitWithLastError(hr, "failed to close file during cabinet extraction"); + RexExitWithLastError(hr, "failed to close file during cabinet extraction"); } vrgffFileTable[hf].hFile = INVALID_HANDLE_VALUE; @@ -440,7 +455,7 @@ static __callback INT_PTR DIAMONDAPI RexCallback(FDINOTIFICATIONTYPE iNotificati sz = static_cast(pFDINotify->psz1); if (!::MultiByteToWideChar(CP_ACP, 0, sz, -1, wz, countof(wz))) { - ExitWithLastError(hr, "failed to convert cabinet file id to unicode: %s", sz); + RexExitWithLastError(hr, "failed to convert cabinet file id to unicode: %s", sz); } if (prcs->pfnProgress) @@ -457,25 +472,25 @@ static __callback INT_PTR DIAMONDAPI RexCallback(FDINOTIFICATIONTYPE iNotificati // get the created date for the resource in the cabinet if (!::DosDateTimeToFileTime(pFDINotify->date, pFDINotify->time, &ft)) { - ExitWithLastError(hr, "failed to get time for resource: %ls", wz); + RexExitWithLastError(hr, "failed to get time for resource: %ls", wz); } WCHAR wzPath[MAX_PATH]; hr = ::StringCchCopyW(wzPath, countof(wzPath), prcs->pwzExtractDir); - ExitOnFailure(hr, "failed to copy extract directory: %ls for file: %ls", prcs->pwzExtractDir, wz); + RexExitOnFailure(hr, "failed to copy extract directory: %ls for file: %ls", prcs->pwzExtractDir, wz); if (L'*' == *prcs->pwzExtract) { hr = ::StringCchCatW(wzPath, countof(wzPath), wz); - ExitOnFailure(hr, "failed to concat onto path: %ls file: %ls", wzPath, wz); + RexExitOnFailure(hr, "failed to concat onto path: %ls file: %ls", wzPath, wz); } else { Assert(*prcs->pwzExtractName); hr = ::StringCchCatW(wzPath, countof(wzPath), prcs->pwzExtractName); - ExitOnFailure(hr, "failed to concat onto path: %ls file: %ls", wzPath, prcs->pwzExtractName); + RexExitOnFailure(hr, "failed to concat onto path: %ls file: %ls", wzPath, prcs->pwzExtractName); } // Quickly chop off the file name part of the path to ensure the path exists @@ -486,7 +501,7 @@ static __callback INT_PTR DIAMONDAPI RexCallback(FDINOTIFICATIONTYPE iNotificati *wzFile = L'\0'; hr = DirEnsureExists(wzPath, NULL); - ExitOnFailure(hr, "failed to ensure directory: %ls", wzPath); + RexExitOnFailure(hr, "failed to ensure directory: %ls", wzPath); hr = S_OK; @@ -505,14 +520,14 @@ static __callback INT_PTR DIAMONDAPI RexCallback(FDINOTIFICATIONTYPE iNotificati if (FILETABLESIZE <= i) { hr = E_OUTOFMEMORY; - ExitOnFailure(hr, "File table exceeded"); + RexExitOnFailure(hr, "File table exceeded"); } // open the file hFile = ::CreateFileW(wzPath, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (INVALID_HANDLE_VALUE == hFile) { - ExitWithLastError(hr, "failed to open file: %ls", wzPath); + RexExitWithLastError(hr, "failed to open file: %ls", wzPath); } vrgffFileTable[i].fUsed = TRUE; @@ -545,7 +560,7 @@ static __callback INT_PTR DIAMONDAPI RexCallback(FDINOTIFICATIONTYPE iNotificati sz = static_cast(pFDINotify->psz1); if (!::MultiByteToWideChar(CP_ACP, 0, sz, -1, wz, countof(wz))) { - ExitWithLastError(hr, "failed to convert cabinet file id to unicode: %s", sz); + RexExitWithLastError(hr, "failed to convert cabinet file id to unicode: %s", sz); } RexClose(pFDINotify->hf); diff --git a/src/dutil/rmutil.cpp b/src/dutil/rmutil.cpp index 75d3e277..95c8c8a4 100644 --- a/src/dutil/rmutil.cpp +++ b/src/dutil/rmutil.cpp @@ -3,6 +3,21 @@ #include "precomp.h" #include + +// Exit macros +#define RmExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_RMUTIL, x, s, __VA_ARGS__) +#define RmExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_RMUTIL, x, s, __VA_ARGS__) +#define RmExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_RMUTIL, x, s, __VA_ARGS__) +#define RmExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_RMUTIL, x, s, __VA_ARGS__) +#define RmExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_RMUTIL, x, s, __VA_ARGS__) +#define RmExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_RMUTIL, x, s, __VA_ARGS__) +#define RmExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_RMUTIL, p, x, e, s, __VA_ARGS__) +#define RmExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_RMUTIL, p, x, s, __VA_ARGS__) +#define RmExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_RMUTIL, p, x, e, s, __VA_ARGS__) +#define RmExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_RMUTIL, p, x, s, __VA_ARGS__) +#define RmExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_RMUTIL, e, x, s, __VA_ARGS__) +#define RmExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_RMUTIL, g, x, s, __VA_ARGS__) + #define ARRAY_GROWTH_SIZE 5 typedef DWORD (WINAPI *PFNRMJOINSESSION)( @@ -80,13 +95,13 @@ extern "C" HRESULT DAPI RmuJoinSession( *ppSession = NULL; pSession = static_cast(MemAlloc(sizeof(RMU_SESSION), TRUE)); - ExitOnNull(pSession, hr, E_OUTOFMEMORY, "Failed to allocate the RMU_SESSION structure."); + RmExitOnNull(pSession, hr, E_OUTOFMEMORY, "Failed to allocate the RMU_SESSION structure."); hr = RmuInitialize(); - ExitOnFailure(hr, "Failed to initialize Restart Manager."); + RmExitOnFailure(hr, "Failed to initialize Restart Manager."); er = vpfnRmJoinSession(&pSession->dwSessionHandle, wzSessionKey); - ExitOnWin32Error(er, hr, "Failed to join Restart Manager session %ls.", wzSessionKey); + RmExitOnWin32Error(er, hr, "Failed to join Restart Manager session %ls.", wzSessionKey); ::InitializeCriticalSection(&pSession->cs); pSession->fInitialized = TRUE; @@ -120,7 +135,7 @@ extern "C" HRESULT DAPI RmuAddFile( // Create or grow the jagged array. hr = StrArrayAllocString(&pSession->rgsczFilenames, &pSession->cFilenames, wzPath, 0); - ExitOnFailure(hr, "Failed to add the filename to the array."); + RmExitOnFailure(hr, "Failed to add the filename to the array."); LExit: ::LeaveCriticalSection(&pSession->cs); @@ -161,29 +176,29 @@ extern "C" HRESULT DAPI RmuAddProcessById( // Adding SeDebugPrivilege in the event that the process targeted by ::OpenProcess() is in a another user context. if (!::OpenProcessToken(::GetCurrentProcess(), TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES, &hToken)) { - ExitWithLastError(hr, "Failed to get process token."); + RmExitWithLastError(hr, "Failed to get process token."); } priv.PrivilegeCount = 1; priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; if (!::LookupPrivilegeValueW(NULL, L"SeDebugPrivilege", &priv.Privileges[0].Luid)) { - ExitWithLastError(hr, "Failed to get debug privilege LUID."); + RmExitWithLastError(hr, "Failed to get debug privilege LUID."); } cbPrevPriv = sizeof(TOKEN_PRIVILEGES); pPrevPriv = static_cast(MemAlloc(cbPrevPriv, TRUE)); - ExitOnNull(pPrevPriv, hr, E_OUTOFMEMORY, "Failed to allocate memory for empty previous privileges."); + RmExitOnNull(pPrevPriv, hr, E_OUTOFMEMORY, "Failed to allocate memory for empty previous privileges."); if (!::AdjustTokenPrivileges(hToken, FALSE, &priv, cbPrevPriv, pPrevPriv, &cbPrevPriv)) { LPVOID pv = MemReAlloc(pPrevPriv, cbPrevPriv, TRUE); - ExitOnNull(pv, hr, E_OUTOFMEMORY, "Failed to allocate memory for previous privileges."); + RmExitOnNull(pv, hr, E_OUTOFMEMORY, "Failed to allocate memory for previous privileges."); pPrevPriv = static_cast(pv); if (!::AdjustTokenPrivileges(hToken, FALSE, &priv, cbPrevPriv, pPrevPriv, &cbPrevPriv)) { - ExitWithLastError(hr, "Failed to get debug privilege LUID."); + RmExitWithLastError(hr, "Failed to get debug privilege LUID."); } } @@ -195,13 +210,13 @@ extern "C" HRESULT DAPI RmuAddProcessById( { if (!::GetProcessTimes(hProcess, &CreationTime, &ExitTime, &KernelTime, &UserTime)) { - ExitWithLastError(hr, "Failed to get the process times for process ID %d.", dwProcessId); + RmExitWithLastError(hr, "Failed to get the process times for process ID %d.", dwProcessId); } ::EnterCriticalSection(&pSession->cs); fLocked = TRUE; hr = RmuApplicationArrayAlloc(&pSession->rgApplications, &pSession->cApplications, dwProcessId, CreationTime); - ExitOnFailure(hr, "Failed to add the application to the array."); + RmExitOnFailure(hr, "Failed to add the application to the array."); } else { @@ -213,7 +228,7 @@ extern "C" HRESULT DAPI RmuAddProcessById( } else { - ExitOnWin32Error(er, hr, "Failed to open the process ID %d.", dwProcessId); + RmExitOnWin32Error(er, hr, "Failed to open the process ID %d.", dwProcessId); } } @@ -258,7 +273,7 @@ extern "C" HRESULT DAPI RmuAddProcessesByName( BOOL fNotFound = FALSE; hr = ProcFindAllIdsFromExeName(wzProcessName, &pdwProcessIds, &cProcessIds); - ExitOnFailure(hr, "Failed to enumerate all the processes by name %ls.", wzProcessName); + RmExitOnFailure(hr, "Failed to enumerate all the processes by name %ls.", wzProcessName); for (DWORD i = 0; i < cProcessIds; ++i) { @@ -270,7 +285,7 @@ extern "C" HRESULT DAPI RmuAddProcessesByName( } else { - ExitOnFailure(hr, "Failed to add process %ls (%d) to the Restart Manager session.", wzProcessName, pdwProcessIds[i]); + RmExitOnFailure(hr, "Failed to add process %ls (%d) to the Restart Manager session.", wzProcessName, pdwProcessIds[i]); } } @@ -303,7 +318,7 @@ extern "C" HRESULT DAPI RmuAddService( ::EnterCriticalSection(&pSession->cs); hr = StrArrayAllocString(&pSession->rgsczServiceNames, &pSession->cServiceNames, wzServiceName, 0); - ExitOnFailure(hr, "Failed to add the service name to the array."); + RmExitOnFailure(hr, "Failed to add the service name to the array."); LExit: ::LeaveCriticalSection(&pSession->cs); @@ -341,7 +356,7 @@ extern "C" HRESULT DAPI RmuRegisterResources( pSession->cServiceNames, pSession->rgsczServiceNames ); - ExitOnWin32Error(er, hr, "Failed to register the resources with the Restart Manager session."); + RmExitOnWin32Error(er, hr, "Failed to register the resources with the Restart Manager session."); // Empty the arrays if registered in case additional resources are added later. ReleaseNullStrArray(pSession->rgsczFilenames, pSession->cFilenames); @@ -373,11 +388,11 @@ extern "C" HRESULT DAPI RmuEndSession( if (!pSession->fStartedSessionHandle) { hr = RmuRegisterResources(pSession); - ExitOnFailure(hr, "Failed to register remaining resources."); + RmExitOnFailure(hr, "Failed to register remaining resources."); } er = vpfnRmEndSession(pSession->dwSessionHandle); - ExitOnWin32Error(er, hr, "Failed to end the Restart Manager session."); + RmExitOnWin32Error(er, hr, "Failed to end the Restart Manager session."); LExit: if (pSession->fInitialized) @@ -404,16 +419,16 @@ static HRESULT RmuInitialize() if (1 == iRef && !vhModule) { hr = LoadSystemLibrary(L"rstrtmgr.dll", &hModule); - ExitOnFailure(hr, "Failed to load the rstrtmgr.dll module."); + RmExitOnFailure(hr, "Failed to load the rstrtmgr.dll module."); vpfnRmJoinSession = reinterpret_cast(::GetProcAddress(hModule, "RmJoinSession")); - ExitOnNullWithLastError(vpfnRmJoinSession, hr, "Failed to get the RmJoinSession procedure from rstrtmgr.dll."); + RmExitOnNullWithLastError(vpfnRmJoinSession, hr, "Failed to get the RmJoinSession procedure from rstrtmgr.dll."); vpfnRmRegisterResources = reinterpret_cast(::GetProcAddress(hModule, "RmRegisterResources")); - ExitOnNullWithLastError(vpfnRmRegisterResources, hr, "Failed to get the RmRegisterResources procedure from rstrtmgr.dll."); + RmExitOnNullWithLastError(vpfnRmRegisterResources, hr, "Failed to get the RmRegisterResources procedure from rstrtmgr.dll."); vpfnRmEndSession = reinterpret_cast(::GetProcAddress(hModule, "RmEndSession")); - ExitOnNullWithLastError(vpfnRmEndSession, hr, "Failed to get the RmEndSession procedure from rstrtmgr.dll."); + RmExitOnNullWithLastError(vpfnRmEndSession, hr, "Failed to get the RmEndSession procedure from rstrtmgr.dll."); vhModule = hModule; } @@ -447,7 +462,7 @@ static HRESULT RmuApplicationArrayAlloc( RM_UNIQUE_PROCESS *pApplication = NULL; hr = MemEnsureArraySize(reinterpret_cast(prgApplications), *pcApplications + 1, sizeof(RM_UNIQUE_PROCESS), ARRAY_GROWTH_SIZE); - ExitOnFailure(hr, "Failed to allocate memory for the application array."); + RmExitOnFailure(hr, "Failed to allocate memory for the application array."); pApplication = static_cast(&(*prgApplications)[*pcApplications]); pApplication->dwProcessId = dwProcessId; @@ -466,7 +481,7 @@ static HRESULT RmuApplicationArrayFree( HRESULT hr = S_OK; hr = MemFree(rgApplications); - ExitOnFailure(hr, "Failed to free memory for the application array."); + RmExitOnFailure(hr, "Failed to free memory for the application array."); LExit: return hr; diff --git a/src/dutil/rssutil.cpp b/src/dutil/rssutil.cpp index db49d954..8f994dfc 100644 --- a/src/dutil/rssutil.cpp +++ b/src/dutil/rssutil.cpp @@ -2,6 +2,21 @@ #include "precomp.h" + +// Exit macros +#define RssExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_RSSUTIL, x, s, __VA_ARGS__) +#define RssExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_RSSUTIL, x, s, __VA_ARGS__) +#define RssExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_RSSUTIL, x, s, __VA_ARGS__) +#define RssExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_RSSUTIL, x, s, __VA_ARGS__) +#define RssExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_RSSUTIL, x, s, __VA_ARGS__) +#define RssExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_RSSUTIL, x, s, __VA_ARGS__) +#define RssExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_RSSUTIL, p, x, e, s, __VA_ARGS__) +#define RssExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_RSSUTIL, p, x, s, __VA_ARGS__) +#define RssExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_RSSUTIL, p, x, e, s, __VA_ARGS__) +#define RssExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_RSSUTIL, p, x, s, __VA_ARGS__) +#define RssExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_RSSUTIL, e, x, s, __VA_ARGS__) +#define RssExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_RSSUTIL, g, x, s, __VA_ARGS__) + static HRESULT ParseRssDocument( __in IXMLDOMDocument *pixd, __out RSS_CHANNEL **ppChannel @@ -68,10 +83,10 @@ extern "C" HRESULT DAPI RssParseFromString( IXMLDOMDocument *pixdRss = NULL; hr = XmlLoadDocument(wzRssString, &pixdRss); - ExitOnFailure(hr, "Failed to load RSS string as XML document."); + RssExitOnFailure(hr, "Failed to load RSS string as XML document."); hr = ParseRssDocument(pixdRss, &pNewChannel); - ExitOnFailure(hr, "Failed to parse RSS document."); + RssExitOnFailure(hr, "Failed to parse RSS document."); *ppChannel = pNewChannel; pNewChannel = NULL; @@ -102,10 +117,10 @@ extern "C" HRESULT DAPI RssParseFromFile( IXMLDOMDocument *pixdRss = NULL; hr = XmlLoadDocumentFromFile(wzRssFile, &pixdRss); - ExitOnFailure(hr, "Failed to load RSS string as XML document."); + RssExitOnFailure(hr, "Failed to load RSS string as XML document."); hr = ParseRssDocument(pixdRss, &pNewChannel); - ExitOnFailure(hr, "Failed to parse RSS document."); + RssExitOnFailure(hr, "Failed to parse RSS document."); *ppChannel = pNewChannel; pNewChannel = NULL; @@ -175,17 +190,17 @@ static HRESULT ParseRssDocument( // Get the document element and start processing channels. // hr = pixd ->get_documentElement(&pRssElement); - ExitOnFailure(hr, "failed get_documentElement in ParseRssDocument"); + RssExitOnFailure(hr, "failed get_documentElement in ParseRssDocument"); hr = pRssElement->get_childNodes(&pChannelNodes); - ExitOnFailure(hr, "Failed to get child nodes of Rss Document element."); + RssExitOnFailure(hr, "Failed to get child nodes of Rss Document element."); while (S_OK == (hr = XmlNextElement(pChannelNodes, &pNode, &bstrNodeName))) { if (0 == lstrcmpW(bstrNodeName, L"channel")) { hr = ParseRssChannel(pNode, &pNewChannel); - ExitOnFailure(hr, "Failed to parse RSS channel."); + RssExitOnFailure(hr, "Failed to parse RSS channel."); } else if (0 == lstrcmpW(bstrNodeName, L"link")) { @@ -242,13 +257,13 @@ static HRESULT ParseRssChannel( // the RSS_CHANNEL structure // hr = XmlSelectNodes(pixnChannel, L"item", &pNodeList); - ExitOnFailure(hr, "Failed to select all RSS items in an RSS channel."); + RssExitOnFailure(hr, "Failed to select all RSS items in an RSS channel."); hr = pNodeList->get_length(&cItems); - ExitOnFailure(hr, "Failed to count the number of RSS items in RSS channel."); + RssExitOnFailure(hr, "Failed to count the number of RSS items in RSS channel."); pNewChannel = static_cast(MemAlloc(sizeof(RSS_CHANNEL) + sizeof(RSS_ITEM) * cItems, TRUE)); - ExitOnNull(pNewChannel, hr, E_OUTOFMEMORY, "Failed to allocate RSS channel structure."); + RssExitOnNull(pNewChannel, hr, E_OUTOFMEMORY, "Failed to allocate RSS channel structure."); pNewChannel->cItems = cItems; @@ -256,7 +271,7 @@ static HRESULT ParseRssChannel( // Process the elements under a channel now. // hr = pixnChannel->get_childNodes(&pNodeList); - ExitOnFailure(hr, "Failed to get child nodes of RSS channel element."); + RssExitOnFailure(hr, "Failed to get child nodes of RSS channel element."); cItems = 0; // reset the counter and use this to walk through the channel items while (S_OK == (hr = XmlNextElement(pNodeList, &pNode, &bstrNodeName))) @@ -264,45 +279,45 @@ static HRESULT ParseRssChannel( if (0 == lstrcmpW(bstrNodeName, L"title")) { hr = XmlGetText(pNode, &bstrNodeValue); - ExitOnFailure(hr, "Failed to get RSS channel title."); + RssExitOnFailure(hr, "Failed to get RSS channel title."); hr = StrAllocString(&pNewChannel->wzTitle, bstrNodeValue, 0); - ExitOnFailure(hr, "Failed to allocate RSS channel title."); + RssExitOnFailure(hr, "Failed to allocate RSS channel title."); } else if (0 == lstrcmpW(bstrNodeName, L"link")) { hr = XmlGetText(pNode, &bstrNodeValue); - ExitOnFailure(hr, "Failed to get RSS channel link."); + RssExitOnFailure(hr, "Failed to get RSS channel link."); hr = StrAllocString(&pNewChannel->wzLink, bstrNodeValue, 0); - ExitOnFailure(hr, "Failed to allocate RSS channel link."); + RssExitOnFailure(hr, "Failed to allocate RSS channel link."); } else if (0 == lstrcmpW(bstrNodeName, L"description")) { hr = XmlGetText(pNode, &bstrNodeValue); - ExitOnFailure(hr, "Failed to get RSS channel description."); + RssExitOnFailure(hr, "Failed to get RSS channel description."); hr = StrAllocString(&pNewChannel->wzDescription, bstrNodeValue, 0); - ExitOnFailure(hr, "Failed to allocate RSS channel description."); + RssExitOnFailure(hr, "Failed to allocate RSS channel description."); } else if (0 == lstrcmpW(bstrNodeName, L"ttl")) { hr = XmlGetText(pNode, &bstrNodeValue); - ExitOnFailure(hr, "Failed to get RSS channel description."); + RssExitOnFailure(hr, "Failed to get RSS channel description."); pNewChannel->dwTimeToLive = (DWORD)wcstoul(bstrNodeValue, NULL, 10); } else if (0 == lstrcmpW(bstrNodeName, L"item")) { hr = ParseRssItem(pNode, cItems, pNewChannel); - ExitOnFailure(hr, "Failed to parse RSS item."); + RssExitOnFailure(hr, "Failed to parse RSS item."); ++cItems; } else { hr = ParseRssUnknownElement(pNode, &pNewChannel->pUnknownElements); - ExitOnFailure(hr, "Failed to parse unknown RSS channel element: %ls", bstrNodeName); + RssExitOnFailure(hr, "Failed to parse unknown RSS channel element: %ls", bstrNodeName); } ReleaseNullBSTR(bstrNodeValue); @@ -349,7 +364,7 @@ static HRESULT ParseRssItem( if (pChannel->cItems <= cItem) { hr = E_UNEXPECTED; - ExitOnFailure(hr, "Unexpected number of items parsed."); + RssExitOnFailure(hr, "Unexpected number of items parsed."); } pItem = pChannel->rgItems + cItem; @@ -358,71 +373,71 @@ static HRESULT ParseRssItem( // Process the elements under an item now. // hr = pixnItem->get_childNodes(&pNodeList); - ExitOnFailure(hr, "Failed to get child nodes of RSS item element."); + RssExitOnFailure(hr, "Failed to get child nodes of RSS item element."); while (S_OK == (hr = XmlNextElement(pNodeList, &pNode, &bstrNodeName))) { if (0 == lstrcmpW(bstrNodeName, L"title")) { hr = XmlGetText(pNode, &bstrNodeValue); - ExitOnFailure(hr, "Failed to get RSS channel title."); + RssExitOnFailure(hr, "Failed to get RSS channel title."); hr = StrAllocString(&pItem->wzTitle, bstrNodeValue, 0); - ExitOnFailure(hr, "Failed to allocate RSS item title."); + RssExitOnFailure(hr, "Failed to allocate RSS item title."); } else if (0 == lstrcmpW(bstrNodeName, L"link")) { hr = XmlGetText(pNode, &bstrNodeValue); - ExitOnFailure(hr, "Failed to get RSS channel link."); + RssExitOnFailure(hr, "Failed to get RSS channel link."); hr = StrAllocString(&pItem->wzLink, bstrNodeValue, 0); - ExitOnFailure(hr, "Failed to allocate RSS item link."); + RssExitOnFailure(hr, "Failed to allocate RSS item link."); } else if (0 == lstrcmpW(bstrNodeName, L"description")) { hr = XmlGetText(pNode, &bstrNodeValue); - ExitOnFailure(hr, "Failed to get RSS item description."); + RssExitOnFailure(hr, "Failed to get RSS item description."); hr = StrAllocString(&pItem->wzDescription, bstrNodeValue, 0); - ExitOnFailure(hr, "Failed to allocate RSS item description."); + RssExitOnFailure(hr, "Failed to allocate RSS item description."); } else if (0 == lstrcmpW(bstrNodeName, L"guid")) { hr = XmlGetText(pNode, &bstrNodeValue); - ExitOnFailure(hr, "Failed to get RSS item guid."); + RssExitOnFailure(hr, "Failed to get RSS item guid."); hr = StrAllocString(&pItem->wzGuid, bstrNodeValue, 0); - ExitOnFailure(hr, "Failed to allocate RSS item guid."); + RssExitOnFailure(hr, "Failed to allocate RSS item guid."); } else if (0 == lstrcmpW(bstrNodeName, L"pubDate")) { hr = XmlGetText(pNode, &bstrNodeValue); - ExitOnFailure(hr, "Failed to get RSS item guid."); + RssExitOnFailure(hr, "Failed to get RSS item guid."); hr = TimeFromString(bstrNodeValue, &pItem->ftPublished); - ExitOnFailure(hr, "Failed to convert RSS item time."); + RssExitOnFailure(hr, "Failed to convert RSS item time."); } else if (0 == lstrcmpW(bstrNodeName, L"enclosure")) { hr = XmlGetAttribute(pNode, L"url", &bstrNodeValue); - ExitOnFailure(hr, "Failed to get RSS item enclosure url."); + RssExitOnFailure(hr, "Failed to get RSS item enclosure url."); hr = StrAllocString(&pItem->wzEnclosureUrl, bstrNodeValue, 0); - ExitOnFailure(hr, "Failed to allocate RSS item enclosure url."); + RssExitOnFailure(hr, "Failed to allocate RSS item enclosure url."); ReleaseNullBSTR(bstrNodeValue); hr = XmlGetAttributeNumber(pNode, L"length", &pItem->dwEnclosureSize); - ExitOnFailure(hr, "Failed to get RSS item enclosure length."); + RssExitOnFailure(hr, "Failed to get RSS item enclosure length."); hr = XmlGetAttribute(pNode, L"type", &bstrNodeValue); - ExitOnFailure(hr, "Failed to get RSS item enclosure type."); + RssExitOnFailure(hr, "Failed to get RSS item enclosure type."); hr = StrAllocString(&pItem->wzEnclosureType, bstrNodeValue, 0); - ExitOnFailure(hr, "Failed to allocate RSS item enclosure type."); + RssExitOnFailure(hr, "Failed to allocate RSS item enclosure type."); } else { hr = ParseRssUnknownElement(pNode, &pItem->pUnknownElements); - ExitOnFailure(hr, "Failed to parse unknown RSS item element: %ls", bstrNodeName); + RssExitOnFailure(hr, "Failed to parse unknown RSS item element: %ls", bstrNodeName); } ReleaseNullBSTR(bstrNodeValue); @@ -460,39 +475,39 @@ static HRESULT ParseRssUnknownElement( RSS_UNKNOWN_ELEMENT* pNewUnknownElement; pNewUnknownElement = static_cast(MemAlloc(sizeof(RSS_UNKNOWN_ELEMENT), TRUE)); - ExitOnNull(pNewUnknownElement, hr, E_OUTOFMEMORY, "Failed to allocate unknown element."); + RssExitOnNull(pNewUnknownElement, hr, E_OUTOFMEMORY, "Failed to allocate unknown element."); hr = pNode->get_namespaceURI(&bstrNodeNamespace); if (S_OK == hr) { hr = StrAllocString(&pNewUnknownElement->wzNamespace, bstrNodeNamespace, 0); - ExitOnFailure(hr, "Failed to allocate RSS unknown element namespace."); + RssExitOnFailure(hr, "Failed to allocate RSS unknown element namespace."); } else if (S_FALSE == hr) { hr = S_OK; } - ExitOnFailure(hr, "Failed to get unknown element namespace."); + RssExitOnFailure(hr, "Failed to get unknown element namespace."); hr = pNode->get_baseName(&bstrNodeName); - ExitOnFailure(hr, "Failed to get unknown element name."); + RssExitOnFailure(hr, "Failed to get unknown element name."); hr = StrAllocString(&pNewUnknownElement->wzElement, bstrNodeName, 0); - ExitOnFailure(hr, "Failed to allocate RSS unknown element name."); + RssExitOnFailure(hr, "Failed to allocate RSS unknown element name."); hr = XmlGetText(pNode, &bstrNodeValue); - ExitOnFailure(hr, "Failed to get unknown element value."); + RssExitOnFailure(hr, "Failed to get unknown element value."); hr = StrAllocString(&pNewUnknownElement->wzValue, bstrNodeValue, 0); - ExitOnFailure(hr, "Failed to allocate RSS unknown element value."); + RssExitOnFailure(hr, "Failed to allocate RSS unknown element value."); hr = pNode->get_attributes(&pixnnmAttributes); - ExitOnFailure(hr, "Failed get attributes on RSS unknown element."); + RssExitOnFailure(hr, "Failed get attributes on RSS unknown element."); while (S_OK == (hr = pixnnmAttributes->nextNode(&pixnAttribute))) { hr = ParseRssUnknownAttribute(pixnAttribute, &pNewUnknownElement->pAttributes); - ExitOnFailure(hr, "Failed to parse attribute on RSS unknown element."); + RssExitOnFailure(hr, "Failed to parse attribute on RSS unknown element."); ReleaseNullObject(pixnAttribute); } @@ -501,7 +516,7 @@ static HRESULT ParseRssUnknownElement( { hr = S_OK; } - ExitOnFailure(hr, "Failed to enumerate all attributes on RSS unknown element."); + RssExitOnFailure(hr, "Failed to enumerate all attributes on RSS unknown element."); RSS_UNKNOWN_ELEMENT** ppTail = ppUnknownElement; while (*ppTail) @@ -543,31 +558,31 @@ static HRESULT ParseRssUnknownAttribute( RSS_UNKNOWN_ATTRIBUTE* pNewUnknownAttribute; pNewUnknownAttribute = static_cast(MemAlloc(sizeof(RSS_UNKNOWN_ATTRIBUTE), TRUE)); - ExitOnNull(pNewUnknownAttribute, hr, E_OUTOFMEMORY, "Failed to allocate unknown attribute."); + RssExitOnNull(pNewUnknownAttribute, hr, E_OUTOFMEMORY, "Failed to allocate unknown attribute."); hr = pNode->get_namespaceURI(&bstrNodeNamespace); if (S_OK == hr) { hr = StrAllocString(&pNewUnknownAttribute->wzNamespace, bstrNodeNamespace, 0); - ExitOnFailure(hr, "Failed to allocate RSS unknown attribute namespace."); + RssExitOnFailure(hr, "Failed to allocate RSS unknown attribute namespace."); } else if (S_FALSE == hr) { hr = S_OK; } - ExitOnFailure(hr, "Failed to get unknown attribute namespace."); + RssExitOnFailure(hr, "Failed to get unknown attribute namespace."); hr = pNode->get_baseName(&bstrNodeName); - ExitOnFailure(hr, "Failed to get unknown attribute name."); + RssExitOnFailure(hr, "Failed to get unknown attribute name."); hr = StrAllocString(&pNewUnknownAttribute->wzAttribute, bstrNodeName, 0); - ExitOnFailure(hr, "Failed to allocate RSS unknown attribute name."); + RssExitOnFailure(hr, "Failed to allocate RSS unknown attribute name."); hr = XmlGetText(pNode, &bstrNodeValue); - ExitOnFailure(hr, "Failed to get unknown attribute value."); + RssExitOnFailure(hr, "Failed to get unknown attribute value."); hr = StrAllocString(&pNewUnknownAttribute->wzValue, bstrNodeValue, 0); - ExitOnFailure(hr, "Failed to allocate RSS unknown attribute value."); + RssExitOnFailure(hr, "Failed to allocate RSS unknown attribute value."); RSS_UNKNOWN_ATTRIBUTE** ppTail = ppUnknownAttribute; while (*ppTail) diff --git a/src/dutil/shelutil.cpp b/src/dutil/shelutil.cpp index a69c9eaa..2eb9a52a 100644 --- a/src/dutil/shelutil.cpp +++ b/src/dutil/shelutil.cpp @@ -2,6 +2,21 @@ #include "precomp.h" + +// Exit macros +#define ShelExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_SHELUTIL, x, s, __VA_ARGS__) +#define ShelExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_SHELUTIL, x, s, __VA_ARGS__) +#define ShelExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_SHELUTIL, x, s, __VA_ARGS__) +#define ShelExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_SHELUTIL, x, s, __VA_ARGS__) +#define ShelExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_SHELUTIL, x, s, __VA_ARGS__) +#define ShelExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_SHELUTIL, x, s, __VA_ARGS__) +#define ShelExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_SHELUTIL, p, x, e, s, __VA_ARGS__) +#define ShelExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_SHELUTIL, p, x, s, __VA_ARGS__) +#define ShelExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_SHELUTIL, p, x, e, s, __VA_ARGS__) +#define ShelExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_SHELUTIL, p, x, s, __VA_ARGS__) +#define ShelExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_SHELUTIL, e, x, s, __VA_ARGS__) +#define ShelExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_SHELUTIL, g, x, s, __VA_ARGS__) + static PFN_SHELLEXECUTEEXW vpfnShellExecuteExW = ::ShellExecuteExW; static HRESULT GetDesktopShellView( @@ -55,7 +70,7 @@ extern "C" HRESULT DAPI ShelExec( if (!vpfnShellExecuteExW(&shExecInfo)) { - ExitWithLastError(hr, "ShellExecEx failed with return code: %d", Dutil_er); + ShelExitWithLastError(hr, "ShellExecEx failed with return code: %d", Dutil_er); } if (phProcess) @@ -93,44 +108,44 @@ extern "C" HRESULT DAPI ShelExecUnelevated( IShellDispatch2* psd = NULL; bstrTargetPath = ::SysAllocString(wzTargetPath); - ExitOnNull(bstrTargetPath, hr, E_OUTOFMEMORY, "Failed to allocate target path BSTR."); + ShelExitOnNull(bstrTargetPath, hr, E_OUTOFMEMORY, "Failed to allocate target path BSTR."); if (wzParameters && *wzParameters) { vtParameters.vt = VT_BSTR; vtParameters.bstrVal = ::SysAllocString(wzParameters); - ExitOnNull(bstrTargetPath, hr, E_OUTOFMEMORY, "Failed to allocate parameters BSTR."); + ShelExitOnNull(bstrTargetPath, hr, E_OUTOFMEMORY, "Failed to allocate parameters BSTR."); } if (wzVerb && *wzVerb) { vtVerb.vt = VT_BSTR; vtVerb.bstrVal = ::SysAllocString(wzVerb); - ExitOnNull(bstrTargetPath, hr, E_OUTOFMEMORY, "Failed to allocate verb BSTR."); + ShelExitOnNull(bstrTargetPath, hr, E_OUTOFMEMORY, "Failed to allocate verb BSTR."); } if (wzWorkingDirectory && *wzWorkingDirectory) { vtWorkingDirectory.vt = VT_BSTR; vtWorkingDirectory.bstrVal = ::SysAllocString(wzWorkingDirectory); - ExitOnNull(bstrTargetPath, hr, E_OUTOFMEMORY, "Failed to allocate working directory BSTR."); + ShelExitOnNull(bstrTargetPath, hr, E_OUTOFMEMORY, "Failed to allocate working directory BSTR."); } vtShow.vt = VT_INT; vtShow.intVal = nShowCmd; hr = GetDesktopShellView(IID_PPV_ARGS(&psv)); - ExitOnFailure(hr, "Failed to get desktop shell view."); + ShelExitOnFailure(hr, "Failed to get desktop shell view."); hr = GetShellDispatchFromView(psv, IID_PPV_ARGS(&psd)); - ExitOnFailure(hr, "Failed to get shell dispatch from view."); + ShelExitOnFailure(hr, "Failed to get shell dispatch from view."); hr = psd->ShellExecute(bstrTargetPath, vtParameters, vtWorkingDirectory, vtVerb, vtShow); if (S_FALSE == hr) { hr = HRESULT_FROM_WIN32(ERROR_CANCELLED); } - ExitOnRootFailure(hr, "Failed to launch unelevate executable: %ls", bstrTargetPath); + ShelExitOnRootFailure(hr, "Failed to launch unelevate executable: %ls", bstrTargetPath); LExit: ReleaseObject(psd); @@ -157,13 +172,13 @@ extern "C" HRESULT DAPI ShelGetFolder( WCHAR wzPath[MAX_PATH]; hr = ::SHGetFolderPathW(NULL, csidlFolder | CSIDL_FLAG_CREATE, NULL, SHGFP_TYPE_CURRENT, wzPath); - ExitOnFailure(hr, "Failed to get folder path for CSIDL: %d", csidlFolder); + ShelExitOnFailure(hr, "Failed to get folder path for CSIDL: %d", csidlFolder); hr = StrAllocString(psczFolderPath, wzPath, 0); - ExitOnFailure(hr, "Failed to copy shell folder path: %ls", wzPath); + ShelExitOnFailure(hr, "Failed to copy shell folder path: %ls", wzPath); hr = PathBackslashTerminate(psczFolderPath); - ExitOnFailure(hr, "Failed to backslash terminate shell folder path: %ls", *psczFolderPath); + ShelExitOnFailure(hr, "Failed to backslash terminate shell folder path: %ls", *psczFolderPath); LExit: return hr; @@ -206,19 +221,19 @@ extern "C" HRESULT DAPI ShelGetKnownFolder( TraceError(hr, "Failed to load shell32.dll"); ExitFunction1(hr = E_NOTIMPL); } - ExitOnFailure(hr, "Failed to load shell32.dll."); + ShelExitOnFailure(hr, "Failed to load shell32.dll."); pfn = reinterpret_cast(::GetProcAddress(hShell32Dll, "SHGetKnownFolderPath")); - ExitOnNull(pfn, hr, E_NOTIMPL, "Failed to find SHGetKnownFolderPath entry point."); + ShelExitOnNull(pfn, hr, E_NOTIMPL, "Failed to find SHGetKnownFolderPath entry point."); hr = pfn(rfidFolder, KF_FLAG_CREATE, NULL, &pwzPath); - ExitOnFailure(hr, "Failed to get known folder path."); + ShelExitOnFailure(hr, "Failed to get known folder path."); hr = StrAllocString(psczFolderPath, pwzPath, 0); - ExitOnFailure(hr, "Failed to copy shell folder path: %ls", pwzPath); + ShelExitOnFailure(hr, "Failed to copy shell folder path: %ls", pwzPath); hr = PathBackslashTerminate(psczFolderPath); - ExitOnFailure(hr, "Failed to backslash terminate shell folder path: %ls", *psczFolderPath); + ShelExitOnFailure(hr, "Failed to backslash terminate shell folder path: %ls", *psczFolderPath); LExit: if (pwzPath) @@ -255,32 +270,32 @@ static HRESULT GetDesktopShellView( // desktop web browser and then grabs its view // returns IShellView, IFolderView and related interfaces hr = ::CoCreateInstance(CLSID_ShellWindows, NULL, CLSCTX_LOCAL_SERVER, IID_PPV_ARGS(&psw)); - ExitOnFailure(hr, "Failed to get shell view."); + ShelExitOnFailure(hr, "Failed to get shell view."); hr = psw->FindWindowSW(&vEmpty, &vEmpty, SWC_DESKTOP, (long*)&hwnd, SWFO_NEEDDISPATCH, &pdisp); if (S_OK == hr) { hr = IUnknown_QueryService(pdisp, SID_STopLevelBrowser, IID_PPV_ARGS(&psb)); - ExitOnFailure(hr, "Failed to get desktop window."); + ShelExitOnFailure(hr, "Failed to get desktop window."); hr = psb->QueryActiveShellView(&psv); - ExitOnFailure(hr, "Failed to get active shell view."); + ShelExitOnFailure(hr, "Failed to get active shell view."); hr = psv->QueryInterface(riid, ppv); - ExitOnFailure(hr, "Failed to query for the desktop shell view."); + ShelExitOnFailure(hr, "Failed to query for the desktop shell view."); } else if (S_FALSE == hr) { //Windows XP hr = SHGetDesktopFolder(&psf); - ExitOnFailure(hr, "Failed to get desktop folder."); + ShelExitOnFailure(hr, "Failed to get desktop folder."); hr = psf->CreateViewObject(NULL, IID_IShellView, ppv); - ExitOnFailure(hr, "Failed to query for the desktop shell view."); + ShelExitOnFailure(hr, "Failed to query for the desktop shell view."); } else { - ExitOnFailure(hr, "Failed to get desktop window."); + ShelExitOnFailure(hr, "Failed to get desktop window."); } LExit: @@ -307,16 +322,16 @@ static HRESULT GetShellDispatchFromView( // From a shell view object, gets its automation interface and from that get the shell // application object that implements IShellDispatch2 and related interfaces. hr = psv->GetItemObject(SVGIO_BACKGROUND, IID_PPV_ARGS(&pdispBackground)); - ExitOnFailure(hr, "Failed to get the automation interface for shell."); + ShelExitOnFailure(hr, "Failed to get the automation interface for shell."); hr = pdispBackground->QueryInterface(IID_PPV_ARGS(&psfvd)); - ExitOnFailure(hr, "Failed to get shell folder view dual."); + ShelExitOnFailure(hr, "Failed to get shell folder view dual."); hr = psfvd->get_Application(&pdisp); - ExitOnFailure(hr, "Failed to application object."); + ShelExitOnFailure(hr, "Failed to application object."); hr = pdisp->QueryInterface(riid, ppv); - ExitOnFailure(hr, "Failed to get IShellDispatch2."); + ShelExitOnFailure(hr, "Failed to get IShellDispatch2."); LExit: ReleaseObject(pdisp); diff --git a/src/dutil/sqlutil.cpp b/src/dutil/sqlutil.cpp index 099c6ae9..63ee80ac 100644 --- a/src/dutil/sqlutil.cpp +++ b/src/dutil/sqlutil.cpp @@ -9,6 +9,21 @@ #define DBINITCONSTANTS #include "sqlutil.h" + +// Exit macros +#define SqlExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_SQLUTIL, x, s, __VA_ARGS__) +#define SqlExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_SQLUTIL, x, s, __VA_ARGS__) +#define SqlExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_SQLUTIL, x, s, __VA_ARGS__) +#define SqlExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_SQLUTIL, x, s, __VA_ARGS__) +#define SqlExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_SQLUTIL, x, s, __VA_ARGS__) +#define SqlExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_SQLUTIL, x, s, __VA_ARGS__) +#define SqlExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_SQLUTIL, p, x, e, s, __VA_ARGS__) +#define SqlExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_SQLUTIL, p, x, s, __VA_ARGS__) +#define SqlExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_SQLUTIL, p, x, e, s, __VA_ARGS__) +#define SqlExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_SQLUTIL, p, x, s, __VA_ARGS__) +#define SqlExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_SQLUTIL, e, x, s, __VA_ARGS__) +#define SqlExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_SQLUTIL, g, x, s, __VA_ARGS__) + // private prototypes static HRESULT FileSpecToString( __in const SQL_FILESPEC* psf, @@ -54,7 +69,7 @@ extern "C" HRESULT DAPI SqlConnectDatabase( //obtain access to the SQLOLEDB provider hr = ::CoCreateInstance(CLSID_SQLOLEDB, NULL, CLSCTX_INPROC_SERVER, IID_IDBInitialize, (LPVOID*)&pidbInitialize); - ExitOnFailure(hr, "failed to create IID_IDBInitialize object"); + SqlExitOnFailure(hr, "failed to create IID_IDBInitialize object"); // if there is an instance if (wzInstance && *wzInstance) @@ -65,7 +80,7 @@ extern "C" HRESULT DAPI SqlConnectDatabase( { hr = StrAllocString(&pwzServerInstance, wzServer, 0); } - ExitOnFailure(hr, "failed to allocate memory for the server instance"); + SqlExitOnFailure(hr, "failed to allocate memory for the server instance"); // server[\instance] rgdbpInit[cProperties].dwPropertyID = DBPROP_INIT_DATASOURCE; @@ -124,13 +139,13 @@ extern "C" HRESULT DAPI SqlConnectDatabase( // create and set the property set hr = pidbInitialize->QueryInterface(IID_IDBProperties, (LPVOID*)&pidbProperties); - ExitOnFailure(hr, "failed to get IID_IDBProperties object"); + SqlExitOnFailure(hr, "failed to get IID_IDBProperties object"); hr = pidbProperties->SetProperties(1, rgdbpsetInit); - ExitOnFailure(hr, "failed to set properties"); + SqlExitOnFailure(hr, "failed to set properties"); //initialize connection to datasource hr = pidbInitialize->Initialize(); - ExitOnFailure(hr, "failed to initialize connection to database: %ls", wzDatabase); + SqlExitOnFailure(hr, "failed to initialize connection to database: %ls", wzDatabase); hr = pidbInitialize->QueryInterface(IID_IDBCreateSession, (LPVOID*)ppidbSession); @@ -163,10 +178,10 @@ extern "C" HRESULT DAPI SqlStartTransaction( HRESULT hr = S_OK; hr = pidbSession->CreateSession(NULL, IID_IDBCreateCommand, (IUnknown**)ppidbCommand); - ExitOnFailure(hr, "unable to create command from session"); + SqlExitOnFailure(hr, "unable to create command from session"); hr = (*ppidbCommand)->QueryInterface(IID_ITransactionLocal, (LPVOID*)ppit); - ExitOnFailure(hr, "Unable to QueryInterface session to get ITransactionLocal"); + SqlExitOnFailure(hr, "Unable to QueryInterface session to get ITransactionLocal"); hr = ((ITransactionLocal*)*ppit)->StartTransaction(ISOLATIONLEVEL_SERIALIZABLE, 0, NULL, NULL); @@ -192,12 +207,12 @@ extern "C" HRESULT DAPI SqlEndTransaction( if (fCommit) { hr = pit->Commit(FALSE, XACTTC_SYNC, 0); - ExitOnFailure(hr, "commit of transaction failed"); + SqlExitOnFailure(hr, "commit of transaction failed"); } else { hr = pit->Abort(NULL, FALSE, FALSE); - ExitOnFailure(hr, "abort of transaction failed"); + SqlExitOnFailure(hr, "abort of transaction failed"); } LExit: @@ -231,7 +246,7 @@ extern "C" HRESULT DAPI SqlDatabaseExists( IDBCreateSession* pidbSession = NULL; hr = SqlConnectDatabase(wzServer, wzInstance, L"master", fIntegratedAuth, wzUser, wzPassword, &pidbSession); - ExitOnFailure(hr, "failed to connect to 'master' database on server %ls", wzServer); + SqlExitOnFailure(hr, "failed to connect to 'master' database on server %ls", wzServer); hr = SqlSessionDatabaseExists(pidbSession, wzDatabase, pbstrErrorDescription); @@ -271,17 +286,17 @@ extern "C" HRESULT DAPI SqlSessionDatabaseExists( // query to see if the database exists // hr = StrAllocFormatted(&pwzQuery, L"SELECT name FROM sysdatabases WHERE name='%s'", wzDatabase); - ExitOnFailure(hr, "failed to allocate query string to ensure database exists"); + SqlExitOnFailure(hr, "failed to allocate query string to ensure database exists"); hr = SqlSessionExecuteQuery(pidbSession, pwzQuery, &pirs, NULL, pbstrErrorDescription); - ExitOnFailure(hr, "failed to get database list from 'master' database"); + SqlExitOnFailure(hr, "failed to get database list from 'master' database"); Assert(pirs); // // check to see if the database was returned // hr = pirs->GetNextRows(DB_NULL_HCHAPTER, 0, 1, &cRows, &prow); - ExitOnFailure(hr, "failed to get row with database name"); + SqlExitOnFailure(hr, "failed to get row with database name"); // succeeded but no database if ((DB_S_ENDOFROWSET == hr) || (0 == cRows)) @@ -324,10 +339,10 @@ extern "C" HRESULT DAPI SqlDatabaseEnsureExists( // connect to the master database to create the new database // hr = SqlConnectDatabase(wzServer, wzInstance, L"master", fIntegratedAuth, wzUser, wzPassword, &pidbSession); - ExitOnFailure(hr, "failed to connect to 'master' database on server %ls", wzServer); + SqlExitOnFailure(hr, "failed to connect to 'master' database on server %ls", wzServer); hr = SqlSessionDatabaseEnsureExists(pidbSession, wzDatabase, psfDatabase, psfLog, pbstrErrorDescription); - ExitOnFailure(hr, "failed to create database: %ls", wzDatabase); + SqlExitOnFailure(hr, "failed to create database: %ls", wzDatabase); Assert(S_OK == hr); LExit: @@ -355,12 +370,12 @@ extern "C" HRESULT DAPI SqlSessionDatabaseEnsureExists( HRESULT hr = S_OK; hr = SqlSessionDatabaseExists(pidbSession, wzDatabase, pbstrErrorDescription); - ExitOnFailure(hr, "failed to determine if exists, database: %ls", wzDatabase); + SqlExitOnFailure(hr, "failed to determine if exists, database: %ls", wzDatabase); if (S_FALSE == hr) { hr = SqlSessionCreateDatabase(pidbSession, wzDatabase, psfDatabase, psfLog, pbstrErrorDescription); - ExitOnFailure(hr, "failed to create database: %1", wzDatabase); + SqlExitOnFailure(hr, "failed to create database: %ls", wzDatabase); } // else database already exists, return S_FALSE @@ -398,10 +413,10 @@ extern "C" HRESULT DAPI SqlCreateDatabase( // connect to the master database to create the new database // hr = SqlConnectDatabase(wzServer, wzInstance, L"master", fIntegratedAuth, wzUser, wzPassword, &pidbSession); - ExitOnFailure(hr, "failed to connect to 'master' database on server %ls", wzServer); + SqlExitOnFailure(hr, "failed to connect to 'master' database on server %ls", wzServer); hr = SqlSessionCreateDatabase(pidbSession, wzDatabase, psfDatabase, psfLog, pbstrErrorDescription); - ExitOnFailure(hr, "failed to create database: %ls", wzDatabase); + SqlExitOnFailure(hr, "failed to create database: %ls", wzDatabase); Assert(S_OK == hr); LExit: @@ -433,23 +448,23 @@ extern "C" HRESULT DAPI SqlSessionCreateDatabase( if (psfDatabase) { hr = FileSpecToString(psfDatabase, &pwzDbFile); - ExitOnFailure(hr, "failed to convert db filespec to string"); + SqlExitOnFailure(hr, "failed to convert db filespec to string"); } if (psfLog) { hr = FileSpecToString(psfLog, &pwzLogFile); - ExitOnFailure(hr, "failed to convert log filespec to string"); + SqlExitOnFailure(hr, "failed to convert log filespec to string"); } hr = EscapeSqlIdentifier(wzDatabase, &pwzDatabaseEscaped); - ExitOnFailure(hr, "failed to escape database string"); + SqlExitOnFailure(hr, "failed to escape database string"); hr = StrAllocFormatted(&pwzQuery, L"CREATE DATABASE %s %s%s %s%s", pwzDatabaseEscaped, pwzDbFile ? L"ON " : L"", pwzDbFile ? pwzDbFile : L"", pwzLogFile ? L"LOG ON " : L"", pwzLogFile ? pwzLogFile : L""); - ExitOnFailure(hr, "failed to allocate query to create database: %ls", pwzDatabaseEscaped); + SqlExitOnFailure(hr, "failed to allocate query to create database: %ls", pwzDatabaseEscaped); hr = SqlSessionExecuteQuery(pidbSession, pwzQuery, NULL, NULL, pbstrErrorDescription); - ExitOnFailure(hr, "failed to create database: %ls, Query: %ls", pwzDatabaseEscaped, pwzQuery); + SqlExitOnFailure(hr, "failed to create database: %ls, Query: %ls", pwzDatabaseEscaped, pwzQuery); LExit: ReleaseStr(pwzQuery); @@ -486,7 +501,7 @@ extern "C" HRESULT DAPI SqlDropDatabase( // connect to the master database to search for wzDatabase // hr = SqlConnectDatabase(wzServer, wzInstance, L"master", fIntegratedAuth, wzUser, wzPassword, &pidbSession); - ExitOnFailure(hr, "Failed to connect to 'master' database"); + SqlExitOnFailure(hr, "Failed to connect to 'master' database"); hr = SqlSessionDropDatabase(pidbSession, wzDatabase, pbstrErrorDescription); @@ -515,18 +530,18 @@ extern "C" HRESULT DAPI SqlSessionDropDatabase( LPWSTR pwzDatabaseEscaped = NULL; hr = SqlSessionDatabaseExists(pidbSession, wzDatabase, pbstrErrorDescription); - ExitOnFailure(hr, "failed to determine if exists, database: %ls", wzDatabase); + SqlExitOnFailure(hr, "failed to determine if exists, database: %ls", wzDatabase); hr = EscapeSqlIdentifier(wzDatabase, &pwzDatabaseEscaped); - ExitOnFailure(hr, "failed to escape database string"); + SqlExitOnFailure(hr, "failed to escape database string"); if (S_OK == hr) { hr = StrAllocFormatted(&pwzQuery, L"DROP DATABASE %s", pwzDatabaseEscaped); - ExitOnFailure(hr, "failed to allocate query to drop database: %ls", pwzDatabaseEscaped); + SqlExitOnFailure(hr, "failed to allocate query to drop database: %ls", pwzDatabaseEscaped); hr = SqlSessionExecuteQuery(pidbSession, pwzQuery, NULL, NULL, pbstrErrorDescription); - ExitOnFailure(hr, "Failed to drop database"); + SqlExitOnFailure(hr, "Failed to drop database"); } LExit: @@ -567,23 +582,23 @@ extern "C" HRESULT DAPI SqlSessionExecuteQuery( // create the command // hr = pidbSession->CreateSession(NULL, IID_IDBCreateCommand, (IUnknown**)&pidbCommand); - ExitOnFailure(hr, "failed to create database session"); + SqlExitOnFailure(hr, "failed to create database session"); hr = pidbCommand->CreateCommand(NULL, IID_ICommand, (IUnknown**)&picmd); - ExitOnFailure(hr, "failed to create command to execute session"); + SqlExitOnFailure(hr, "failed to create command to execute session"); // // set the sql text into the command // hr = picmd->QueryInterface(IID_ICommandText, (LPVOID*)&picmdText); - ExitOnFailure(hr, "failed to get command text object for command"); + SqlExitOnFailure(hr, "failed to get command text object for command"); hr = picmdText->SetCommandText(DBGUID_DEFAULT , wzSql); - ExitOnFailure(hr, "failed to set SQL string: %ls", wzSql); + SqlExitOnFailure(hr, "failed to set SQL string: %ls", wzSql); // // execute the command // hr = picmd->Execute(NULL, (ppirs) ? IID_IRowset : IID_NULL, NULL, &cRows, reinterpret_cast(ppirs)); - ExitOnFailure(hr, "failed to execute SQL string: %ls", wzSql); + SqlExitOnFailure(hr, "failed to execute SQL string: %ls", wzSql); if (DB_S_ERRORSOCCURRED == hr) { @@ -642,21 +657,21 @@ extern "C" HRESULT DAPI SqlCommandExecuteQuery( // create the command // hr = pidbCommand->CreateCommand(NULL, IID_ICommand, (IUnknown**)&picmd); - ExitOnFailure(hr, "failed to create command to execute session"); + SqlExitOnFailure(hr, "failed to create command to execute session"); // // set the sql text into the command // hr = picmd->QueryInterface(IID_ICommandText, (LPVOID*)&picmdText); - ExitOnFailure(hr, "failed to get command text object for command"); + SqlExitOnFailure(hr, "failed to get command text object for command"); hr = picmdText->SetCommandText(DBGUID_DEFAULT , wzSql); - ExitOnFailure(hr, "failed to set SQL string: %ls", wzSql); + SqlExitOnFailure(hr, "failed to set SQL string: %ls", wzSql); // // execute the command // hr = picmd->Execute(NULL, (ppirs) ? IID_IRowset : IID_NULL, NULL, &cRows, reinterpret_cast(ppirs)); - ExitOnFailure(hr, "failed to execute SQL string: %ls", wzSql); + SqlExitOnFailure(hr, "failed to execute SQL string: %ls", wzSql); if (DB_S_ERRORSOCCURRED == hr) { @@ -700,14 +715,14 @@ extern "C" HRESULT DAPI SqlGetErrorInfo( // only ask for error information if the interface supports it. hr = pObjectWithError->QueryInterface(IID_ISupportErrorInfo,(void**)&pISupportErrorInfo); - ExitOnFailure(hr, "No error information was found for object."); + SqlExitOnFailure(hr, "No error information was found for object."); hr = pISupportErrorInfo->InterfaceSupportsErrorInfo(IID_InterfaceWithError); - ExitOnFailure(hr, "InterfaceWithError is not supported for object with error"); + SqlExitOnFailure(hr, "InterfaceWithError is not supported for object with error"); // ignore the return of GetErrorInfo it can succeed and return a NULL pointer in pIErrorInfoAll anyway hr = ::GetErrorInfo(0, &pIErrorInfoAll); - ExitOnFailure(hr, "failed to get error info"); + SqlExitOnFailure(hr, "failed to get error info"); if (S_OK == hr && pIErrorInfoAll) { @@ -787,37 +802,37 @@ static HRESULT FileSpecToString( LPWSTR pwz = NULL; hr = StrAllocString(&pwz, L"(", 1024); - ExitOnFailure(hr, "failed to allocate string for database file info"); + SqlExitOnFailure(hr, "failed to allocate string for database file info"); - ExitOnNull(*psf->wzName, hr, E_INVALIDARG, "logical name not specified in database file info"); - ExitOnNull(*psf->wzFilename, hr, E_INVALIDARG, "filename not specified in database file info"); + SqlExitOnNull(*psf->wzName, hr, E_INVALIDARG, "logical name not specified in database file info"); + SqlExitOnNull(*psf->wzFilename, hr, E_INVALIDARG, "filename not specified in database file info"); hr = StrAllocFormatted(&pwz, L"%sNAME=%s", pwz, psf->wzName); - ExitOnFailure(hr, "failed to format database file info name: %ls", psf->wzName); + SqlExitOnFailure(hr, "failed to format database file info name: %ls", psf->wzName); hr = StrAllocFormatted(&pwz, L"%s, FILENAME='%s'", pwz, psf->wzFilename); - ExitOnFailure(hr, "failed to format database file info filename: %ls", psf->wzFilename); + SqlExitOnFailure(hr, "failed to format database file info filename: %ls", psf->wzFilename); if (0 != psf->wzSize[0]) { hr = StrAllocFormatted(&pwz, L"%s, SIZE=%s", pwz, psf->wzSize); - ExitOnFailure(hr, "failed to format database file info size: %s", psf->wzSize); + SqlExitOnFailure(hr, "failed to format database file info size: %ls", psf->wzSize); } if (0 != psf->wzMaxSize[0]) { hr = StrAllocFormatted(&pwz, L"%s, MAXSIZE=%s", pwz, psf->wzMaxSize); - ExitOnFailure(hr, "failed to format database file info maxsize: %s", psf->wzMaxSize); + SqlExitOnFailure(hr, "failed to format database file info maxsize: %ls", psf->wzMaxSize); } if (0 != psf->wzGrow[0]) { hr = StrAllocFormatted(&pwz, L"%s, FILEGROWTH=%s", pwz, psf->wzGrow); - ExitOnFailure(hr, "failed to format database file info growth: %s", psf->wzGrow); + SqlExitOnFailure(hr, "failed to format database file info growth: %ls", psf->wzGrow); } hr = StrAllocFormatted(&pwz, L"%s)", pwz); - ExitOnFailure(hr, "failed to allocate string for file spec"); + SqlExitOnFailure(hr, "failed to allocate string for file spec"); *ppwz = pwz; pwz = NULL; // null here so it doesn't get freed below @@ -850,13 +865,13 @@ static HRESULT EscapeSqlIdentifier( if (cchIdentifier == 0 || (wzIdentifier[0] == '[' && wzIdentifier[cchIdentifier-1] == ']')) { hr = StrAllocString(&pwz, wzIdentifier, 0); - ExitOnFailure(hr, "failed to format database name: %ls", wzIdentifier); + SqlExitOnFailure(hr, "failed to format database name: %ls", wzIdentifier); } else { //escape it hr = StrAllocFormatted(&pwz, L"[%s]", wzIdentifier); - ExitOnFailure(hr, "failed to format escaped database name: %ls", wzIdentifier); + SqlExitOnFailure(hr, "failed to format escaped database name: %ls", wzIdentifier); } *ppwz = pwz; diff --git a/src/dutil/srputil.cpp b/src/dutil/srputil.cpp index 9fc2f94a..e44536cc 100644 --- a/src/dutil/srputil.cpp +++ b/src/dutil/srputil.cpp @@ -3,6 +3,21 @@ #include "precomp.h" +// Exit macros +#define SrpExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_SRPUTIL, x, s, __VA_ARGS__) +#define SrpExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_SRPUTIL, x, s, __VA_ARGS__) +#define SrpExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_SRPUTIL, x, s, __VA_ARGS__) +#define SrpExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_SRPUTIL, x, s, __VA_ARGS__) +#define SrpExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_SRPUTIL, x, s, __VA_ARGS__) +#define SrpExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_SRPUTIL, x, s, __VA_ARGS__) +#define SrpExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_SRPUTIL, p, x, e, s, __VA_ARGS__) +#define SrpExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_SRPUTIL, p, x, s, __VA_ARGS__) +#define SrpExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_SRPUTIL, p, x, e, s, __VA_ARGS__) +#define SrpExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_SRPUTIL, p, x, s, __VA_ARGS__) +#define SrpExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_SRPUTIL, e, x, s, __VA_ARGS__) +#define SrpExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_SRPUTIL, g, x, s, __VA_ARGS__) + + typedef BOOL (WINAPI *PFN_SETRESTOREPTW)( __in PRESTOREPOINTINFOW pRestorePtSpec, __out PSTATEMGRSTATUS pSMgrStatus @@ -28,7 +43,7 @@ DAPI_(HRESULT) SrpInitialize( } vpfnSRSetRestorePointW = reinterpret_cast(::GetProcAddress(vhSrClientDll, "SRSetRestorePointW")); - ExitOnNullWithLastError(vpfnSRSetRestorePointW, hr, "Failed to find set restore point proc address."); + SrpExitOnNullWithLastError(vpfnSRSetRestorePointW, hr, "Failed to find set restore point proc address."); // If allowed, initialize COM security to enable NetworkService, // LocalService and System to make callbacks to the process @@ -37,7 +52,7 @@ DAPI_(HRESULT) SrpInitialize( if (fInitializeComSecurity) { hr = InitializeComSecurity(); - ExitOnFailure(hr, "Failed to initialize security for COM to talk to system restore."); + SrpExitOnFailure(hr, "Failed to initialize security for COM to talk to system restore."); } LExit: @@ -79,7 +94,7 @@ DAPI_(HRESULT) SrpCreateRestorePoint( if (!vpfnSRSetRestorePointW(&restorePoint, &status)) { - ExitOnWin32Error(status.nStatus, hr, "Failed to create system restore point."); + SrpExitOnWin32Error(status.nStatus, hr, "Failed to create system restore point."); } LExit: @@ -116,42 +131,42 @@ static HRESULT InitializeComSecurity() // Initialize the security descriptor. if (!::InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION)) { - ExitWithLastError(hr, "Failed to initialize security descriptor for system restore."); + SrpExitWithLastError(hr, "Failed to initialize security descriptor for system restore."); } // Create an administrator group security identifier (SID). cbSid = sizeof(rgSidBA); if (!::CreateWellKnownSid(WinBuiltinAdministratorsSid, NULL, rgSidBA, &cbSid)) { - ExitWithLastError(hr, "Failed to create administrator SID for system restore."); + SrpExitWithLastError(hr, "Failed to create administrator SID for system restore."); } // Create a local service security identifier (SID). cbSid = sizeof(rgSidLS); if (!::CreateWellKnownSid(WinLocalServiceSid, NULL, rgSidLS, &cbSid)) { - ExitWithLastError(hr, "Failed to create local service SID for system restore."); + SrpExitWithLastError(hr, "Failed to create local service SID for system restore."); } // Create a network service security identifier (SID). cbSid = sizeof(rgSidNS); if (!::CreateWellKnownSid(WinNetworkServiceSid, NULL, rgSidNS, &cbSid)) { - ExitWithLastError(hr, "Failed to create network service SID for system restore."); + SrpExitWithLastError(hr, "Failed to create network service SID for system restore."); } // Create a personal account security identifier (SID). cbSid = sizeof(rgSidPS); if (!::CreateWellKnownSid(WinSelfSid, NULL, rgSidPS, &cbSid)) { - ExitWithLastError(hr, "Failed to create self SID for system restore."); + SrpExitWithLastError(hr, "Failed to create self SID for system restore."); } // Create a local service security identifier (SID). cbSid = sizeof(rgSidSY); if (!::CreateWellKnownSid(WinLocalSystemSid, NULL, rgSidSY, &cbSid)) { - ExitWithLastError(hr, "Failed to create local system SID for system restore."); + SrpExitWithLastError(hr, "Failed to create local system SID for system restore."); } // Setup the access control entries (ACE) for COM. COM_RIGHTS_EXECUTE and @@ -203,29 +218,29 @@ static HRESULT InitializeComSecurity() // Create an access control list (ACL) using this ACE list. er = ::SetEntriesInAcl(countof(ea), ea, NULL, &pAcl); - ExitOnWin32Error(er, hr, "Failed to create ACL for system restore."); + SrpExitOnWin32Error(er, hr, "Failed to create ACL for system restore."); // Set the security descriptor owner to Administrators. if (!::SetSecurityDescriptorOwner(&sd, rgSidBA, FALSE)) { - ExitWithLastError(hr, "Failed to set administrators owner for system restore."); + SrpExitWithLastError(hr, "Failed to set administrators owner for system restore."); } // Set the security descriptor group to Administrators. if (!::SetSecurityDescriptorGroup(&sd, rgSidBA, FALSE)) { - ExitWithLastError(hr, "Failed to set administrators group access for system restore."); + SrpExitWithLastError(hr, "Failed to set administrators group access for system restore."); } // Set the discretionary access control list (DACL) to the ACL. if (!::SetSecurityDescriptorDacl(&sd, TRUE, pAcl, FALSE)) { - ExitWithLastError(hr, "Failed to set DACL for system restore."); + SrpExitWithLastError(hr, "Failed to set DACL for system restore."); } // Note that an explicit security descriptor is being passed in. hr= ::CoInitializeSecurity(&sd, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_PKT_PRIVACY, RPC_C_IMP_LEVEL_IDENTIFY, NULL, EOAC_DISABLE_AAA | EOAC_NO_CUSTOM_MARSHAL, NULL); - ExitOnFailure(hr, "Failed to initialize COM security for system restore."); + SrpExitOnFailure(hr, "Failed to initialize COM security for system restore."); LExit: if (pAcl) diff --git a/src/dutil/strutil.cpp b/src/dutil/strutil.cpp index c1d701d3..daa090c9 100644 --- a/src/dutil/strutil.cpp +++ b/src/dutil/strutil.cpp @@ -2,6 +2,21 @@ #include "precomp.h" + +// Exit macros +#define StrExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_STRUTIL, x, s, __VA_ARGS__) +#define StrExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_STRUTIL, x, s, __VA_ARGS__) +#define StrExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_STRUTIL, x, s, __VA_ARGS__) +#define StrExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_STRUTIL, x, s, __VA_ARGS__) +#define StrExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_STRUTIL, x, s, __VA_ARGS__) +#define StrExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_STRUTIL, x, s, __VA_ARGS__) +#define StrExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_STRUTIL, p, x, e, s, __VA_ARGS__) +#define StrExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_STRUTIL, p, x, s, __VA_ARGS__) +#define StrExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_STRUTIL, p, x, e, s, __VA_ARGS__) +#define StrExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_STRUTIL, p, x, s, __VA_ARGS__) +#define StrExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_STRUTIL, e, x, s, __VA_ARGS__) +#define StrExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_STRUTIL, g, x, s, __VA_ARGS__) + #define ARRAY_GROWTH_SIZE 5 // Forward declarations. @@ -84,7 +99,7 @@ static HRESULT AllocHelper( if (cch >= MAXDWORD / sizeof(WCHAR)) { hr = E_OUTOFMEMORY; - ExitOnFailure(hr, "Not enough memory to allocate string of size: %u", cch); + StrExitOnFailure(hr, "Not enough memory to allocate string of size: %u", cch); } if (*ppwz) @@ -93,7 +108,7 @@ static HRESULT AllocHelper( { LPVOID pvNew = NULL; hr = MemReAllocSecure(*ppwz, sizeof(WCHAR)* cch, FALSE, &pvNew); - ExitOnFailure(hr, "Failed to reallocate string"); + StrExitOnFailure(hr, "Failed to reallocate string"); pwz = static_cast(pvNew); } else @@ -106,7 +121,7 @@ static HRESULT AllocHelper( pwz = static_cast(MemAlloc(sizeof(WCHAR) * cch, TRUE)); } - ExitOnNull(pwz, hr, E_OUTOFMEMORY, "failed to allocate string, len: %u", cch); + StrExitOnNull(pwz, hr, E_OUTOFMEMORY, "failed to allocate string, len: %u", cch); *ppwz = pwz; LExit: @@ -131,12 +146,12 @@ HRESULT DAPI StrTrimCapacity( SIZE_T cchLen = 0; hr = ::StringCchLengthW(*ppwz, STRSAFE_MAX_CCH, reinterpret_cast(&cchLen)); - ExitOnFailure(hr, "Failed to calculate length of string"); + StrExitOnFailure(hr, "Failed to calculate length of string"); ++cchLen; // Add 1 for null-terminator hr = StrAlloc(ppwz, cchLen); - ExitOnFailure(hr, "Failed to reallocate string"); + StrExitOnFailure(hr, "Failed to reallocate string"); LExit: return hr; @@ -181,7 +196,7 @@ HRESULT DAPI StrTrimWhitespace( } hr = StrAllocString(&sczResult, wzSource, i); - ExitOnFailure(hr, "Failed to copy result string"); + StrExitOnFailure(hr, "Failed to copy result string"); // Output result *ppwz = sczResult; @@ -212,7 +227,7 @@ extern "C" HRESULT DAPI StrAnsiAlloc( if (cch >= MAXDWORD / sizeof(WCHAR)) { hr = E_OUTOFMEMORY; - ExitOnFailure(hr, "Not enough memory to allocate string of size: %u", cch); + StrExitOnFailure(hr, "Not enough memory to allocate string of size: %u", cch); } if (*ppsz) @@ -224,7 +239,7 @@ extern "C" HRESULT DAPI StrAnsiAlloc( psz = static_cast(MemAlloc(sizeof(CHAR) * cch, TRUE)); } - ExitOnNull(psz, hr, E_OUTOFMEMORY, "failed to allocate string, len: %u", cch); + StrExitOnNull(psz, hr, E_OUTOFMEMORY, "failed to allocate string, len: %u", cch); *ppsz = psz; LExit: @@ -252,12 +267,12 @@ HRESULT DAPI StrAnsiTrimCapacity( #pragma prefast(disable:25068) hr = ::StringCchLengthA(*ppz, STRSAFE_MAX_CCH, reinterpret_cast(&cchLen)); #pragma prefast(pop) - ExitOnFailure(hr, "Failed to calculate length of string"); + StrExitOnFailure(hr, "Failed to calculate length of string"); ++cchLen; // Add 1 for null-terminator hr = StrAnsiAlloc(ppz, cchLen); - ExitOnFailure(hr, "Failed to reallocate string"); + StrExitOnFailure(hr, "Failed to reallocate string"); LExit: return hr; @@ -302,7 +317,7 @@ HRESULT DAPI StrAnsiTrimWhitespace( } hr = StrAnsiAllocStringAnsi(&sczResult, szSource, i); - ExitOnFailure(hr, "Failed to copy result string"); + StrExitOnFailure(hr, "Failed to copy result string"); // Output result *ppz = sczResult; @@ -375,7 +390,7 @@ static HRESULT AllocStringHelper( if (-1 == cch) { hr = E_INVALIDARG; - ExitOnFailure(hr, "failed to get size of destination string"); + StrExitOnFailure(hr, "failed to get size of destination string"); } cch /= sizeof(WCHAR); //convert the count in bytes to count in characters } @@ -387,13 +402,13 @@ static HRESULT AllocStringHelper( SIZE_T cchNeeded; hr = ::ULongPtrAdd(cchSource, 1, &cchNeeded); // add one for the null terminator - ExitOnFailure(hr, "source string is too long"); + StrExitOnFailure(hr, "source string is too long"); if (cch < cchNeeded) { cch = cchNeeded; hr = AllocHelper(ppwz, cch, fZeroOnRealloc); - ExitOnFailure(hr, "failed to allocate string from string."); + StrExitOnFailure(hr, "failed to allocate string from string."); } // copy everything (the NULL terminator will be included) @@ -431,7 +446,7 @@ extern "C" HRESULT DAPI StrAnsiAllocString( if (-1 == cch) { hr = E_INVALIDARG; - ExitOnFailure(hr, "failed to get size of destination string"); + StrExitOnFailure(hr, "failed to get size of destination string"); } cch /= sizeof(CHAR); //convert the count in bytes to count in characters } @@ -441,7 +456,7 @@ extern "C" HRESULT DAPI StrAnsiAllocString( cchDest = ::WideCharToMultiByte(uiCodepage, 0, wzSource, -1, NULL, 0, NULL, NULL); if (0 == cchDest) { - ExitWithLastError(hr, "failed to get required size for conversion to ANSI: %ls", wzSource); + StrExitWithLastError(hr, "failed to get required size for conversion to ANSI: %ls", wzSource); } --cchDest; // subtract one because WideChageToMultiByte includes space for the NULL terminator that we track below @@ -457,7 +472,7 @@ extern "C" HRESULT DAPI StrAnsiAllocString( if (cch >= MAXDWORD / sizeof(WCHAR)) { hr = E_OUTOFMEMORY; - ExitOnFailure(hr, "Not enough memory to allocate string of size: %u", cch); + StrExitOnFailure(hr, "Not enough memory to allocate string of size: %u", cch); } if (*ppsz) @@ -468,14 +483,14 @@ extern "C" HRESULT DAPI StrAnsiAllocString( { psz = static_cast(MemAlloc(sizeof(CHAR) * cch, TRUE)); } - ExitOnNull(psz, hr, E_OUTOFMEMORY, "failed to allocate string, len: %u", cch); + StrExitOnNull(psz, hr, E_OUTOFMEMORY, "failed to allocate string, len: %u", cch); *ppsz = psz; } if (0 == ::WideCharToMultiByte(uiCodepage, 0, wzSource, 0 == cchSource ? -1 : (int)cchSource, *ppsz, (int)cch, NULL, NULL)) { - ExitWithLastError(hr, "failed to convert to ansi: %ls", wzSource); + StrExitWithLastError(hr, "failed to convert to ansi: %ls", wzSource); } (*ppsz)[cchDest] = L'\0'; @@ -511,7 +526,7 @@ extern "C" HRESULT DAPI StrAllocStringAnsi( if (-1 == cch) { hr = E_INVALIDARG; - ExitOnFailure(hr, "failed to get size of destination string"); + StrExitOnFailure(hr, "failed to get size of destination string"); } cch /= sizeof(WCHAR); //convert the count in bytes to count in characters } @@ -521,7 +536,7 @@ extern "C" HRESULT DAPI StrAllocStringAnsi( cchDest = ::MultiByteToWideChar(uiCodepage, 0, szSource, -1, NULL, 0); if (0 == cchDest) { - ExitWithLastError(hr, "failed to get required size for conversion to unicode: %s", szSource); + StrExitWithLastError(hr, "failed to get required size for conversion to unicode: %s", szSource); } --cchDest; //subtract one because MultiByteToWideChar includes space for the NULL terminator that we track below @@ -537,7 +552,7 @@ extern "C" HRESULT DAPI StrAllocStringAnsi( if (cch >= MAXDWORD / sizeof(WCHAR)) { hr = E_OUTOFMEMORY; - ExitOnFailure(hr, "Not enough memory to allocate string of size: %u", cch); + StrExitOnFailure(hr, "Not enough memory to allocate string of size: %u", cch); } if (*ppwz) @@ -549,14 +564,14 @@ extern "C" HRESULT DAPI StrAllocStringAnsi( pwz = static_cast(MemAlloc(sizeof(WCHAR) * cch, TRUE)); } - ExitOnNull(pwz, hr, E_OUTOFMEMORY, "failed to allocate string, len: %u", cch); + StrExitOnNull(pwz, hr, E_OUTOFMEMORY, "failed to allocate string, len: %u", cch); *ppwz = pwz; } if (0 == ::MultiByteToWideChar(uiCodepage, 0, szSource, 0 == cchSource ? -1 : (int)cchSource, *ppwz, (int)cch)) { - ExitWithLastError(hr, "failed to convert to unicode: %s", szSource); + StrExitWithLastError(hr, "failed to convert to unicode: %s", szSource); } (*ppwz)[cchDest] = L'\0'; @@ -589,7 +604,7 @@ HRESULT DAPI StrAnsiAllocStringAnsi( if (-1 == cch) { hr = E_INVALIDARG; - ExitOnFailure(hr, "failed to get size of destination string"); + StrExitOnFailure(hr, "failed to get size of destination string"); } cch /= sizeof(CHAR); //convert the count in bytes to count in characters } @@ -601,13 +616,13 @@ HRESULT DAPI StrAnsiAllocStringAnsi( SIZE_T cchNeeded; hr = ::ULongPtrAdd(cchSource, 1, &cchNeeded); // add one for the null terminator - ExitOnFailure(hr, "source string is too long"); + StrExitOnFailure(hr, "source string is too long"); if (cch < cchNeeded) { cch = cchNeeded; hr = StrAnsiAlloc(ppsz, cch); - ExitOnFailure(hr, "failed to allocate string from string."); + StrExitOnFailure(hr, "failed to allocate string from string."); } // copy everything (the NULL terminator will be included) @@ -647,12 +662,12 @@ extern "C" HRESULT DAPI StrAllocPrefix( if (-1 == cch) { hr = E_INVALIDARG; - ExitOnFailure(hr, "failed to get size of destination string"); + StrExitOnFailure(hr, "failed to get size of destination string"); } cch /= sizeof(WCHAR); //convert the count in bytes to count in characters hr = ::StringCchLengthW(*ppwz, STRSAFE_MAX_CCH, reinterpret_cast(&cchLen)); - ExitOnFailure(hr, "Failed to calculate length of string"); + StrExitOnFailure(hr, "Failed to calculate length of string"); } Assert(cchLen <= cch); @@ -660,14 +675,14 @@ extern "C" HRESULT DAPI StrAllocPrefix( if (0 == cchPrefix) { hr = ::StringCchLengthW(wzPrefix, STRSAFE_MAX_CCH, reinterpret_cast(&cchPrefix)); - ExitOnFailure(hr, "Failed to calculate length of string"); + StrExitOnFailure(hr, "Failed to calculate length of string"); } if (cch - cchLen < cchPrefix + 1) { cch = cchPrefix + cchLen + 1; hr = StrAlloc(ppwz, cch); - ExitOnFailure(hr, "failed to allocate string from string: %ls", wzPrefix); + StrExitOnFailure(hr, "failed to allocate string from string: %ls", wzPrefix); } if (*ppwz) @@ -681,7 +696,7 @@ extern "C" HRESULT DAPI StrAllocPrefix( else { hr = E_UNEXPECTED; - ExitOnFailure(hr, "for some reason our buffer is still null"); + StrExitOnFailure(hr, "for some reason our buffer is still null"); } LExit: @@ -753,12 +768,12 @@ static HRESULT AllocConcatHelper( if (-1 == cch) { hr = E_INVALIDARG; - ExitOnFailure(hr, "failed to get size of destination string"); + StrExitOnFailure(hr, "failed to get size of destination string"); } cch /= sizeof(WCHAR); //convert the count in bytes to count in characters hr = ::StringCchLengthW(*ppwz, STRSAFE_MAX_CCH, reinterpret_cast(&cchLen)); - ExitOnFailure(hr, "Failed to calculate length of string"); + StrExitOnFailure(hr, "Failed to calculate length of string"); } Assert(cchLen <= cch); @@ -766,14 +781,14 @@ static HRESULT AllocConcatHelper( if (0 == cchSource) { hr = ::StringCchLengthW(wzSource, STRSAFE_MAX_CCH, reinterpret_cast(&cchSource)); - ExitOnFailure(hr, "Failed to calculate length of string"); + StrExitOnFailure(hr, "Failed to calculate length of string"); } if (cch - cchLen < cchSource + 1) { cch = (cchSource + cchLen + 1) * 2; hr = AllocHelper(ppwz, cch, fZeroOnRealloc); - ExitOnFailure(hr, "failed to allocate string from string: %ls", wzSource); + StrExitOnFailure(hr, "failed to allocate string from string: %ls", wzSource); } if (*ppwz) @@ -783,7 +798,7 @@ static HRESULT AllocConcatHelper( else { hr = E_UNEXPECTED; - ExitOnFailure(hr, "for some reason our buffer is still null"); + StrExitOnFailure(hr, "for some reason our buffer is still null"); } LExit: @@ -816,7 +831,7 @@ extern "C" HRESULT DAPI StrAnsiAllocConcat( if (-1 == cch) { hr = E_INVALIDARG; - ExitOnFailure(hr, "failed to get size of destination string"); + StrExitOnFailure(hr, "failed to get size of destination string"); } cch /= sizeof(CHAR); // convert the count in bytes to count in characters @@ -824,7 +839,7 @@ extern "C" HRESULT DAPI StrAnsiAllocConcat( #pragma prefast(disable:25068) hr = ::StringCchLengthA(*ppz, STRSAFE_MAX_CCH, reinterpret_cast(&cchLen)); #pragma prefast(pop) - ExitOnFailure(hr, "Failed to calculate length of string"); + StrExitOnFailure(hr, "Failed to calculate length of string"); } Assert(cchLen <= cch); @@ -835,14 +850,14 @@ extern "C" HRESULT DAPI StrAnsiAllocConcat( #pragma prefast(disable:25068) hr = ::StringCchLengthA(pzSource, STRSAFE_MAX_CCH, reinterpret_cast(&cchSource)); #pragma prefast(pop) - ExitOnFailure(hr, "Failed to calculate length of string"); + StrExitOnFailure(hr, "Failed to calculate length of string"); } if (cch - cchLen < cchSource + 1) { cch = (cchSource + cchLen + 1) * 2; hr = StrAnsiAlloc(ppz, cch); - ExitOnFailure(hr, "failed to allocate string from string: %hs", pzSource); + StrExitOnFailure(hr, "failed to allocate string from string: %hs", pzSource); } if (*ppz) @@ -855,7 +870,7 @@ extern "C" HRESULT DAPI StrAnsiAllocConcat( else { hr = E_UNEXPECTED; - ExitOnFailure(hr, "for some reason our buffer is still null"); + StrExitOnFailure(hr, "for some reason our buffer is still null"); } LExit: @@ -908,7 +923,7 @@ extern "C" HRESULT __cdecl StrAllocConcatFormatted( va_start(args, wzFormat); hr = StrAllocFormattedArgs(&sczFormatted, wzFormat, args); va_end(args); - ExitOnFailure(hr, "Failed to allocate formatted string"); + StrExitOnFailure(hr, "Failed to allocate formatted string"); hr = StrAllocConcat(ppwz, sczFormatted, 0); @@ -942,7 +957,7 @@ extern "C" HRESULT __cdecl StrAllocConcatFormattedSecure( va_start(args, wzFormat); hr = StrAllocFormattedArgsSecure(&sczFormatted, wzFormat, args); va_end(args); - ExitOnFailure(hr, "Failed to allocate formatted string"); + StrExitOnFailure(hr, "Failed to allocate formatted string"); hr = StrAllocConcatSecure(ppwz, sczFormatted, 0); @@ -1068,7 +1083,7 @@ static HRESULT AllocFormattedArgsHelper( if (-1 == cbOriginal) { hr = E_INVALIDARG; - ExitOnFailure(hr, "failed to get size of destination string"); + StrExitOnFailure(hr, "failed to get size of destination string"); } cch = cbOriginal / sizeof(WCHAR); //convert the count in bytes to count in characters @@ -1080,7 +1095,7 @@ static HRESULT AllocFormattedArgsHelper( cch = 256; hr = AllocHelper(ppwz, cch, fZeroOnRealloc); - ExitOnFailure(hr, "failed to allocate string to format: %ls", wzFormat); + StrExitOnFailure(hr, "failed to allocate string to format: %ls", wzFormat); } // format the message (grow until it fits or there is a failure) @@ -1104,12 +1119,12 @@ static HRESULT AllocFormattedArgsHelper( cch *= 2; hr = AllocHelper(ppwz, cch, fZeroOnRealloc); - ExitOnFailure(hr, "failed to allocate string to format: %ls", wzFormat); + StrExitOnFailure(hr, "failed to allocate string to format: %ls", wzFormat); hr = S_FALSE; } } while (S_FALSE == hr); - ExitOnFailure(hr, "failed to format string"); + StrExitOnFailure(hr, "failed to format string"); LExit: if (pwzOriginal && fZeroOnRealloc) @@ -1148,7 +1163,7 @@ extern "C" HRESULT DAPI StrAnsiAllocFormattedArgs( if (-1 == cch) { hr = E_INVALIDARG; - ExitOnFailure(hr, "failed to get size of destination string"); + StrExitOnFailure(hr, "failed to get size of destination string"); } cch /= sizeof(CHAR); //convert the count in bytes to count in characters @@ -1159,7 +1174,7 @@ extern "C" HRESULT DAPI StrAnsiAllocFormattedArgs( { cch = 256; hr = StrAnsiAlloc(ppsz, cch); - ExitOnFailure(hr, "failed to allocate string to format: %s", szFormat); + StrExitOnFailure(hr, "failed to allocate string to format: %s", szFormat); } // format the message (grow until it fits or there is a failure) @@ -1183,11 +1198,11 @@ extern "C" HRESULT DAPI StrAnsiAllocFormattedArgs( } cch *= 2; hr = StrAnsiAlloc(ppsz, cch); - ExitOnFailure(hr, "failed to allocate string to format: %hs", szFormat); + StrExitOnFailure(hr, "failed to allocate string to format: %hs", szFormat); hr = S_FALSE; } } while (S_FALSE == hr); - ExitOnFailure(hr, "failed to format string"); + StrExitOnFailure(hr, "failed to format string"); LExit: ReleaseStr(pszOriginal); @@ -1224,11 +1239,11 @@ extern "C" HRESULT DAPI StrAllocFromError( if (0 == cchMessage) { - ExitWithLastError(hr, "Failed to format message for error: 0x%x", hrError); + StrExitWithLastError(hr, "Failed to format message for error: 0x%x", hrError); } hr = StrAllocString(ppwzMessage, reinterpret_cast(pvMessage), cchMessage); - ExitOnFailure(hr, "Failed to allocate string for message."); + StrExitOnFailure(hr, "Failed to allocate string for message."); LExit: if (pvMessage) @@ -1308,7 +1323,7 @@ extern "C" HRESULT DAPI StrFree( Assert(p); HRESULT hr = MemFree(p); - ExitOnFailure(hr, "failed to free string"); + StrExitOnFailure(hr, "failed to free string"); LExit: return hr; @@ -1332,7 +1347,7 @@ extern "C" HRESULT DAPI StrReplaceStringAll( do { hr = StrReplaceString(ppwzOriginal, &dwStartIndex, wzOldSubString, wzNewSubString); - ExitOnFailure(hr, "Failed to replace substring"); + StrExitOnFailure(hr, "Failed to replace substring"); } while (S_OK == hr); @@ -1373,21 +1388,21 @@ extern "C" HRESULT DAPI StrReplaceString( } hr = ::PtrdiffTToDWord(wzSubLocation - *ppwzOriginal, pdwStartIndex); - ExitOnFailure(hr, "Failed to diff pointers."); + StrExitOnFailure(hr, "Failed to diff pointers."); hr = StrAllocString(&pwzBuffer, *ppwzOriginal, wzSubLocation - *ppwzOriginal); - ExitOnFailure(hr, "Failed to duplicate string."); + StrExitOnFailure(hr, "Failed to duplicate string."); pwzBuffer[wzSubLocation - *ppwzOriginal] = '\0'; hr = StrAllocConcat(&pwzBuffer, wzNewSubString, 0); - ExitOnFailure(hr, "Failed to append new string."); + StrExitOnFailure(hr, "Failed to append new string."); hr = StrAllocConcat(&pwzBuffer, wzSubLocation + wcslen(wzOldSubString), 0); - ExitOnFailure(hr, "Failed to append post string."); + StrExitOnFailure(hr, "Failed to append post string."); hr = StrFree(*ppwzOriginal); - ExitOnFailure(hr, "Failed to free original string."); + StrExitOnFailure(hr, "Failed to free original string."); *ppwzOriginal = pwzBuffer; *pdwStartIndex = *pdwStartIndex + static_cast(wcslen(wzNewSubString)); @@ -1477,10 +1492,10 @@ HRESULT DAPI StrAllocHexEncode( SIZE_T cchSource = sizeof(WCHAR) * (cbSource + 1); hr = StrAlloc(ppwzDest, cchSource); - ExitOnFailure(hr, "Failed to allocate hex string."); + StrExitOnFailure(hr, "Failed to allocate hex string."); hr = StrHexEncode(pbSource, cbSource, *ppwzDest, cchSource); - ExitOnFailure(hr, "Failed to encode hex string."); + StrExitOnFailure(hr, "Failed to encode hex string."); LExit: return hr; @@ -1509,7 +1524,7 @@ extern "C" HRESULT DAPI StrHexDecode( if (cbDest < cchSource / 2) { hr = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); - ExitOnRootFailure(hr, "Insufficient buffer to decode string '%ls' len: %u into %u bytes.", wzSource, cchSource, cbDest); + StrExitOnRootFailure(hr, "Insufficient buffer to decode string '%ls' len: %u into %u bytes.", wzSource, cchSource, cbDest); } for (i = 0; i < cchSource / 2; ++i) @@ -1547,20 +1562,20 @@ extern "C" HRESULT DAPI StrAllocHexDecode( DWORD cb = 0; hr = ::StringCchLengthW(wzSource, STRSAFE_MAX_CCH, &cch); - ExitOnFailure(hr, "Failed to calculate length of source string."); + StrExitOnFailure(hr, "Failed to calculate length of source string."); if (cch % 2) { hr = E_INVALIDARG; - ExitOnFailure(hr, "Invalid source parameter, string must be even length or it cannot be decoded."); + StrExitOnFailure(hr, "Invalid source parameter, string must be even length or it cannot be decoded."); } cb = static_cast(cch / 2); pb = static_cast(MemAlloc(cb, TRUE)); - ExitOnNull(pb, hr, E_OUTOFMEMORY, "Failed to allocate memory for hex decode."); + StrExitOnNull(pb, hr, E_OUTOFMEMORY, "Failed to allocate memory for hex decode."); hr = StrHexDecode(wzSource, pb, cb); - ExitOnFailure(hr, "Failed to decode source string."); + StrExitOnFailure(hr, "Failed to decode source string."); *ppbDest = pb; pb = NULL; @@ -1637,7 +1652,7 @@ extern "C" HRESULT DAPI StrAllocBase85Encode( ++cchDest; // add room for null terminator hr = StrAlloc(pwzDest, cchDest); - ExitOnFailure(hr, "failed to allocate destination string"); + StrExitOnFailure(hr, "failed to allocate destination string"); wzDest = *pwzDest; @@ -1740,7 +1755,7 @@ extern "C" HRESULT DAPI StrAllocBase85Decode( } *ppbDest = static_cast(MemAlloc(cbDest, FALSE)); - ExitOnNull(*ppbDest, hr, E_OUTOFMEMORY, "failed allocate memory to decode the string"); + StrExitOnNull(*ppbDest, hr, E_OUTOFMEMORY, "failed allocate memory to decode the string"); pbDest = *ppbDest; *pcbDest = cbDest; @@ -1860,7 +1875,7 @@ extern "C" HRESULT DAPI MultiSzLen( DWORD_PTR dwMaxSize = 0; hr = StrMaxLength(pwzMultiSz, &dwMaxSize); - ExitOnFailure(hr, "failed to get the max size of a string while calculating MULTISZ length"); + StrExitOnFailure(hr, "failed to get the max size of a string while calculating MULTISZ length"); *pcch = 0; while (*pcch < dwMaxSize) @@ -1914,7 +1929,7 @@ extern "C" HRESULT DAPI MultiSzPrepend( else { hr = MultiSzLen(*ppwzMultiSz, &cchMultiSz); - ExitOnFailure(hr, "failed to get length of multisz"); + StrExitOnFailure(hr, "failed to get length of multisz"); } cchInsert = lstrlenW(pwzInsert); @@ -1923,11 +1938,11 @@ extern "C" HRESULT DAPI MultiSzPrepend( // Allocate the result buffer hr = StrAlloc(&pwzResult, cchResult + 1); - ExitOnFailure(hr, "failed to allocate result string"); + StrExitOnFailure(hr, "failed to allocate result string"); // Prepend hr = ::StringCchCopyW(pwzResult, cchResult, pwzInsert); - ExitOnFailure(hr, "failed to copy prepend string: %ls", pwzInsert); + StrExitOnFailure(hr, "failed to copy prepend string: %ls", pwzInsert); // If there was no MULTISZ, double null terminate our result, otherwise, copy the MULTISZ in if (0 == cchMultiSz) @@ -1983,7 +1998,7 @@ extern "C" HRESULT DAPI MultiSzFindSubstring( SIZE_T cchProgress = 0; hr = MultiSzLen(pwzMultiSz, &cchMultiSz); - ExitOnFailure(hr, "failed to get the length of a MULTISZ string"); + StrExitOnFailure(hr, "failed to get the length of a MULTISZ string"); // Find the string containing the sub string hr = S_OK; @@ -2049,7 +2064,7 @@ extern "C" HRESULT DAPI MultiSzFindString( SIZE_T cchProgress = 0; hr = MultiSzLen(pwzMultiSz, &cchMutliSz); - ExitOnFailure(hr, "failed to get the length of a MULTISZ string"); + StrExitOnFailure(hr, "failed to get the length of a MULTISZ string"); // Find the string hr = S_OK; @@ -2116,7 +2131,7 @@ extern "C" HRESULT DAPI MultiSzRemoveString( SIZE_T cchProgress = 0; hr = MultiSzLen(*ppwzMultiSz, &cchMultiSz); - ExitOnFailure(hr, "failed to get the length of a MULTISZ string"); + StrExitOnFailure(hr, "failed to get the length of a MULTISZ string"); // Find the index we want to remove hr = S_OK; @@ -2159,7 +2174,7 @@ extern "C" HRESULT DAPI MultiSzRemoveString( if (cchProgress > cchMultiSz) { hr = E_UNEXPECTED; - ExitOnFailure(hr, "failed to move past the string to be removed from MULTISZ"); + StrExitOnFailure(hr, "failed to move past the string to be removed from MULTISZ"); } // Move on to the next character @@ -2181,7 +2196,7 @@ extern "C" HRESULT DAPI MultiSzInsertString( __deref_inout __nullnullterminated LPWSTR* ppwzMultiSz, __inout_opt SIZE_T* pcchMultiSz, __in DWORD_PTR dwIndex, - __in __nullnullterminated LPCWSTR pwzInsert + __in_z LPCWSTR pwzInsert ) { Assert(ppwzMultiSz && pwzInsert && *pwzInsert); @@ -2202,7 +2217,7 @@ extern "C" HRESULT DAPI MultiSzInsertString( else { hr = MultiSzLen(*ppwzMultiSz, &cchMultiSz); - ExitOnFailure(hr, "failed to get the length of a MULTISZ string"); + StrExitOnFailure(hr, "failed to get the length of a MULTISZ string"); } // Find the index we want to insert at @@ -2220,7 +2235,7 @@ extern "C" HRESULT DAPI MultiSzInsertString( if ((dwCurrentIndex + 1 != dwIndex && L'\0' == *(wz + 1)) || cchProgress >= cchMultiSz) { hr = HRESULT_FROM_WIN32(ERROR_OBJECT_NOT_FOUND); - ExitOnRootFailure(hr, "requested to insert into an invalid index: %u in a MULTISZ", dwIndex); + StrExitOnRootFailure(hr, "requested to insert into an invalid index: %u in a MULTISZ", dwIndex); } // Move on to the next string @@ -2235,7 +2250,7 @@ extern "C" HRESULT DAPI MultiSzInsertString( cchResult = cchMultiSz + cchString + 1; hr = StrAlloc(&pwzResult, cchResult); - ExitOnFailure(hr, "failed to allocate result string for MULTISZ insert"); + StrExitOnFailure(hr, "failed to allocate result string for MULTISZ insert"); // Copy the part before the insert ::CopyMemory(pwzResult, *ppwzMultiSz, cchProgress * sizeof(WCHAR)); @@ -2273,7 +2288,7 @@ MultiSzReplaceString - replaces string at the specified index with a new one extern "C" HRESULT DAPI MultiSzReplaceString( __deref_inout __nullnullterminated LPWSTR* ppwzMultiSz, __in DWORD_PTR dwIndex, - __in __nullnullterminated LPCWSTR pwzString + __in_z LPCWSTR pwzString ) { Assert(ppwzMultiSz && pwzString && *pwzString); @@ -2281,10 +2296,10 @@ extern "C" HRESULT DAPI MultiSzReplaceString( HRESULT hr = S_OK; hr = MultiSzRemoveString(ppwzMultiSz, dwIndex); - ExitOnFailure(hr, "failed to remove string from MULTISZ at the specified index: %u", dwIndex); + StrExitOnFailure(hr, "failed to remove string from MULTISZ at the specified index: %u", dwIndex); hr = MultiSzInsertString(ppwzMultiSz, NULL, dwIndex, pwzString); - ExitOnFailure(hr, "failed to insert string into MULTISZ at the specified index: %u", dwIndex); + StrExitOnFailure(hr, "failed to insert string into MULTISZ at the specified index: %u", dwIndex); LExit: return hr; @@ -2344,7 +2359,7 @@ extern "C" HRESULT DAPI StrStringToInt16( LONGLONG ll = 0; hr = StrStringToInt64(wzIn, cchIn, &ll); - ExitOnFailure(hr, "Failed to parse int64."); + StrExitOnFailure(hr, "Failed to parse int64."); if (SHORT_MAX < ll || SHORT_MIN > ll) { @@ -2370,7 +2385,7 @@ extern "C" HRESULT DAPI StrStringToUInt16( ULONGLONG ull = 0; hr = StrStringToUInt64(wzIn, cchIn, &ull); - ExitOnFailure(hr, "Failed to parse uint64."); + StrExitOnFailure(hr, "Failed to parse uint64."); if (USHORT_MAX < ull) { @@ -2396,7 +2411,7 @@ extern "C" HRESULT DAPI StrStringToInt32( LONGLONG ll = 0; hr = StrStringToInt64(wzIn, cchIn, &ll); - ExitOnFailure(hr, "Failed to parse int64."); + StrExitOnFailure(hr, "Failed to parse int64."); if (INT_MAX < ll || INT_MIN > ll) { @@ -2422,7 +2437,7 @@ extern "C" HRESULT DAPI StrStringToUInt32( ULONGLONG ull = 0; hr = StrStringToUInt64(wzIn, cchIn, &ull); - ExitOnFailure(hr, "Failed to parse uint64."); + StrExitOnFailure(hr, "Failed to parse uint64."); if (UINT_MAX < ull) { @@ -2607,13 +2622,13 @@ extern "C" HRESULT DAPI StrArrayAllocString( UINT cNewStrArray; hr = ::UIntAdd(*pcStrArray, 1, &cNewStrArray); - ExitOnFailure(hr, "Failed to increment the string array element count."); + StrExitOnFailure(hr, "Failed to increment the string array element count."); hr = MemEnsureArraySize(reinterpret_cast(prgsczStrArray), cNewStrArray, sizeof(LPWSTR), ARRAY_GROWTH_SIZE); - ExitOnFailure(hr, "Failed to allocate memory for the string array."); + StrExitOnFailure(hr, "Failed to allocate memory for the string array."); hr = StrAllocString(&(*prgsczStrArray)[*pcStrArray], wzSource, cchSource); - ExitOnFailure(hr, "Failed to allocate and assign the string."); + StrExitOnFailure(hr, "Failed to allocate and assign the string."); *pcStrArray = cNewStrArray; @@ -2639,12 +2654,12 @@ extern "C" HRESULT DAPI StrArrayFree( if (NULL != rgsczStrArray[i]) { hr = StrFree(rgsczStrArray[i]); - ExitOnFailure(hr, "Failed to free the string at index %u.", i); + StrExitOnFailure(hr, "Failed to free the string at index %u.", i); } } hr = MemFree(rgsczStrArray); - ExitOnFailure(hr, "Failed to free memory for the string array."); + StrExitOnFailure(hr, "Failed to free memory for the string array."); LExit: return hr; @@ -2667,12 +2682,12 @@ extern "C" HRESULT DAPI StrSplitAllocArray( // Copy wzSource so it is not modified. hr = StrAllocString(&sczCopy, wzSource, 0); - ExitOnFailure(hr, "Failed to copy the source string."); + StrExitOnFailure(hr, "Failed to copy the source string."); for (LPCWSTR wzToken = ::wcstok_s(sczCopy, wzDelim, &wzContext); wzToken; wzToken = ::wcstok_s(NULL, wzDelim, &wzContext)) { hr = StrArrayAllocString(prgsczStrArray, pcStrArray, wzToken, 0); - ExitOnFailure(hr, "Failed to add the string to the string array."); + StrExitOnFailure(hr, "Failed to add the string to the string array."); } LExit: @@ -2696,20 +2711,20 @@ static HRESULT StrAllocStringMapInvariant( HRESULT hr = S_OK; hr = StrAllocString(pscz, wzSource, cchSource); - ExitOnFailure(hr, "Failed to allocate a copy of the source string."); + StrExitOnFailure(hr, "Failed to allocate a copy of the source string."); if (0 == cchSource) { // Need the actual string size for LCMapString. This includes the null-terminator // but LCMapString doesn't care either way. hr = ::StringCchLengthW(*pscz, INT_MAX, reinterpret_cast(&cchSource)); - ExitOnFailure(hr, "Failed to get the length of the string."); + StrExitOnFailure(hr, "Failed to get the length of the string."); } // Convert the copy of the string to upper or lower case in-place. if (0 == ::LCMapStringW(LOCALE_INVARIANT, dwMapFlags, *pscz, cchSource, *pscz, cchSource)) { - ExitWithLastError(hr, "Failed to convert the string case."); + StrExitWithLastError(hr, "Failed to convert the string case."); } LExit: @@ -2734,7 +2749,7 @@ extern "C" DAPI_(HRESULT) StrSecureZeroString( if (-1 == cch) { hr = E_INVALIDARG; - ExitOnFailure(hr, "Failed to get size of string"); + StrExitOnFailure(hr, "Failed to get size of string"); } else { diff --git a/src/dutil/svcutil.cpp b/src/dutil/svcutil.cpp index 9da2b5b3..1a39bfee 100644 --- a/src/dutil/svcutil.cpp +++ b/src/dutil/svcutil.cpp @@ -2,6 +2,21 @@ #include "precomp.h" + +// Exit macros +#define SvcExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_SVCUTIL, x, s, __VA_ARGS__) +#define SvcExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_SVCUTIL, x, s, __VA_ARGS__) +#define SvcExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_SVCUTIL, x, s, __VA_ARGS__) +#define SvcExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_SVCUTIL, x, s, __VA_ARGS__) +#define SvcExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_SVCUTIL, x, s, __VA_ARGS__) +#define SvcExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_SVCUTIL, x, s, __VA_ARGS__) +#define SvcExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_SVCUTIL, p, x, e, s, __VA_ARGS__) +#define SvcExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_SVCUTIL, p, x, s, __VA_ARGS__) +#define SvcExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_SVCUTIL, p, x, e, s, __VA_ARGS__) +#define SvcExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_SVCUTIL, p, x, s, __VA_ARGS__) +#define SvcExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_SVCUTIL, e, x, s, __VA_ARGS__) +#define SvcExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_SVCUTIL, g, x, s, __VA_ARGS__) + /******************************************************************** SvcQueryConfig - queries the configuration of a service @@ -21,16 +36,16 @@ extern "C" HRESULT DAPI SvcQueryConfig( if (ERROR_INSUFFICIENT_BUFFER == er) { pConfig = static_cast(MemAlloc(cbConfig, TRUE)); - ExitOnNull(pConfig, hr, E_OUTOFMEMORY, "Failed to allocate memory to get configuration."); + SvcExitOnNull(pConfig, hr, E_OUTOFMEMORY, "Failed to allocate memory to get configuration."); if (!::QueryServiceConfigW(sch, pConfig, cbConfig, &cbConfig)) { - ExitWithLastError(hr, "Failed to read service configuration."); + SvcExitWithLastError(hr, "Failed to read service configuration."); } } else { - ExitOnWin32Error(er, hr, "Failed to query service configuration."); + SvcExitOnWin32Error(er, hr, "Failed to query service configuration."); } } diff --git a/src/dutil/thmutil.cpp b/src/dutil/thmutil.cpp index 9b9bf15e..d87e997d 100644 --- a/src/dutil/thmutil.cpp +++ b/src/dutil/thmutil.cpp @@ -693,7 +693,7 @@ DAPI_(HRESULT) ThemeCreateParentWindow( } LExit: - MemFree(pMonitorContext); + ReleaseMem(pMonitorContext); return hr; } @@ -1514,7 +1514,7 @@ LExit: DAPI_(HRESULT) ThemeGetTextControl( __in const THEME* pTheme, __in DWORD dwControl, - __out_z LPWSTR* psczText + __inout_z LPWSTR* psczText ) { HRESULT hr = S_OK; @@ -1729,6 +1729,7 @@ static HRESULT ParseImage( LPWSTR sczImageFile = NULL; int iResourceId = 0; Gdiplus::Bitmap* pBitmap = NULL; + *phImage = NULL; hr = XmlGetAttribute(pElement, L"ImageResource", &bstr); ThmExitOnFailure(hr, "Failed to get image resource attribute."); @@ -1801,6 +1802,7 @@ static HRESULT ParseIcon( BSTR bstr = NULL; LPWSTR sczImageFile = NULL; int iResourceId = 0; + *phIcon = NULL; hr = XmlGetAttribute(pElement, L"IconResource", &bstr); ThmExitOnFailure(hr, "Failed to get icon resource attribute."); @@ -4720,7 +4722,7 @@ static HRESULT ShowControl( hr = S_OK; - Button_SetCheck(hWnd, (!sczText && !pControl->sczValue) || CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, 0, sczText, -1, pControl->sczValue, -1)); + Button_SetCheck(hWnd, (!sczText && !pControl->sczValue) || (sczText && CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, 0, sczText, -1, pControl->sczValue, -1))); } } diff --git a/src/dutil/timeutil.cpp b/src/dutil/timeutil.cpp index dacb2660..b7953c94 100644 --- a/src/dutil/timeutil.cpp +++ b/src/dutil/timeutil.cpp @@ -2,6 +2,21 @@ #include "precomp.h" + +// Exit macros +#define TimeExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_TIMEUTIL, x, s, __VA_ARGS__) +#define TimeExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_TIMEUTIL, x, s, __VA_ARGS__) +#define TimeExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_TIMEUTIL, x, s, __VA_ARGS__) +#define TimeExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_TIMEUTIL, x, s, __VA_ARGS__) +#define TimeExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_TIMEUTIL, x, s, __VA_ARGS__) +#define TimeExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_TIMEUTIL, x, s, __VA_ARGS__) +#define TimeExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_TIMEUTIL, p, x, e, s, __VA_ARGS__) +#define TimeExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_TIMEUTIL, p, x, s, __VA_ARGS__) +#define TimeExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_TIMEUTIL, p, x, e, s, __VA_ARGS__) +#define TimeExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_TIMEUTIL, p, x, s, __VA_ARGS__) +#define TimeExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_TIMEUTIL, e, x, s, __VA_ARGS__) +#define TimeExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_TIMEUTIL, g, x, s, __VA_ARGS__) + const LPCWSTR DAY_OF_WEEK[] = { L"Sun", L"Mon", L"Tue", L"Wed", L"Thu", L"Fri", L"Sat" }; const LPCWSTR MONTH_OF_YEAR[] = { L"None", L"Jan", L"Feb", L"Mar", L"Apr", L"May", L"Jun", L"Jul", L"Aug", L"Sep", L"Oct", L"Nov", L"Dec" }; enum TIME_PARSER { DayOfWeek, DayOfMonth, MonthOfYear, Year, Hours, Minutes, Seconds, TimeZone }; @@ -39,7 +54,7 @@ extern "C" HRESULT DAPI TimeFromString( LPWSTR pwzEnd = NULL; hr = StrAllocString(&pwzTime, wzTime, 0); - ExitOnFailure(hr, "Failed to copy time."); + TimeExitOnFailure(hr, "Failed to copy time."); pwzStart = pwzEnd = pwzTime; while (pwzEnd && *pwzEnd) @@ -58,7 +73,7 @@ extern "C" HRESULT DAPI TimeFromString( { case DayOfWeek: hr = DayFromString(pwzStart, &sysTime.wDayOfWeek); - ExitOnFailure(hr, "Failed to convert string to day: %ls", pwzStart); + TimeExitOnFailure(hr, "Failed to convert string to day: %ls", pwzStart); break; case DayOfMonth: @@ -67,7 +82,7 @@ extern "C" HRESULT DAPI TimeFromString( case MonthOfYear: hr = MonthFromString(pwzStart, &sysTime.wMonth); - ExitOnFailure(hr, "Failed to convert to month: %ls", pwzStart); + TimeExitOnFailure(hr, "Failed to convert to month: %ls", pwzStart); break; case Year: @@ -104,7 +119,7 @@ extern "C" HRESULT DAPI TimeFromString( if (!::SystemTimeToFileTime(&sysTime, pFileTime)) { - ExitWithLastError(hr, "Failed to convert system time to file time."); + TimeExitWithLastError(hr, "Failed to convert system time to file time."); } LExit: @@ -134,7 +149,7 @@ extern "C" HRESULT DAPI TimeFromString3339( LPWSTR pwzEnd = NULL; hr = StrAllocString(&pwzTime, wzTime, 0); - ExitOnFailure(hr, "Failed to copy time."); + TimeExitOnFailure(hr, "Failed to copy time."); pwzStart = pwzEnd = pwzTime; while (pwzEnd && *pwzEnd) @@ -188,7 +203,7 @@ extern "C" HRESULT DAPI TimeFromString3339( if (!::SystemTimeToFileTime(&sysTime, pFileTime)) { - ExitWithLastError(hr, "Failed to convert system time to file time."); + TimeExitWithLastError(hr, "Failed to convert system time to file time."); } LExit: @@ -291,29 +306,29 @@ HRESULT DAPI TimeSystemToDateTimeString( iLenDate = ::GetDateFormatW(locale, 0, pst, DATE_FORMAT, NULL, 0); if (0 >= iLenDate) { - ExitWithLastError(hr, "Failed to get date format with NULL"); + TimeExitWithLastError(hr, "Failed to get date format with NULL"); } iLenTime = ::GetTimeFormatW(locale, 0, pst, TIME_FORMAT, NULL, 0); if (0 >= iLenTime) { - ExitWithLastError(hr, "Failed to get time format with NULL"); + TimeExitWithLastError(hr, "Failed to get time format with NULL"); } // Between both lengths we account for 2 null terminators, and only need one, so we subtract one hr = StrAlloc(ppwz, iLenDate + iLenTime - 1); - ExitOnFailure(hr, "Failed to allocate string"); + TimeExitOnFailure(hr, "Failed to allocate string"); if (!::GetDateFormatW(locale, 0, pst, DATE_FORMAT, *ppwz, iLenDate)) { - ExitWithLastError(hr, "Failed to get date format with buffer"); + TimeExitWithLastError(hr, "Failed to get date format with buffer"); } // Space to separate them (*ppwz)[iLenDate - 1] = ' '; if (!::GetTimeFormatW(locale, 0, pst, TIME_FORMAT, (*ppwz) + iLenDate - 1, iLenTime)) { - ExitWithLastError(hr, "Failed to get time format with buffer"); + TimeExitWithLastError(hr, "Failed to get time format with buffer"); } LExit: diff --git a/src/dutil/uncutil.cpp b/src/dutil/uncutil.cpp index 6deb43bd..415ea198 100644 --- a/src/dutil/uncutil.cpp +++ b/src/dutil/uncutil.cpp @@ -2,6 +2,21 @@ #include "precomp.h" + +// Exit macros +#define UncExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_UNCUTIL, x, s, __VA_ARGS__) +#define UncExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_UNCUTIL, x, s, __VA_ARGS__) +#define UncExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_UNCUTIL, x, s, __VA_ARGS__) +#define UncExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_UNCUTIL, x, s, __VA_ARGS__) +#define UncExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_UNCUTIL, x, s, __VA_ARGS__) +#define UncExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_UNCUTIL, x, s, __VA_ARGS__) +#define UncExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_UNCUTIL, p, x, e, s, __VA_ARGS__) +#define UncExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_UNCUTIL, p, x, s, __VA_ARGS__) +#define UncExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_UNCUTIL, p, x, e, s, __VA_ARGS__) +#define UncExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_UNCUTIL, p, x, s, __VA_ARGS__) +#define UncExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_UNCUTIL, e, x, s, __VA_ARGS__) +#define UncExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_UNCUTIL, g, x, s, __VA_ARGS__) + DAPI_(HRESULT) UncConvertFromMountedDrive( __inout LPWSTR *psczUNCPath, __in LPCWSTR sczMountedDrivePath @@ -14,7 +29,7 @@ DAPI_(HRESULT) UncConvertFromMountedDrive( // Only copy drive letter and colon hr = StrAllocString(&sczDrive, sczMountedDrivePath, 2); - ExitOnFailure(hr, "Failed to copy drive"); + UncExitOnFailure(hr, "Failed to copy drive"); // ERROR_NOT_CONNECTED means it's not a mapped drive er = ::WNetGetConnectionW(sczDrive, NULL, &dwLength); @@ -23,7 +38,7 @@ DAPI_(HRESULT) UncConvertFromMountedDrive( er = ERROR_SUCCESS; hr = StrAlloc(psczUNCPath, dwLength); - ExitOnFailure(hr, "Failed to allocate string to get raw UNC path of length %u", dwLength); + UncExitOnFailure(hr, "Failed to allocate string to get raw UNC path of length %u", dwLength); er = ::WNetGetConnectionW(sczDrive, *psczUNCPath, &dwLength); if (ERROR_CONNECTION_UNAVAIL == er) @@ -31,11 +46,11 @@ DAPI_(HRESULT) UncConvertFromMountedDrive( // This means the drive is remembered but not currently connected, this can mean the location is accessible via UNC path but not via mounted drive path er = ERROR_SUCCESS; } - ExitOnWin32Error(er, hr, "::WNetGetConnectionW() failed with buffer provided on drive %ls", sczDrive); + UncExitOnWin32Error(er, hr, "::WNetGetConnectionW() failed with buffer provided on drive %ls", sczDrive); // Skip drive letter and colon hr = StrAllocConcat(psczUNCPath, sczMountedDrivePath + 2, 0); - ExitOnFailure(hr, "Failed to copy rest of database path"); + UncExitOnFailure(hr, "Failed to copy rest of database path"); } else { @@ -44,7 +59,7 @@ DAPI_(HRESULT) UncConvertFromMountedDrive( er = ERROR_NO_DATA; } - ExitOnWin32Error(er, hr, "::WNetGetConnectionW() failed on drive %ls", sczDrive); + UncExitOnWin32Error(er, hr, "::WNetGetConnectionW() failed on drive %ls", sczDrive); } LExit: diff --git a/src/dutil/uriutil.cpp b/src/dutil/uriutil.cpp index fc192b3f..7913c22e 100644 --- a/src/dutil/uriutil.cpp +++ b/src/dutil/uriutil.cpp @@ -3,6 +3,21 @@ #include "precomp.h" +// Exit macros +#define UriExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_URIUTIL, x, s, __VA_ARGS__) +#define UriExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_URIUTIL, x, s, __VA_ARGS__) +#define UriExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_URIUTIL, x, s, __VA_ARGS__) +#define UriExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_URIUTIL, x, s, __VA_ARGS__) +#define UriExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_URIUTIL, x, s, __VA_ARGS__) +#define UriExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_URIUTIL, x, s, __VA_ARGS__) +#define UriExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_URIUTIL, p, x, e, s, __VA_ARGS__) +#define UriExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_URIUTIL, p, x, s, __VA_ARGS__) +#define UriExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_URIUTIL, p, x, e, s, __VA_ARGS__) +#define UriExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_URIUTIL, p, x, s, __VA_ARGS__) +#define UriExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_URIUTIL, e, x, s, __VA_ARGS__) +#define UriExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_URIUTIL, g, x, s, __VA_ARGS__) + + // // UriCanonicalize - canonicalizes a URI. // @@ -16,11 +31,11 @@ extern "C" HRESULT DAPI UriCanonicalize( if (!::InternetCanonicalizeUrlW(*psczUri, wz, &cch, ICU_DECODE)) { - ExitWithLastError(hr, "Failed to canonicalize URI."); + UriExitWithLastError(hr, "Failed to canonicalize URI."); } hr = StrAllocString(psczUri, wz, cch); - ExitOnFailure(hr, "Failed copy canonicalized URI."); + UriExitOnFailure(hr, "Failed copy canonicalized URI."); LExit: return hr; @@ -83,7 +98,7 @@ extern "C" HRESULT DAPI UriCrack( if (!::InternetCrackUrlW(wzUri, 0, ICU_DECODE | ICU_ESCAPE, &components)) { - ExitWithLastError(hr, "Failed to crack URI."); + UriExitWithLastError(hr, "Failed to crack URI."); } if (pScheme) @@ -94,7 +109,7 @@ extern "C" HRESULT DAPI UriCrack( if (psczHostName) { hr = StrAllocString(psczHostName, components.lpszHostName, components.dwHostNameLength); - ExitOnFailure(hr, "Failed to copy host name."); + UriExitOnFailure(hr, "Failed to copy host name."); } if (pPort) @@ -105,25 +120,25 @@ extern "C" HRESULT DAPI UriCrack( if (psczUser) { hr = StrAllocString(psczUser, components.lpszUserName, components.dwUserNameLength); - ExitOnFailure(hr, "Failed to copy user name."); + UriExitOnFailure(hr, "Failed to copy user name."); } if (psczPassword) { hr = StrAllocString(psczPassword, components.lpszPassword, components.dwPasswordLength); - ExitOnFailure(hr, "Failed to copy password."); + UriExitOnFailure(hr, "Failed to copy password."); } if (psczPath) { hr = StrAllocString(psczPath, components.lpszUrlPath, components.dwUrlPathLength); - ExitOnFailure(hr, "Failed to copy path."); + UriExitOnFailure(hr, "Failed to copy path."); } if (psczQueryString) { hr = StrAllocString(psczQueryString, components.lpszExtraInfo, components.dwExtraInfoLength); - ExitOnFailure(hr, "Failed to copy query string."); + UriExitOnFailure(hr, "Failed to copy query string."); } LExit: @@ -142,7 +157,7 @@ extern "C" HRESULT DAPI UriCrackEx( HRESULT hr = S_OK; hr = UriCrack(wzUri, &pUriInfo->scheme, &pUriInfo->sczHostName, &pUriInfo->port, &pUriInfo->sczUser, &pUriInfo->sczPassword, &pUriInfo->sczPath, &pUriInfo->sczQueryString); - ExitOnFailure(hr, "Failed to crack URI."); + UriExitOnFailure(hr, "Failed to crack URI."); LExit: return hr; @@ -195,11 +210,11 @@ extern "C" HRESULT DAPI UriCreate( if (!::InternetCreateUrlW(&components, ICU_ESCAPE, wz, &cch)) { - ExitWithLastError(hr, "Failed to create URI."); + UriExitWithLastError(hr, "Failed to create URI."); } hr = StrAllocString(psczUri, wz, cch); - ExitOnFailure(hr, "Failed copy created URI."); + UriExitOnFailure(hr, "Failed copy created URI."); LExit: return hr; @@ -227,13 +242,13 @@ extern "C" HRESULT DAPI UriGetServerAndResource( LPWSTR sczQueryString = NULL; hr = UriCrack(wzUri, &scheme, &sczHostName, &port, &sczUser, &sczPassword, &sczPath, &sczQueryString); - ExitOnFailure(hr, "Failed to crack URI."); + UriExitOnFailure(hr, "Failed to crack URI."); hr = UriCreate(psczServer, scheme, sczHostName, port, sczUser, sczPassword, NULL, NULL); - ExitOnFailure(hr, "Failed to allocate server URI."); + UriExitOnFailure(hr, "Failed to allocate server URI."); hr = UriCreate(psczResource, INTERNET_SCHEME_UNKNOWN, NULL, INTERNET_INVALID_PORT_NUMBER, NULL, NULL, sczPath, sczQueryString); - ExitOnFailure(hr, "Failed to allocate resource URI."); + UriExitOnFailure(hr, "Failed to allocate resource URI."); LExit: ReleaseStr(sczQueryString); @@ -265,13 +280,13 @@ extern "C" HRESULT DAPI UriFile( if (!::InternetCrackUrlW(wzUri, 0, ICU_DECODE | ICU_ESCAPE, &uc)) { - ExitWithLastError(hr, "Failed to crack URI."); + UriExitWithLastError(hr, "Failed to crack URI."); } // Copy only the file name. Fortunately, PathFile() understands that // forward slashes can be directory separators like backslashes. hr = StrAllocString(psczFile, PathFile(wz), 0); - ExitOnFailure(hr, "Failed to copy file name"); + UriExitOnFailure(hr, "Failed to copy file name"); LExit: return hr; @@ -367,7 +382,7 @@ extern "C" HRESULT DAPI UriRoot( LPCWSTR pwcSlash = NULL; hr = UriProtocol(wzUri, &protocol); - ExitOnFailure(hr, "Invalid URI."); + UriExitOnFailure(hr, "Invalid URI."); switch (protocol) { @@ -377,7 +392,7 @@ extern "C" HRESULT DAPI UriRoot( if (((L'a' <= wzUri[8] && L'z' >= wzUri[8]) || (L'A' <= wzUri[8] && L'Z' >= wzUri[8])) && L':' == wzUri[9]) { hr = StrAlloc(ppwzRoot, 4); - ExitOnFailure(hr, "Failed to allocate string for root of URI."); + UriExitOnFailure(hr, "Failed to allocate string for root of URI."); *ppwzRoot[0] = wzUri[8]; *ppwzRoot[1] = L':'; *ppwzRoot[2] = L'\\'; @@ -386,7 +401,7 @@ extern "C" HRESULT DAPI UriRoot( else { hr = E_INVALIDARG; - ExitOnFailure(hr, "Invalid file path in URI."); + UriExitOnFailure(hr, "Invalid file path in URI."); } } else // UNC share @@ -395,23 +410,23 @@ extern "C" HRESULT DAPI UriRoot( if (!pwcSlash) { hr = E_INVALIDARG; - ExitOnFailure(hr, "Invalid server name in URI."); + UriExitOnFailure(hr, "Invalid server name in URI."); } else { hr = StrAllocString(ppwzRoot, L"\\\\", 64); - ExitOnFailure(hr, "Failed to allocate string for root of URI."); + UriExitOnFailure(hr, "Failed to allocate string for root of URI."); pwcSlash = wcschr(pwcSlash + 1, L'/'); if (pwcSlash) { hr = StrAllocConcat(ppwzRoot, wzUri + 8, pwcSlash - wzUri - 8); - ExitOnFailure(hr, "Failed to add server/share to root of URI."); + UriExitOnFailure(hr, "Failed to add server/share to root of URI."); } else { hr = StrAllocConcat(ppwzRoot, wzUri + 8, 0); - ExitOnFailure(hr, "Failed to add server/share to root of URI."); + UriExitOnFailure(hr, "Failed to add server/share to root of URI."); } // replace all slashes with backslashes to be truly UNC. @@ -431,12 +446,12 @@ extern "C" HRESULT DAPI UriRoot( if (pwcSlash) { hr = StrAllocString(ppwzRoot, wzUri, pwcSlash - wzUri); - ExitOnFailure(hr, "Failed allocate root from URI."); + UriExitOnFailure(hr, "Failed allocate root from URI."); } else { hr = StrAllocString(ppwzRoot, wzUri, 0); - ExitOnFailure(hr, "Failed allocate root from URI."); + UriExitOnFailure(hr, "Failed allocate root from URI."); } break; @@ -445,18 +460,18 @@ extern "C" HRESULT DAPI UriRoot( if (pwcSlash) { hr = StrAllocString(ppwzRoot, wzUri, pwcSlash - wzUri); - ExitOnFailure(hr, "Failed allocate root from URI."); + UriExitOnFailure(hr, "Failed allocate root from URI."); } else { hr = StrAllocString(ppwzRoot, wzUri, 0); - ExitOnFailure(hr, "Failed allocate root from URI."); + UriExitOnFailure(hr, "Failed allocate root from URI."); } break; default: hr = E_INVALIDARG; - ExitOnFailure(hr, "Unknown URI protocol."); + UriExitOnFailure(hr, "Unknown URI protocol."); } if (pProtocol) @@ -473,7 +488,7 @@ extern "C" HRESULT DAPI UriResolve( __in_z LPCWSTR wzUri, __in_opt LPCWSTR wzBaseUri, __out LPWSTR* ppwzResolvedUri, - __out_opt const URI_PROTOCOL* pResolvedProtocol + __out_opt URI_PROTOCOL* pResolvedProtocol ) { UNREFERENCED_PARAMETER(wzUri); @@ -486,45 +501,45 @@ extern "C" HRESULT DAPI UriResolve( URI_PROTOCOL protocol = URI_PROTOCOL_UNKNOWN; hr = UriProtocol(wzUri, &protocol); - ExitOnFailure(hr, "Failed to determine protocol for URL: %ls", wzUri); + UriExitOnFailure(hr, "Failed to determine protocol for URL: %ls", wzUri); - ExitOnNull(ppwzResolvedUri, hr, E_INVALIDARG, "Failed to resolve URI, because no method of output was provided"); + UriExitOnNull(ppwzResolvedUri, hr, E_INVALIDARG, "Failed to resolve URI, because no method of output was provided"); if (URI_PROTOCOL_UNKNOWN == protocol) { - ExitOnNull(wzBaseUri, hr, E_INVALIDARG, "Failed to resolve URI - base URI provided was NULL"); + UriExitOnNull(wzBaseUri, hr, E_INVALIDARG, "Failed to resolve URI - base URI provided was NULL"); if (L'/' == *wzUri || L'\\' == *wzUri) { hr = UriRoot(wzBaseUri, ppwzResolvedUri, &protocol); - ExitOnFailure(hr, "Failed to get root from URI: %ls", wzBaseUri); + UriExitOnFailure(hr, "Failed to get root from URI: %ls", wzBaseUri); hr = StrAllocConcat(ppwzResolvedUri, wzUri, 0); - ExitOnFailure(hr, "Failed to concat file to base URI."); + UriExitOnFailure(hr, "Failed to concat file to base URI."); } else { hr = UriProtocol(wzBaseUri, &protocol); - ExitOnFailure(hr, "Failed to get protocol of base URI: %ls", wzBaseUri); + UriExitOnFailure(hr, "Failed to get protocol of base URI: %ls", wzBaseUri); LPCWSTR pwcFile = const_cast (UriFile(wzBaseUri)); if (!pwcFile) { hr = E_INVALIDARG; - ExitOnFailure(hr, "Failed to get file from base URI: %ls", wzBaseUri); + UriExitOnFailure(hr, "Failed to get file from base URI: %ls", wzBaseUri); } hr = StrAllocString(ppwzResolvedUri, wzBaseUri, pwcFile - wzBaseUri); - ExitOnFailure(hr, "Failed to allocate string for resolved URI."); + UriExitOnFailure(hr, "Failed to allocate string for resolved URI."); hr = StrAllocConcat(ppwzResolvedUri, wzUri, 0); - ExitOnFailure(hr, "Failed to concat file to resolved URI."); + UriExitOnFailure(hr, "Failed to concat file to resolved URI."); } } else { hr = StrAllocString(ppwzResolvedUri, wzUri, 0); - ExitOnFailure(hr, "Failed to copy resolved URI."); + UriExitOnFailure(hr, "Failed to copy resolved URI."); } if (pResolvedProtocol) diff --git a/src/dutil/userutil.cpp b/src/dutil/userutil.cpp index 2e77f1df..ca6d5480 100644 --- a/src/dutil/userutil.cpp +++ b/src/dutil/userutil.cpp @@ -2,6 +2,21 @@ #include "precomp.h" + +// UserExit macros +#define UserExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_USERUTIL, x, s, __VA_ARGS__) +#define UserExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_USERUTIL, x, s, __VA_ARGS__) +#define UserExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_USERUTIL, x, s, __VA_ARGS__) +#define UserExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_USERUTIL, x, s, __VA_ARGS__) +#define UserExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_USERUTIL, x, s, __VA_ARGS__) +#define UserExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_USERUTIL, x, s, __VA_ARGS__) +#define UserExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_USERUTIL, p, x, e, s, __VA_ARGS__) +#define UserExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_USERUTIL, p, x, s, __VA_ARGS__) +#define UserExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_USERUTIL, p, x, e, s, __VA_ARGS__) +#define UserExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_USERUTIL, p, x, s, __VA_ARGS__) +#define UserExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_USERUTIL, e, x, s, __VA_ARGS__) +#define UserExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_USERUTIL, g, x, s, __VA_ARGS__) + static BOOL CheckIsMemberHelper( __in_z LPCWSTR pwzGroupUserDomain, __in_ecount(cguiGroupData) const GROUP_USERS_INFO_0 *pguiGroupData, @@ -29,14 +44,14 @@ extern "C" HRESULT DAPI UserBuildDomainUserName( if (cch >= cchLeft) { hr = ERROR_MORE_DATA; - ExitOnFailure(hr, "Buffer size is not big enough to hold domain name: %ls", pwzDomain); + UserExitOnFailure(hr, "Buffer size is not big enough to hold domain name: %ls", pwzDomain); } else if (cch > 0) { // handle the domain case hr = ::StringCchCopyNW(pwz, cchWz, pwzDomain, cchLeft - 1); // last parameter does not include '\0' - ExitOnFailure(hr, "Failed to copy Domain onto string."); + UserExitOnFailure(hr, "Failed to copy Domain onto string."); cchLeft -= cch; pwz += cch; @@ -45,11 +60,11 @@ extern "C" HRESULT DAPI UserBuildDomainUserName( if (1 >= cchLeft) { hr = ERROR_MORE_DATA; - ExitOnFailure(hr, "Insufficient buffer size while building domain user name"); + UserExitOnFailure(hr, "Insufficient buffer size while building domain user name"); } hr = ::StringCchCopyNW(pwz, cchWz, L"\\", cchLeft - 1); // last parameter does not include '\0' - ExitOnFailure(hr, "Failed to copy backslash onto string."); + UserExitOnFailure(hr, "Failed to copy backslash onto string."); --cchLeft; ++pwz; @@ -60,11 +75,11 @@ extern "C" HRESULT DAPI UserBuildDomainUserName( if (cch >= cchLeft) { hr = ERROR_MORE_DATA; - ExitOnFailure(hr, "Buffer size is not big enough to hold user name: %ls", pwzName); + UserExitOnFailure(hr, "Buffer size is not big enough to hold user name: %ls", pwzName); } hr = ::StringCchCopyNW(pwz, cchWz, pwzName, cchLeft - 1); // last parameter does not include '\0' - ExitOnFailure(hr, "Failed to copy User name onto string."); + UserExitOnFailure(hr, "Failed to copy User name onto string."); LExit: return hr; @@ -98,10 +113,10 @@ extern "C" HRESULT DAPI UserCheckIsMember( VARIANT_BOOL vtBoolResult = VARIANT_FALSE; hr = UserBuildDomainUserName(wzGroupUserDomain, countof(wzGroupUserDomain), pwzGroupName, pwzGroupDomain); - ExitOnFailure(hr, "Failed to build group name from group domain %ls, group name %ls", pwzGroupDomain, pwzGroupName); + UserExitOnFailure(hr, "Failed to build group name from group domain %ls, group name %ls", pwzGroupDomain, pwzGroupName); hr = UserBuildDomainUserName(wzUserDomain, countof(wzUserDomain), pwzName, pwzDomain); - ExitOnFailure(hr, "Failed to build group name from group domain %ls, group name %ls", pwzGroupDomain, pwzGroupName); + UserExitOnFailure(hr, "Failed to build group name from group domain %ls, group name %ls", pwzGroupDomain, pwzGroupName); if (pwzDomain && *pwzDomain) { @@ -115,12 +130,12 @@ extern "C" HRESULT DAPI UserCheckIsMember( Trace(REPORT_VERBOSE, "failed to get groups for user %ls from domain %ls with error code 0x%x - continuing", pwzName, (wz != NULL) ? wz : L"", HRESULT_FROM_WIN32(er)); er = ERROR_SUCCESS; } - ExitOnWin32Error(er, hr, "Failed to get list of global groups for user while checking group membership information for user: %ls", pwzName); + UserExitOnWin32Error(er, hr, "Failed to get list of global groups for user while checking group membership information for user: %ls", pwzName); if (dwRead != dwTotal) { hr = HRESULT_FROM_WIN32(ERROR_MORE_DATA); - ExitOnRootFailure(hr, "Failed to get entire list of groups (global) for user while checking group membership information for user: %ls", pwzName); + UserExitOnRootFailure(hr, "Failed to get entire list of groups (global) for user while checking group membership information for user: %ls", pwzName); } if (CheckIsMemberHelper(wzGroupUserDomain, pguiGroupData, dwRead)) @@ -143,12 +158,12 @@ extern "C" HRESULT DAPI UserCheckIsMember( Trace(REPORT_VERBOSE, "failed to get local groups for user %ls from domain %ls with error code 0x%x - continuing", pwzName, (wz != NULL) ? wz : L"", HRESULT_FROM_WIN32(er)); er = ERROR_SUCCESS; } - ExitOnWin32Error(er, hr, "Failed to get list of groups for user while checking group membership information for user: %ls", pwzName); + UserExitOnWin32Error(er, hr, "Failed to get list of groups for user while checking group membership information for user: %ls", pwzName); if (dwRead != dwTotal) { hr = HRESULT_FROM_WIN32(ERROR_MORE_DATA); - ExitOnRootFailure(hr, "Failed to get entire list of groups (local) for user while checking group membership information for user: %ls", pwzName); + UserExitOnRootFailure(hr, "Failed to get entire list of groups (local) for user while checking group membership information for user: %ls", pwzName); } if (CheckIsMemberHelper(wzGroupUserDomain, pguiGroupData, dwRead)) @@ -159,18 +174,18 @@ extern "C" HRESULT DAPI UserCheckIsMember( // If the above methods failed, let's try active directory hr = UserCreateADsPath(pwzDomain, pwzName, &bstrUser); - ExitOnFailure(hr, "failed to create user ADsPath in order to check group membership for group: %ls domain: %ls", pwzName, pwzDomain); + UserExitOnFailure(hr, "failed to create user ADsPath in order to check group membership for group: %ls domain: %ls", pwzName, pwzDomain); hr = UserCreateADsPath(pwzGroupDomain, pwzGroupName, &bstrGroup); - ExitOnFailure(hr, "failed to create group ADsPath in order to check group membership for group: %ls domain: %ls", pwzGroupName, pwzGroupDomain); + UserExitOnFailure(hr, "failed to create group ADsPath in order to check group membership for group: %ls domain: %ls", pwzGroupName, pwzGroupDomain); if (lstrlenW(pwzGroupDomain) > 0) { hr = ::ADsGetObject(bstrGroup, IID_IADsGroup, reinterpret_cast(&pGroup)); - ExitOnFailure(hr, "Failed to get group '%ls' from active directory.", reinterpret_cast(bstrGroup) ); + UserExitOnFailure(hr, "Failed to get group '%ls' from active directory.", reinterpret_cast(bstrGroup) ); hr = pGroup->IsMember(bstrUser, &vtBoolResult); - ExitOnFailure(hr, "Failed to check if user %ls is a member of group '%ls' using active directory.", reinterpret_cast(bstrUser), reinterpret_cast(bstrGroup) ); + UserExitOnFailure(hr, "Failed to check if user %ls is a member of group '%ls' using active directory.", reinterpret_cast(bstrUser), reinterpret_cast(bstrGroup) ); } if (vtBoolResult) @@ -180,10 +195,10 @@ extern "C" HRESULT DAPI UserCheckIsMember( } hr = ::ADsGetObject(bstrGroup, IID_IADsGroup, reinterpret_cast(&pGroup)); - ExitOnFailure(hr, "Failed to get group '%ls' from active directory.", reinterpret_cast(bstrGroup) ); + UserExitOnFailure(hr, "Failed to get group '%ls' from active directory.", reinterpret_cast(bstrGroup) ); hr = pGroup->IsMember(bstrUser, &vtBoolResult); - ExitOnFailure(hr, "Failed to check if user %ls is a member of group '%ls' using active directory.", reinterpret_cast(bstrUser), reinterpret_cast(bstrGroup) ); + UserExitOnFailure(hr, "Failed to check if user %ls is a member of group '%ls' using active directory.", reinterpret_cast(bstrUser), reinterpret_cast(bstrGroup) ); if (vtBoolResult) { @@ -222,25 +237,25 @@ extern "C" HRESULT DAPI UserCreateADsPath( LPWSTR pwzAdsPath = NULL; hr = StrAllocString(&pwzAdsPath, L"WinNT://", 0); - ExitOnFailure(hr, "failed to allocate AdsPath string"); + UserExitOnFailure(hr, "failed to allocate AdsPath string"); if (*wzObjectDomain) { hr = StrAllocFormatted(&pwzAdsPath, L"%s/%s", wzObjectDomain, wzObjectName); - ExitOnFailure(hr, "failed to allocate AdsPath string"); + UserExitOnFailure(hr, "failed to allocate AdsPath string"); } else if (NULL != wcsstr(wzObjectName, L"\\") || NULL != wcsstr(wzObjectName, L"/")) { hr = StrAllocConcat(&pwzAdsPath, wzObjectName, 0); - ExitOnFailure(hr, "failed to concat objectname: %ls", wzObjectName); + UserExitOnFailure(hr, "failed to concat objectname: %ls", wzObjectName); } else { hr = StrAllocConcat(&pwzAdsPath, L"Localhost/", 0); - ExitOnFailure(hr, "failed to concat LocalHost/"); + UserExitOnFailure(hr, "failed to concat LocalHost/"); hr = StrAllocConcat(&pwzAdsPath, wzObjectName, 0); - ExitOnFailure(hr, "failed to concat object name: %ls", wzObjectName); + UserExitOnFailure(hr, "failed to concat object name: %ls", wzObjectName); } *pbstrAdsPath = ::SysAllocString(pwzAdsPath); diff --git a/src/dutil/wiutil.cpp b/src/dutil/wiutil.cpp index 7336d685..ffbfe85a 100644 --- a/src/dutil/wiutil.cpp +++ b/src/dutil/wiutil.cpp @@ -3,6 +3,21 @@ #include "precomp.h" +// Exit macros +#define WiuExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_WIUTIL, x, s, __VA_ARGS__) +#define WiuExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_WIUTIL, x, s, __VA_ARGS__) +#define WiuExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_WIUTIL, x, s, __VA_ARGS__) +#define WiuExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_WIUTIL, x, s, __VA_ARGS__) +#define WiuExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_WIUTIL, x, s, __VA_ARGS__) +#define WiuExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_WIUTIL, x, s, __VA_ARGS__) +#define WiuExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_WIUTIL, p, x, e, s, __VA_ARGS__) +#define WiuExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_WIUTIL, p, x, s, __VA_ARGS__) +#define WiuExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_WIUTIL, p, x, e, s, __VA_ARGS__) +#define WiuExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_WIUTIL, p, x, s, __VA_ARGS__) +#define WiuExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_WIUTIL, e, x, s, __VA_ARGS__) +#define WiuExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_WIUTIL, g, x, s, __VA_ARGS__) + + // constants const DWORD WIU_MSI_PROGRESS_INVALID = 0xFFFFFFFF; @@ -112,8 +127,8 @@ static DWORD CalculatePhaseProgress( __in DWORD dwWeightPercentage ); void InitializeMessageData( - __in MSIHANDLE hRecord, - __out LPWSTR** prgsczData, + __in_opt MSIHANDLE hRecord, + __deref_out_ecount(*pcData) LPWSTR** prgsczData, __out DWORD* pcData ); void UninitializeMessageData( @@ -133,7 +148,7 @@ extern "C" HRESULT DAPI WiuInitialize( LPWSTR sczMsiDllPath = NULL; hr = LoadSystemLibraryWithPath(L"Msi.dll", &vhMsiDll, &sczMsiDllPath); - ExitOnFailure(hr, "Failed to load Msi.DLL"); + WiuExitOnFailure(hr, "Failed to load Msi.DLL"); // Ignore failures FileVersion(sczMsiDllPath, &vdwMsiDllMajorMinor, &vdwMsiDllBuildRevision); @@ -275,7 +290,7 @@ extern "C" HRESULT DAPI WiuGetComponentPath( DWORD cchCompare; hr = StrAlloc(psczValue, cch); - ExitOnFailure(hr, "Failed to allocate string for component path."); + WiuExitOnFailure(hr, "Failed to allocate string for component path."); cchCompare = cch; *pInstallState = vpfnMsiGetComponentPathW(wzProductCode, wzComponentId, *psczValue, &cch); @@ -283,7 +298,7 @@ extern "C" HRESULT DAPI WiuGetComponentPath( { ++cch; hr = StrAlloc(psczValue, cch); - ExitOnFailure(hr, "Failed to reallocate string for component path."); + WiuExitOnFailure(hr, "Failed to reallocate string for component path."); cchCompare = cch; *pInstallState = vpfnMsiGetComponentPathW(wzProductCode, wzComponentId, *psczValue, &cch); @@ -292,7 +307,7 @@ extern "C" HRESULT DAPI WiuGetComponentPath( if (INSTALLSTATE_INVALIDARG == *pInstallState) { hr = E_INVALIDARG; - ExitOnRootFailure(hr, "Invalid argument when getting component path."); + WiuExitOnRootFailure(hr, "Invalid argument when getting component path."); } else if (INSTALLSTATE_UNKNOWN == *pInstallState) { @@ -306,7 +321,7 @@ extern "C" HRESULT DAPI WiuGetComponentPath( { ++cch; hr = StrAlloc(psczValue, cch); - ExitOnFailure(hr, "Failed to reallocate string for component path."); + WiuExitOnFailure(hr, "Failed to reallocate string for component path."); *pInstallState = vpfnMsiGetComponentPathW(wzProductCode, wzComponentId, *psczValue, &cch); } @@ -327,7 +342,7 @@ extern "C" HRESULT DAPI WiuLocateComponent( DWORD cchCompare; hr = StrAlloc(psczValue, cch); - ExitOnFailure(hr, "Failed to allocate string for component path."); + WiuExitOnFailure(hr, "Failed to allocate string for component path."); cchCompare = cch; *pInstallState = vpfnMsiLocateComponentW(wzComponentId, *psczValue, &cch); @@ -335,7 +350,7 @@ extern "C" HRESULT DAPI WiuLocateComponent( { ++cch; hr = StrAlloc(psczValue, cch); - ExitOnFailure(hr, "Failed to reallocate string for component path."); + WiuExitOnFailure(hr, "Failed to reallocate string for component path."); cchCompare = cch; *pInstallState = vpfnMsiLocateComponentW(wzComponentId, *psczValue, &cch); @@ -344,7 +359,7 @@ extern "C" HRESULT DAPI WiuLocateComponent( if (INSTALLSTATE_INVALIDARG == *pInstallState) { hr = E_INVALIDARG; - ExitOnRootFailure(hr, "Invalid argument when locating component."); + WiuExitOnRootFailure(hr, "Invalid argument when locating component."); } else if (INSTALLSTATE_UNKNOWN == *pInstallState) { @@ -358,7 +373,7 @@ extern "C" HRESULT DAPI WiuLocateComponent( { ++cch; hr = StrAlloc(psczValue, cch); - ExitOnFailure(hr, "Failed to reallocate string for component path."); + WiuExitOnFailure(hr, "Failed to reallocate string for component path."); *pInstallState = vpfnMsiLocateComponentW(wzComponentId, *psczValue, &cch); } @@ -380,7 +395,7 @@ extern "C" HRESULT DAPI WiuQueryFeatureState( if (INSTALLSTATE_INVALIDARG == *pInstallState) { hr = E_INVALIDARG; - ExitOnRootFailure(hr, "Failed to query state of feature: %ls in product: %ls", wzFeature, wzProduct); + WiuExitOnRootFailure(hr, "Failed to query state of feature: %ls in product: %ls", wzFeature, wzProduct); } LExit: @@ -399,18 +414,18 @@ extern "C" HRESULT DAPI WiuGetProductInfo( DWORD cch = WIU_GOOD_ENOUGH_PROPERTY_LENGTH; hr = StrAlloc(psczValue, cch); - ExitOnFailure(hr, "Failed to allocate string for product info."); + WiuExitOnFailure(hr, "Failed to allocate string for product info."); er = vpfnMsiGetProductInfoW(wzProductCode, wzProperty, *psczValue, &cch); if (ERROR_MORE_DATA == er) { ++cch; hr = StrAlloc(psczValue, cch); - ExitOnFailure(hr, "Failed to reallocate string for product info."); + WiuExitOnFailure(hr, "Failed to reallocate string for product info."); er = vpfnMsiGetProductInfoW(wzProductCode, wzProperty, *psczValue, &cch); } - ExitOnWin32Error(er, hr, "Failed to get product info."); + WiuExitOnWin32Error(er, hr, "Failed to get product info."); LExit: return hr; @@ -432,24 +447,24 @@ extern "C" HRESULT DAPI WiuGetProductInfoEx( if (!vpfnMsiGetProductInfoExW) { hr = WiuGetProductInfo(wzProductCode, wzProperty, psczValue); - ExitOnFailure(hr, "Failed to get product info when extended info was not available."); + WiuExitOnFailure(hr, "Failed to get product info when extended info was not available."); ExitFunction(); } hr = StrAlloc(psczValue, cch); - ExitOnFailure(hr, "Failed to allocate string for extended product info."); + WiuExitOnFailure(hr, "Failed to allocate string for extended product info."); er = vpfnMsiGetProductInfoExW(wzProductCode, wzUserSid, dwContext, wzProperty, *psczValue, &cch); if (ERROR_MORE_DATA == er) { ++cch; hr = StrAlloc(psczValue, cch); - ExitOnFailure(hr, "Failed to reallocate string for extended product info."); + WiuExitOnFailure(hr, "Failed to reallocate string for extended product info."); er = vpfnMsiGetProductInfoExW(wzProductCode, wzUserSid, dwContext, wzProperty, *psczValue, &cch); } - ExitOnWin32Error(er, hr, "Failed to get extended product info."); + WiuExitOnWin32Error(er, hr, "Failed to get extended product info."); LExit: return hr; @@ -467,18 +482,18 @@ extern "C" HRESULT DAPI WiuGetProductProperty( DWORD cch = WIU_GOOD_ENOUGH_PROPERTY_LENGTH; hr = StrAlloc(psczValue, cch); - ExitOnFailure(hr, "Failed to allocate string for product property."); + WiuExitOnFailure(hr, "Failed to allocate string for product property."); er = ::MsiGetProductPropertyW(hProduct, wzProperty, *psczValue, &cch); if (ERROR_MORE_DATA == er) { ++cch; hr = StrAlloc(psczValue, cch); - ExitOnFailure(hr, "Failed to reallocate string for product property."); + WiuExitOnFailure(hr, "Failed to reallocate string for product property."); er = ::MsiGetProductPropertyW(hProduct, wzProperty, *psczValue, &cch); } - ExitOnWin32Error(er, hr, "Failed to get product property."); + WiuExitOnWin32Error(er, hr, "Failed to get product property."); LExit: return hr; @@ -504,18 +519,18 @@ extern "C" HRESULT DAPI WiuGetPatchInfoEx( } hr = StrAlloc(psczValue, cch); - ExitOnFailure(hr, "Failed to allocate string for extended patch info."); + WiuExitOnFailure(hr, "Failed to allocate string for extended patch info."); er = vpfnMsiGetPatchInfoExW(wzPatchCode, wzProductCode, wzUserSid, dwContext, wzProperty, *psczValue, &cch); if (ERROR_MORE_DATA == er) { ++cch; hr = StrAlloc(psczValue, cch); - ExitOnFailure(hr, "Failed to reallocate string for extended patch info."); + WiuExitOnFailure(hr, "Failed to reallocate string for extended patch info."); er = vpfnMsiGetPatchInfoExW(wzPatchCode, wzProductCode, wzUserSid, dwContext, wzProperty, *psczValue, &cch); } - ExitOnWin32Error(er, hr, "Failed to get extended patch info."); + WiuExitOnWin32Error(er, hr, "Failed to get extended patch info."); LExit: return hr; @@ -539,7 +554,7 @@ extern "C" HRESULT DAPI WiuDeterminePatchSequence( } er = vpfnMsiDeterminePatchSequenceW(wzProductCode, wzUserSid, context, cPatchInfo, pPatchInfo); - ExitOnWin32Error(er, hr, "Failed to determine patch sequence for product code."); + WiuExitOnWin32Error(er, hr, "Failed to determine patch sequence for product code."); LExit: return hr; @@ -561,7 +576,7 @@ extern "C" HRESULT DAPI WiuDetermineApplicablePatches( } er = vpfnMsiDetermineApplicablePatchesW(wzProductPackagePath, cPatchInfo, pPatchInfo); - ExitOnWin32Error(er, hr, "Failed to determine applicable patches for product package."); + WiuExitOnWin32Error(er, hr, "Failed to determine applicable patches for product package."); LExit: return hr; @@ -581,7 +596,7 @@ extern "C" HRESULT DAPI WiuEnumProducts( { ExitFunction1(hr = HRESULT_FROM_WIN32(er)); } - ExitOnWin32Error(er, hr, "Failed to enumerate products."); + WiuExitOnWin32Error(er, hr, "Failed to enumerate products."); LExit: return hr; @@ -612,7 +627,7 @@ extern "C" HRESULT DAPI WiuEnumProductsEx( { ExitFunction1(hr = HRESULT_FROM_WIN32(er)); } - ExitOnWin32Error(er, hr, "Failed to enumerate products."); + WiuExitOnWin32Error(er, hr, "Failed to enumerate products."); LExit: return hr; @@ -633,7 +648,7 @@ extern "C" HRESULT DAPI WiuEnumRelatedProducts( { ExitFunction1(hr = HRESULT_FROM_WIN32(er)); } - ExitOnWin32Error(er, hr, "Failed to enumerate related products for updgrade code: %ls", wzUpgradeCode); + WiuExitOnWin32Error(er, hr, "Failed to enumerate related products for updgrade code: %ls", wzUpgradeCode); LExit: return hr; @@ -650,7 +665,7 @@ LExit: ********************************************************************/ extern "C" HRESULT DAPI WiuEnumRelatedProductCodes( __in_z LPCWSTR wzUpgradeCode, - __deref_out_ecount_opt(pcRelatedProducts) LPWSTR** prgsczProductCodes, + __deref_out_ecount_opt(*pcRelatedProducts) LPWSTR** prgsczProductCodes, __out DWORD* pcRelatedProducts, __in BOOL fReturnHighestVersionOnly ) @@ -673,16 +688,16 @@ extern "C" HRESULT DAPI WiuEnumRelatedProductCodes( hr = S_OK; break; } - ExitOnFailure(hr, "Failed to enumerate related products for upgrade code: %ls", wzUpgradeCode); + WiuExitOnFailure(hr, "Failed to enumerate related products for upgrade code: %ls", wzUpgradeCode); if (fReturnHighestVersionOnly) { // get the version hr = WiuGetProductInfo(wzCurrentProductCode, L"VersionString", &sczInstalledVersion); - ExitOnFailure(hr, "Failed to get version for product code: %ls", wzCurrentProductCode); + WiuExitOnFailure(hr, "Failed to get version for product code: %ls", wzCurrentProductCode); hr = FileVersionFromStringEx(sczInstalledVersion, 0, &qwCurrentVersion); - ExitOnFailure(hr, "Failed to convert version: %ls to DWORD64 for product code: %ls", sczInstalledVersion, wzCurrentProductCode); + WiuExitOnFailure(hr, "Failed to convert version: %ls to DWORD64 for product code: %ls", sczInstalledVersion, wzCurrentProductCode); // if this is the first product found then it is the highest version (for now) if (0 == *pcRelatedProducts) @@ -698,7 +713,7 @@ extern "C" HRESULT DAPI WiuEnumRelatedProductCodes( qwHighestVersion = qwCurrentVersion; hr = StrAllocString(prgsczProductCodes[0], wzCurrentProductCode, 0); - ExitOnFailure(hr, "Failed to update array with higher versioned product code."); + WiuExitOnFailure(hr, "Failed to update array with higher versioned product code."); } // continue here as we don't want anything else added to the list @@ -707,7 +722,7 @@ extern "C" HRESULT DAPI WiuEnumRelatedProductCodes( } hr = StrArrayAllocString(prgsczProductCodes, (LPUINT)(pcRelatedProducts), wzCurrentProductCode, 0); - ExitOnFailure(hr, "Failed to add product code to array."); + WiuExitOnFailure(hr, "Failed to add product code to array."); } LExit: @@ -726,7 +741,7 @@ extern "C" HRESULT DAPI WiuEnableLog( DWORD er = ERROR_SUCCESS; er = vpfnMsiEnableLogW(dwLogMode, wzLogFile, dwLogAttributes); - ExitOnWin32Error(er, hr, "Failed to enable MSI internal logging."); + WiuExitOnWin32Error(er, hr, "Failed to enable MSI internal logging."); LExit: return hr; @@ -780,7 +795,7 @@ extern "C" HRESULT DAPI WiuInitializeExternalUI( // Wire the internal and external UI handler. hr = WiuInitializeInternalUI(internalUILevel, hwndParent, pExecuteContext); - ExitOnFailure(hr, "Failed to set internal UI level and window."); + WiuExitOnFailure(hr, "Failed to set internal UI level and window."); pExecuteContext->fRollback = fRollback; pExecuteContext->pfnMessageHandler = pfnMessageHandler; @@ -791,7 +806,7 @@ extern "C" HRESULT DAPI WiuInitializeExternalUI( if (vpfnMsiSetExternalUIRecord) { er = vpfnMsiSetExternalUIRecord(InstallEngineRecordCallback, dwMessageFilter, pExecuteContext, &pExecuteContext->pfnPreviousExternalUIRecord); - ExitOnWin32Error(er, hr, "Failed to wire up external UI record handler."); + WiuExitOnWin32Error(er, hr, "Failed to wire up external UI record handler."); pExecuteContext->fSetPreviousExternalUIRecord = TRUE; } else @@ -841,7 +856,7 @@ extern "C" HRESULT DAPI WiuConfigureProductEx( er = vpfnMsiConfigureProductExW(wzProduct, iInstallLevel, eInstallState, wzCommandLine); er = CheckForRestartErrorCode(er, pRestart); - ExitOnWin32Error(er, hr, "Failed to configure product: %ls", wzProduct); + WiuExitOnWin32Error(er, hr, "Failed to configure product: %ls", wzProduct); LExit: return hr; @@ -859,7 +874,7 @@ extern "C" HRESULT DAPI WiuInstallProduct( er = vpfnMsiInstallProductW(wzPackagePath, wzCommandLine); er = CheckForRestartErrorCode(er, pRestart); - ExitOnWin32Error(er, hr, "Failed to install product: %ls", wzPackagePath); + WiuExitOnWin32Error(er, hr, "Failed to install product: %ls", wzPackagePath); LExit: return hr; @@ -878,7 +893,7 @@ extern "C" HRESULT DAPI WiuRemovePatches( er = vpfnMsiRemovePatchesW(wzPatchList, wzProductCode, INSTALLTYPE_SINGLE_INSTANCE, wzPropertyList); er = CheckForRestartErrorCode(er, pRestart); - ExitOnWin32Error(er, hr, "Failed to remove patches."); + WiuExitOnWin32Error(er, hr, "Failed to remove patches."); LExit: return hr; @@ -898,7 +913,7 @@ extern "C" HRESULT DAPI WiuSourceListAddSourceEx( DWORD er = ERROR_SUCCESS; er = vpfnMsiSourceListAddSourceExW(wzProductCodeOrPatchCode, wzUserSid, dwContext, MSISOURCETYPE_NETWORK | dwCode, wzSource, dwIndex); - ExitOnWin32Error(er, hr, "Failed to add source."); + WiuExitOnWin32Error(er, hr, "Failed to add source."); LExit: return hr; @@ -924,14 +939,14 @@ extern "C" HRESULT DAPI WiuBeginTransaction( if (!WiuIsMsiTransactionSupported()) { - ExitOnFailure(hr = E_NOTIMPL, "Msi transactions are not supported"); + WiuExitOnFailure(hr = E_NOTIMPL, "Msi transactions are not supported"); } hr = WiuEnableLog(dwLogMode, szLogPath, INSTALLLOGATTRIBUTES_APPEND); - ExitOnFailure(hr, "Failed to enable logging for MSI transaction"); + WiuExitOnFailure(hr, "Failed to enable logging for MSI transaction"); er = vpfnMsiBeginTransaction(szName, dwTransactionAttributes, phTransactionHandle, phChangeOfOwnerEvent); - ExitOnWin32Error(er, hr, "Failed to begin transaction."); + WiuExitOnWin32Error(er, hr, "Failed to begin transaction."); LExit: return hr; @@ -948,14 +963,14 @@ extern "C" HRESULT DAPI WiuEndTransaction( if (!WiuIsMsiTransactionSupported()) { - ExitOnFailure(hr = E_NOTIMPL, "Msi transactions are not supported"); + WiuExitOnFailure(hr = E_NOTIMPL, "Msi transactions are not supported"); } hr = WiuEnableLog(dwLogMode, szLogPath, INSTALLLOGATTRIBUTES_APPEND); - ExitOnFailure(hr, "Failed to enable logging for MSI transaction"); + WiuExitOnFailure(hr, "Failed to enable logging for MSI transaction"); er = vpfnMsiEndTransaction(dwTransactionState); - ExitOnWin32Error(er, hr, "Failed to end transaction."); + WiuExitOnWin32Error(er, hr, "Failed to end transaction."); LExit: return hr; @@ -1048,10 +1063,10 @@ static INT CALLBACK InstallEngineRecordCallback( { hr = HRESULT_FROM_WIN32(er); } - ExitOnFailure(hr, "Failed to allocate string for formated message."); + WiuExitOnFailure(hr, "Failed to allocate string for formated message."); er = ::MsiFormatRecordW(NULL, hRecord, sczMessage, &cchMessage); - ExitOnWin32Error(er, hr, "Failed to format message record."); + WiuExitOnWin32Error(er, hr, "Failed to format message record."); // Pass to handler including both the formated message and the original record. nResult = HandleInstallMessage(pContext, mt, uiFlags, sczMessage, hRecord); @@ -1213,7 +1228,7 @@ static INT HandleInstallProgress( // parse number hr = StrStringToInt32(pwz, cch, &iFields[cFields]); - ExitOnFailure(hr, "Failed to parse MSI message part."); + WiuExitOnFailure(hr, "Failed to parse MSI message part."); // increment field count ++cFields; @@ -1255,7 +1270,7 @@ static INT HandleInstallProgress( else { hr = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); - ExitOnRootFailure(hr, "Insufficient space to hold progress information."); + WiuExitOnRootFailure(hr, "Insufficient space to hold progress information."); } // we only care about the first stage after script execution has started diff --git a/src/dutil/wuautil.cpp b/src/dutil/wuautil.cpp index 94ab659d..dfb28818 100644 --- a/src/dutil/wuautil.cpp +++ b/src/dutil/wuautil.cpp @@ -3,6 +3,21 @@ #include "precomp.h" +// Exit macros +#define WuaExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_WUAUTIL, x, s, __VA_ARGS__) +#define WuaExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_WUAUTIL, x, s, __VA_ARGS__) +#define WuaExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_WUAUTIL, x, s, __VA_ARGS__) +#define WuaExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_WUAUTIL, x, s, __VA_ARGS__) +#define WuaExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_WUAUTIL, x, s, __VA_ARGS__) +#define WuaExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_WUAUTIL, x, s, __VA_ARGS__) +#define WuaExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_WUAUTIL, p, x, e, s, __VA_ARGS__) +#define WuaExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_WUAUTIL, p, x, s, __VA_ARGS__) +#define WuaExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_WUAUTIL, p, x, e, s, __VA_ARGS__) +#define WuaExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_WUAUTIL, p, x, s, __VA_ARGS__) +#define WuaExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_WUAUTIL, e, x, s, __VA_ARGS__) +#define WuaExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_WUAUTIL, g, x, s, __VA_ARGS__) + + // internal function declarations static HRESULT GetAutomaticUpdatesService( @@ -18,10 +33,10 @@ extern "C" HRESULT DAPI WuaPauseAutomaticUpdates() IAutomaticUpdates *pAutomaticUpdates = NULL; hr = GetAutomaticUpdatesService(&pAutomaticUpdates); - ExitOnFailure(hr, "Failed to get the Automatic Updates service."); + WuaExitOnFailure(hr, "Failed to get the Automatic Updates service."); hr = pAutomaticUpdates->Pause(); - ExitOnFailure(hr, "Failed to pause the Automatic Updates service."); + WuaExitOnFailure(hr, "Failed to pause the Automatic Updates service."); LExit: ReleaseObject(pAutomaticUpdates); @@ -35,10 +50,10 @@ extern "C" HRESULT DAPI WuaResumeAutomaticUpdates() IAutomaticUpdates *pAutomaticUpdates = NULL; hr = GetAutomaticUpdatesService(&pAutomaticUpdates); - ExitOnFailure(hr, "Failed to get the Automatic Updates service."); + WuaExitOnFailure(hr, "Failed to get the Automatic Updates service."); hr = pAutomaticUpdates->Resume(); - ExitOnFailure(hr, "Failed to resume the Automatic Updates service."); + WuaExitOnFailure(hr, "Failed to resume the Automatic Updates service."); LExit: ReleaseObject(pAutomaticUpdates); @@ -55,10 +70,10 @@ extern "C" HRESULT DAPI WuaRestartRequired( VARIANT_BOOL bRestartRequired; hr = ::CoCreateInstance(__uuidof(SystemInformation), NULL, CLSCTX_INPROC_SERVER, __uuidof(ISystemInformation), reinterpret_cast(&pSystemInformation)); - ExitOnRootFailure(hr, "Failed to get WUA system information interface."); + WuaExitOnRootFailure(hr, "Failed to get WUA system information interface."); hr = pSystemInformation->get_RebootRequired(&bRestartRequired); - ExitOnRootFailure(hr, "Failed to determine if restart is required from WUA."); + WuaExitOnRootFailure(hr, "Failed to determine if restart is required from WUA."); *pfRestartRequired = (VARIANT_FALSE != bRestartRequired); @@ -79,10 +94,10 @@ static HRESULT GetAutomaticUpdatesService( CLSID clsidAutomaticUpdates = { }; hr = ::CLSIDFromProgID(L"Microsoft.Update.AutoUpdate", &clsidAutomaticUpdates); - ExitOnFailure(hr, "Failed to get CLSID for Microsoft.Update.AutoUpdate."); + WuaExitOnFailure(hr, "Failed to get CLSID for Microsoft.Update.AutoUpdate."); hr = ::CoCreateInstance(clsidAutomaticUpdates, NULL, CLSCTX_INPROC_SERVER, IID_IAutomaticUpdates, reinterpret_cast(ppAutomaticUpdates)); - ExitOnFailure(hr, "Failed to create instance of Microsoft.Update.AutoUpdate."); + WuaExitOnFailure(hr, "Failed to create instance of Microsoft.Update.AutoUpdate."); LExit: return hr; diff --git a/src/dutil/xmlutil.cpp b/src/dutil/xmlutil.cpp index f97ca962..6ecd2449 100644 --- a/src/dutil/xmlutil.cpp +++ b/src/dutil/xmlutil.cpp @@ -2,6 +2,21 @@ #include "precomp.h" + +// Exit macros +#define XmlExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_XMLUTIL, x, s, __VA_ARGS__) +#define XmlExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_XMLUTIL, x, s, __VA_ARGS__) +#define XmlExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_XMLUTIL, x, s, __VA_ARGS__) +#define XmlExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_XMLUTIL, x, s, __VA_ARGS__) +#define XmlExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_XMLUTIL, x, s, __VA_ARGS__) +#define XmlExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_XMLUTIL, x, s, __VA_ARGS__) +#define XmlExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_XMLUTIL, p, x, e, s, __VA_ARGS__) +#define XmlExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_XMLUTIL, p, x, s, __VA_ARGS__) +#define XmlExitOnNullDebugTrace(p, x, e, s, ...) ExitOnNullDebugTraceSource(DUTIL_SOURCE_XMLUTIL, p, x, e, s, __VA_ARGS__) +#define XmlExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_XMLUTIL, p, x, s, __VA_ARGS__) +#define XmlExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_XMLUTIL, e, x, s, __VA_ARGS__) +#define XmlExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_XMLUTIL, g, x, s, __VA_ARGS__) + // intialization globals CLSID vclsidXMLDOM = { 0, 0, 0, { 0, 0, 0, 0, 0, 0, 0, 0} }; static volatile LONG vcXmlInitialized = 0; @@ -23,7 +38,7 @@ extern "C" HRESULT DAPI XmlInitialize( hr = ::CoInitialize(0); if (RPC_E_CHANGED_MODE != hr) { - ExitOnFailure(hr, "failed to initialize COM"); + XmlExitOnFailure(hr, "failed to initialize COM"); fComInitialized = TRUE; } } @@ -47,7 +62,7 @@ extern "C" HRESULT DAPI XmlInitialize( // try to fall back to old MSXML hr = ::CLSIDFromProgID(L"MSXML.DOMDocument", &vclsidXMLDOM); } - ExitOnFailure(hr, "failed to get CLSID for XML DOM"); + XmlExitOnFailure(hr, "failed to get CLSID for XML DOM"); Assert(IsEqualCLSID(vclsidXMLDOM, XmlUtil_CLSID_DOMDocument) || IsEqualCLSID(vclsidXMLDOM, XmlUtil_CLSID_DOMDocument20) || @@ -99,7 +114,7 @@ extern "C" HRESULT DAPI XmlCreateElement( HRESULT hr = S_OK; BSTR bstrElementName = ::SysAllocString(wzElementName); - ExitOnNull(bstrElementName, hr, E_OUTOFMEMORY, "failed SysAllocString"); + XmlExitOnNull(bstrElementName, hr, E_OUTOFMEMORY, "failed SysAllocString"); hr = pixdDocument->createElement(bstrElementName, ppixnElement); LExit: ReleaseBSTR(bstrElementName); @@ -130,7 +145,7 @@ extern "C" HRESULT DAPI XmlCreateDocument( // Test if we have access to the Wow64 API, and store the result in fWow64Available HMODULE hKernel32 = ::GetModuleHandleA("kernel32.dll"); - ExitOnNullWithLastError(hKernel32, hr, "failed to get handle to kernel32.dll"); + XmlExitOnNullWithLastError(hKernel32, hr, "failed to get handle to kernel32.dll"); // This will test if we have access to the Wow64 API if (NULL != GetProcAddress(hKernel32, "IsWow64Process")) @@ -155,7 +170,7 @@ extern "C" HRESULT DAPI XmlCreateDocument( } hr = ::CoCreateInstance(vclsidXMLDOM, NULL, CLSCTX_INPROC_SERVER, XmlUtil_IID_IXMLDOMDocument, (void**)&pixdDocument); - ExitOnFailure(hr, "failed to create XML DOM Document"); + XmlExitOnFailure(hr, "failed to create XML DOM Document"); Assert(pixdDocument); if (IsEqualCLSID(vclsidXMLDOM, XmlUtil_CLSID_DOMDocument30) || IsEqualCLSID(vclsidXMLDOM, XmlUtil_CLSID_DOMDocument20)) @@ -166,9 +181,9 @@ extern "C" HRESULT DAPI XmlCreateDocument( if (pwzElementName) { hr = XmlCreateElement(pixdDocument, pwzElementName, &pixeRootElement); - ExitOnFailure(hr, "failed XmlCreateElement"); + XmlExitOnFailure(hr, "failed XmlCreateElement"); hr = pixdDocument->appendChild(pixeRootElement, NULL); - ExitOnFailure(hr, "failed appendChild"); + XmlExitOnFailure(hr, "failed appendChild"); } *ppixdDocument = pixdDocument; @@ -222,28 +237,28 @@ static void XmlReportParseError( Trace(REPORT_STANDARD, "Failed to parse XML. IXMLDOMParseError reports:"); hr = pixpe->get_errorCode(&lNumber); - ExitOnFailure(hr, "Failed to query IXMLDOMParseError.errorCode."); + XmlExitOnFailure(hr, "Failed to query IXMLDOMParseError.errorCode."); Trace(REPORT_STANDARD, "errorCode = 0x%x", lNumber); hr = pixpe->get_filepos(&lNumber); - ExitOnFailure(hr, "Failed to query IXMLDOMParseError.filepos."); + XmlExitOnFailure(hr, "Failed to query IXMLDOMParseError.filepos."); Trace(REPORT_STANDARD, "filepos = %d", lNumber); hr = pixpe->get_line(&lNumber); - ExitOnFailure(hr, "Failed to query IXMLDOMParseError.line."); + XmlExitOnFailure(hr, "Failed to query IXMLDOMParseError.line."); Trace(REPORT_STANDARD, "line = %d", lNumber); hr = pixpe->get_linepos(&lNumber); - ExitOnFailure(hr, "Failed to query IXMLDOMParseError.linepos."); + XmlExitOnFailure(hr, "Failed to query IXMLDOMParseError.linepos."); Trace(REPORT_STANDARD, "linepos = %d", lNumber); hr = pixpe->get_reason(&bstr); - ExitOnFailure(hr, "Failed to query IXMLDOMParseError.reason."); + XmlExitOnFailure(hr, "Failed to query IXMLDOMParseError.reason."); Trace(REPORT_STANDARD, "reason = %ls", bstr); ReleaseNullBSTR(bstr); hr = pixpe->get_srcText (&bstr); - ExitOnFailure(hr, "Failed to query IXMLDOMParseError.srcText ."); + XmlExitOnFailure(hr, "Failed to query IXMLDOMParseError.srcText ."); Trace(REPORT_STANDARD, "srcText = %ls", bstr); ReleaseNullBSTR(bstr); @@ -272,7 +287,7 @@ extern "C" HRESULT DAPI XmlLoadDocumentEx( if (!wzDocument || !*wzDocument) { hr = E_UNEXPECTED; - ExitOnFailure(hr, "string must be non-null"); + XmlExitOnFailure(hr, "string must be non-null"); } hr = XmlCreateDocument(NULL, &pixd); @@ -280,22 +295,22 @@ extern "C" HRESULT DAPI XmlLoadDocumentEx( { hr = E_FAIL; } - ExitOnFailure(hr, "failed XmlCreateDocument"); + XmlExitOnFailure(hr, "failed XmlCreateDocument"); if (dwAttributes & XML_LOAD_PRESERVE_WHITESPACE) { hr = pixd->put_preserveWhiteSpace(VARIANT_TRUE); - ExitOnFailure(hr, "failed put_preserveWhiteSpace"); + XmlExitOnFailure(hr, "failed put_preserveWhiteSpace"); } // Security issue. Avoid triggering anything external. hr = pixd->put_validateOnParse(VARIANT_FALSE); - ExitOnFailure(hr, "failed put_validateOnParse"); + XmlExitOnFailure(hr, "failed put_validateOnParse"); hr = pixd->put_resolveExternals(VARIANT_FALSE); - ExitOnFailure(hr, "failed put_resolveExternals"); + XmlExitOnFailure(hr, "failed put_resolveExternals"); bstrLoad = ::SysAllocString(wzDocument); - ExitOnNull(bstrLoad, hr, E_OUTOFMEMORY, "failed to allocate bstr for Load in XmlLoadDocumentEx"); + XmlExitOnNull(bstrLoad, hr, E_OUTOFMEMORY, "failed to allocate bstr for Load in XmlLoadDocumentEx"); hr = pixd->loadXML(bstrLoad, &vbSuccess); if (S_FALSE == hr) @@ -308,7 +323,7 @@ extern "C" HRESULT DAPI XmlLoadDocumentEx( XmlReportParseError(pixpe); } - ExitOnFailure(hr, "failed loadXML"); + XmlExitOnFailure(hr, "failed loadXML"); hr = S_OK; @@ -359,26 +374,26 @@ extern "C" HRESULT DAPI XmlLoadDocumentFromFileEx( ::VariantInit(&varPath); varPath.vt = VT_BSTR; varPath.bstrVal = ::SysAllocString(wzPath); - ExitOnNull(varPath.bstrVal, hr, E_OUTOFMEMORY, "failed to allocate bstr for Path in XmlLoadDocumentFromFileEx"); + XmlExitOnNull(varPath.bstrVal, hr, E_OUTOFMEMORY, "failed to allocate bstr for Path in XmlLoadDocumentFromFileEx"); hr = XmlCreateDocument(NULL, &pixd); if (hr == S_FALSE) { hr = E_FAIL; } - ExitOnFailure(hr, "failed XmlCreateDocument"); + XmlExitOnFailure(hr, "failed XmlCreateDocument"); if (dwAttributes & XML_LOAD_PRESERVE_WHITESPACE) { hr = pixd->put_preserveWhiteSpace(VARIANT_TRUE); - ExitOnFailure(hr, "failed put_preserveWhiteSpace"); + XmlExitOnFailure(hr, "failed put_preserveWhiteSpace"); } // Avoid triggering anything external. hr = pixd->put_validateOnParse(VARIANT_FALSE); - ExitOnFailure(hr, "failed put_validateOnParse"); + XmlExitOnFailure(hr, "failed put_validateOnParse"); hr = pixd->put_resolveExternals(VARIANT_FALSE); - ExitOnFailure(hr, "failed put_resolveExternals"); + XmlExitOnFailure(hr, "failed put_resolveExternals"); pixd->put_async(VARIANT_FALSE); hr = pixd->load(varPath, &vbSuccess); @@ -392,7 +407,7 @@ extern "C" HRESULT DAPI XmlLoadDocumentFromFileEx( XmlReportParseError(pixpe); } - ExitOnFailure(hr, "failed to load XML from: %ls", wzPath); + XmlExitOnFailure(hr, "failed to load XML from: %ls", wzPath); if (ppixdDocument) { @@ -434,13 +449,13 @@ extern "C" HRESULT DAPI XmlLoadDocumentFromBuffer( { hr = E_FAIL; } - ExitOnFailure(hr, "failed XmlCreateDocument"); + XmlExitOnFailure(hr, "failed XmlCreateDocument"); // Security issue. Avoid triggering anything external. hr = pixdDocument->put_validateOnParse(VARIANT_FALSE); - ExitOnFailure(hr, "failed put_validateOnParse"); + XmlExitOnFailure(hr, "failed put_validateOnParse"); hr = pixdDocument->put_resolveExternals(VARIANT_FALSE); - ExitOnFailure(hr, "failed put_resolveExternals"); + XmlExitOnFailure(hr, "failed put_resolveExternals"); // load document sa.cDims = 1; @@ -456,7 +471,7 @@ extern "C" HRESULT DAPI XmlLoadDocumentFromBuffer( { hr = HRESULT_FROM_WIN32(ERROR_OPEN_FAILED); } - ExitOnFailure(hr, "failed loadXML"); + XmlExitOnFailure(hr, "failed loadXML"); // return value *ppixdDocument = pixdDocument; @@ -488,20 +503,20 @@ extern "C" HRESULT DAPI XmlSetAttribute( IXMLDOMAttribute* pixaAttribute = NULL; IXMLDOMNode* pixaNode = NULL; BSTR bstrAttributeName = ::SysAllocString(pwzAttribute); - ExitOnNull(bstrAttributeName, hr, E_OUTOFMEMORY, "failed to allocate bstr for AttributeName in XmlSetAttribute"); + XmlExitOnNull(bstrAttributeName, hr, E_OUTOFMEMORY, "failed to allocate bstr for AttributeName in XmlSetAttribute"); hr = pixnNode->get_attributes(&pixnnmAttributes); - ExitOnFailure(hr, "failed get_attributes in XmlSetAttribute(%ls)", pwzAttribute); + XmlExitOnFailure(hr, "failed get_attributes in XmlSetAttribute(%ls)", pwzAttribute); hr = pixnNode->get_ownerDocument(&pixdDocument); if (hr == S_FALSE) { hr = E_FAIL; } - ExitOnFailure(hr, "failed get_ownerDocument in XmlSetAttribute"); + XmlExitOnFailure(hr, "failed get_ownerDocument in XmlSetAttribute"); hr = pixdDocument->createAttribute(bstrAttributeName, &pixaAttribute); - ExitOnFailure(hr, "failed createAttribute in XmlSetAttribute(%ls)", pwzAttribute); + XmlExitOnFailure(hr, "failed createAttribute in XmlSetAttribute(%ls)", pwzAttribute); varAttributeValue.vt = VT_BSTR; varAttributeValue.bstrVal = ::SysAllocString(pwzAttributeValue); @@ -509,13 +524,13 @@ extern "C" HRESULT DAPI XmlSetAttribute( { hr = HRESULT_FROM_WIN32(ERROR_OUTOFMEMORY); } - ExitOnFailure(hr, "failed SysAllocString in XmlSetAttribute"); + XmlExitOnFailure(hr, "failed SysAllocString in XmlSetAttribute"); hr = pixaAttribute->put_nodeValue(varAttributeValue); - ExitOnFailure(hr, "failed put_nodeValue in XmlSetAttribute(%ls)", pwzAttribute); + XmlExitOnFailure(hr, "failed put_nodeValue in XmlSetAttribute(%ls)", pwzAttribute); hr = pixnnmAttributes->setNamedItem(pixaAttribute, &pixaNode); - ExitOnFailure(hr, "failed setNamedItem in XmlSetAttribute(%ls)", pwzAttribute); + XmlExitOnFailure(hr, "failed setNamedItem in XmlSetAttribute(%ls)", pwzAttribute); LExit: ReleaseObject(pixdDocument); @@ -543,11 +558,11 @@ extern "C" HRESULT DAPI XmlSelectSingleNode( BSTR bstrXPath = NULL; - ExitOnNull(pixnParent, hr, E_UNEXPECTED, "pixnParent parameter was null in XmlSelectSingleNode"); - ExitOnNull(ppixnChild, hr, E_UNEXPECTED, "ppixnChild parameter was null in XmlSelectSingleNode"); + XmlExitOnNull(pixnParent, hr, E_UNEXPECTED, "pixnParent parameter was null in XmlSelectSingleNode"); + XmlExitOnNull(ppixnChild, hr, E_UNEXPECTED, "ppixnChild parameter was null in XmlSelectSingleNode"); bstrXPath = ::SysAllocString(wzXPath ? wzXPath : L""); - ExitOnNull(bstrXPath, hr, E_OUTOFMEMORY, "failed to allocate bstr for XPath expression in XmlSelectSingleNode"); + XmlExitOnNull(bstrXPath, hr, E_OUTOFMEMORY, "failed to allocate bstr for XPath expression in XmlSelectSingleNode"); hr = pixnParent->selectSingleNode(bstrXPath, ppixnChild); @@ -575,7 +590,7 @@ extern "C" HRESULT DAPI XmlCreateTextNode( HRESULT hr = S_OK; BSTR bstrText = ::SysAllocString(wzText); - ExitOnNull(bstrText, hr, E_OUTOFMEMORY, "failed SysAllocString"); + XmlExitOnNull(bstrText, hr, E_OUTOFMEMORY, "failed SysAllocString"); hr = pixdDocument->createTextNode(bstrText, ppixnTextNode); LExit: ReleaseBSTR(bstrText); @@ -621,7 +636,7 @@ extern "C" HRESULT DAPI XmlGetAttribute( // get attribute value from source hr = pixnNode->get_attributes(&pixnnmAttributes); - ExitOnFailure(hr, "failed get_attributes"); + XmlExitOnFailure(hr, "failed get_attributes"); hr = XmlGetNamedItem(pixnnmAttributes, bstrAttribute, &pixnAttribute); if (S_FALSE == hr) @@ -629,10 +644,10 @@ extern "C" HRESULT DAPI XmlGetAttribute( // hr = E_FAIL; ExitFunction(); } - ExitOnFailure(hr, "failed getNamedItem in XmlGetAttribute(%ls)", pwzAttribute); + XmlExitOnFailure(hr, "failed getNamedItem in XmlGetAttribute(%ls)", pwzAttribute); hr = pixnAttribute->get_nodeValue(&varAttributeValue); - ExitOnFailure(hr, "failed get_nodeValue in XmlGetAttribute(%ls)", pwzAttribute); + XmlExitOnFailure(hr, "failed get_nodeValue in XmlGetAttribute(%ls)", pwzAttribute); // steal the BSTR from the VARIANT if (S_OK == hr && pbstrAttributeValue) @@ -672,28 +687,28 @@ HRESULT DAPI XmlGetAttributeEx( // get attribute value from source hr = pixnNode->get_attributes(&pixnnmAttributes); - ExitOnFailure(hr, "Failed get_attributes."); + XmlExitOnFailure(hr, "Failed get_attributes."); bstrAttribute = ::SysAllocString(wzAttribute); - ExitOnNull(bstrAttribute, hr, E_OUTOFMEMORY, "Failed to allocate attribute name BSTR."); + XmlExitOnNull(bstrAttribute, hr, E_OUTOFMEMORY, "Failed to allocate attribute name BSTR."); hr = XmlGetNamedItem(pixnnmAttributes, bstrAttribute, &pixnAttribute); if (S_FALSE == hr) { ExitFunction1(hr = E_NOTFOUND); } - ExitOnFailure(hr, "Failed getNamedItem in XmlGetAttribute(%ls)", wzAttribute); + XmlExitOnFailure(hr, "Failed getNamedItem in XmlGetAttribute(%ls)", wzAttribute); hr = pixnAttribute->get_nodeValue(&varAttributeValue); if (S_FALSE == hr) { ExitFunction1(hr = E_NOTFOUND); } - ExitOnFailure(hr, "Failed get_nodeValue in XmlGetAttribute(%ls)", wzAttribute); + XmlExitOnFailure(hr, "Failed get_nodeValue in XmlGetAttribute(%ls)", wzAttribute); // copy value hr = StrAllocString(psczAttributeValue, varAttributeValue.bstrVal, 0); - ExitOnFailure(hr, "Failed to copy attribute value."); + XmlExitOnFailure(hr, "Failed to copy attribute value."); LExit: ReleaseObject(pixnnmAttributes); @@ -721,7 +736,7 @@ HRESULT DAPI XmlGetYesNoAttribute( hr = XmlGetAttributeEx(pixnNode, wzAttribute, &sczValue); if (E_NOTFOUND != hr) { - ExitOnFailure(hr, "Failed to get attribute."); + XmlExitOnFailure(hr, "Failed to get attribute."); *pfYes = CSTR_EQUAL == ::CompareStringW(LOCALE_INVARIANT, 0, sczValue, -1, L"yes", -1); } @@ -764,7 +779,7 @@ extern "C" HRESULT DAPI XmlGetAttributeNumberBase( BSTR bstrPointer = NULL; hr = XmlGetAttribute(pixnNode, pwzAttribute, &bstrPointer); - ExitOnFailure(hr, "Failed to get value from attribute."); + XmlExitOnFailure(hr, "Failed to get value from attribute."); if (S_OK == hr) { @@ -791,13 +806,13 @@ extern "C" HRESULT DAPI XmlGetAttributeLargeNumber( BSTR bstrValue = NULL; hr = XmlGetAttribute(pixnNode, pwzAttribute, &bstrValue); - ExitOnFailure(hr, "failed XmlGetAttribute"); + XmlExitOnFailure(hr, "failed XmlGetAttribute"); if (S_OK == hr) { LONGLONG ll = 0; hr = StrStringToInt64(bstrValue, 0, &ll); - ExitOnFailure(hr, "Failed to treat attribute value as number."); + XmlExitOnFailure(hr, "Failed to treat attribute value as number."); *pdw64Value = ll; } @@ -829,7 +844,7 @@ extern "C" HRESULT DAPI XmlGetNamedItem( HRESULT hr = S_OK; BSTR bstrName = ::SysAllocString(wzName); - ExitOnNull(bstrName, hr, E_OUTOFMEMORY, "failed SysAllocString"); + XmlExitOnNull(bstrName, hr, E_OUTOFMEMORY, "failed SysAllocString"); hr = pixnmAttributes->getNamedItem(bstrName, ppixnNamedItem); @@ -863,12 +878,12 @@ extern "C" HRESULT DAPI XmlSetText( // find the text node hr = pixnNode->get_childNodes(&pixnlNodeList); - ExitOnFailure(hr, "failed to get child nodes"); + XmlExitOnFailure(hr, "failed to get child nodes"); while (S_OK == (hr = pixnlNodeList->nextNode(&pixnChildNode))) { hr = pixnChildNode->get_nodeType(&dnType); - ExitOnFailure(hr, "failed to get node type"); + XmlExitOnFailure(hr, "failed to get node type"); if (NODE_TEXT == dnType) break; @@ -887,10 +902,10 @@ extern "C" HRESULT DAPI XmlSetText( { hr = HRESULT_FROM_WIN32(ERROR_OUTOFMEMORY); } - ExitOnFailure(hr, "failed SysAllocString in XmlSetText"); + XmlExitOnFailure(hr, "failed SysAllocString in XmlSetText"); hr = pixnChildNode->put_nodeValue(varText); - ExitOnFailure(hr, "failed IXMLDOMNode::put_nodeValue"); + XmlExitOnFailure(hr, "failed IXMLDOMNode::put_nodeValue"); } else { @@ -899,13 +914,13 @@ extern "C" HRESULT DAPI XmlSetText( { hr = E_FAIL; } - ExitOnFailure(hr, "failed get_ownerDocument in XmlSetAttribute"); + XmlExitOnFailure(hr, "failed get_ownerDocument in XmlSetAttribute"); hr = XmlCreateTextNode(pixdDocument, pwzText, &pixtTextNode); - ExitOnFailure(hr, "failed createTextNode in XmlSetText(%ls)", pwzText); + XmlExitOnFailure(hr, "failed createTextNode in XmlSetText(%ls)", pwzText); hr = pixnNode->appendChild(pixtTextNode, NULL); - ExitOnFailure(hr, "failed appendChild in XmlSetText(%ls)", pwzText); + XmlExitOnFailure(hr, "failed appendChild in XmlSetText(%ls)", pwzText); } hr = *pwzText ? S_OK : S_FALSE; @@ -933,7 +948,7 @@ extern "C" HRESULT DAPI XmlSetTextNumber( WCHAR wzValue[12]; hr = ::StringCchPrintfW(wzValue, countof(wzValue), L"%u", dwValue); - ExitOnFailure(hr, "Failed to format numeric value as string."); + XmlExitOnFailure(hr, "Failed to format numeric value as string."); hr = XmlSetText(pixnNode, wzValue); @@ -963,21 +978,21 @@ extern "C" HRESULT DAPI XmlCreateChild( { hr = E_FAIL; } - ExitOnFailure(hr, "failed get_ownerDocument"); + XmlExitOnFailure(hr, "failed get_ownerDocument"); hr = XmlCreateElement(pixdDocument, pwzElementType, (IXMLDOMElement**) &pixnChild); if (hr == S_FALSE) { hr = E_FAIL; } - ExitOnFailure(hr, "failed createElement"); + XmlExitOnFailure(hr, "failed createElement"); pixnParent->appendChild(pixnChild,NULL); if (hr == S_FALSE) { hr = E_FAIL; } - ExitOnFailure(hr, "failed appendChild"); + XmlExitOnFailure(hr, "failed appendChild"); if (ppixnChild) { @@ -1005,13 +1020,13 @@ extern "C" HRESULT DAPI XmlRemoveAttribute( // RELEASEME IXMLDOMNamedNodeMap* pixnnmAttributes = NULL; BSTR bstrAttribute = ::SysAllocString(pwzAttribute); - ExitOnNull(bstrAttribute, hr, E_OUTOFMEMORY, "failed to allocate bstr for attribute in XmlRemoveAttribute"); + XmlExitOnNull(bstrAttribute, hr, E_OUTOFMEMORY, "failed to allocate bstr for attribute in XmlRemoveAttribute"); hr = pixnNode->get_attributes(&pixnnmAttributes); - ExitOnFailure(hr, "failed get_attributes in RemoveXmlAttribute(%ls)", pwzAttribute); + XmlExitOnFailure(hr, "failed get_attributes in RemoveXmlAttribute(%ls)", pwzAttribute); hr = pixnnmAttributes->removeNamedItem(bstrAttribute, NULL); - ExitOnFailure(hr, "failed removeNamedItem in RemoveXmlAttribute(%ls)", pwzAttribute); + XmlExitOnFailure(hr, "failed removeNamedItem in RemoveXmlAttribute(%ls)", pwzAttribute); LExit: ReleaseObject(pixnnmAttributes); @@ -1035,11 +1050,11 @@ extern "C" HRESULT DAPI XmlSelectNodes( BSTR bstrXPath = NULL; - ExitOnNull(pixnParent, hr, E_UNEXPECTED, "pixnParent parameter was null in XmlSelectNodes"); - ExitOnNull(ppixnlChildren, hr, E_UNEXPECTED, "ppixnChild parameter was null in XmlSelectNodes"); + XmlExitOnNull(pixnParent, hr, E_UNEXPECTED, "pixnParent parameter was null in XmlSelectNodes"); + XmlExitOnNull(ppixnlChildren, hr, E_UNEXPECTED, "ppixnChild parameter was null in XmlSelectNodes"); bstrXPath = ::SysAllocString(wzXPath ? wzXPath : L""); - ExitOnNull(bstrXPath, hr, E_OUTOFMEMORY, "failed to allocate bstr for XPath expression in XmlSelectNodes"); + XmlExitOnNull(bstrXPath, hr, E_OUTOFMEMORY, "failed to allocate bstr for XPath expression in XmlSelectNodes"); hr = pixnParent->selectNodes(bstrXPath, ppixnlChildren); @@ -1077,24 +1092,24 @@ extern "C" HRESULT DAPI XmlNextAttribute( } hr = pixnnm->nextNode(&pixn); - ExitOnFailure(hr, "Failed to get next attribute."); + XmlExitOnFailure(hr, "Failed to get next attribute."); if (S_OK == hr) { hr = pixn->get_nodeType(&nt); - ExitOnFailure(hr, "failed to get node type"); + XmlExitOnFailure(hr, "failed to get node type"); if (NODE_ATTRIBUTE != nt) { hr = E_UNEXPECTED; - ExitOnFailure(hr, "Failed to get expected node type back: attribute"); + XmlExitOnFailure(hr, "Failed to get expected node type back: attribute"); } // if the caller asked for the attribute name if (pbstrAttribute) { hr = pixn->get_baseName(pbstrAttribute); - ExitOnFailure(hr, "failed to get attribute name"); + XmlExitOnFailure(hr, "failed to get attribute name"); } *pixnAttribute = pixn; @@ -1140,20 +1155,20 @@ extern "C" HRESULT DAPI XmlNextElement( while (S_OK == (hr = pixnl->nextNode(&pixn))) { hr = pixn->get_nodeType(&nt); - ExitOnFailure(hr, "failed to get node type"); + XmlExitOnFailure(hr, "failed to get node type"); if (NODE_ELEMENT == nt) break; ReleaseNullObject(pixn); } - ExitOnFailure(hr, "failed to get next element"); + XmlExitOnFailure(hr, "failed to get next element"); // if we have a node and the caller asked for the element name if (pixn && pbstrElement) { hr = pixn->get_baseName(pbstrElement); - ExitOnFailure(hr, "failed to get element name"); + XmlExitOnFailure(hr, "failed to get element name"); } *pixnElement = pixn; @@ -1185,12 +1200,12 @@ extern "C" HRESULT DAPI XmlRemoveChildren( if (pwzXPath) { hr = XmlSelectNodes(pixnSource, pwzXPath, &pixnlNodeList); - ExitOnFailure(hr, "failed XmlSelectNodes"); + XmlExitOnFailure(hr, "failed XmlSelectNodes"); } else { hr = pixnSource->get_childNodes(&pixnlNodeList); - ExitOnFailure(hr, "failed childNodes"); + XmlExitOnFailure(hr, "failed childNodes"); } if (S_FALSE == hr) { @@ -1200,7 +1215,7 @@ extern "C" HRESULT DAPI XmlRemoveChildren( while (S_OK == (hr = pixnlNodeList->nextNode(&pixnNode))) { hr = pixnSource->removeChild(pixnNode, &pixnRemoveChild); - ExitOnFailure(hr, "failed removeChild"); + XmlExitOnFailure(hr, "failed removeChild"); ReleaseNullObject(pixnRemoveChild); ReleaseNullObject(pixnNode); @@ -1240,14 +1255,14 @@ extern "C" HRESULT DAPI XmlSaveDocument( { hr = HRESULT_FROM_WIN32(ERROR_OUTOFMEMORY); } - ExitOnFailure(hr, "failed to create BSTR"); + XmlExitOnFailure(hr, "failed to create BSTR"); hr = pixdDocument->save(varsDestPath); if (hr == S_FALSE) { hr = E_FAIL; } - ExitOnFailure(hr, "failed save in WriteDocument"); + XmlExitOnFailure(hr, "failed save in WriteDocument"); LExit: ReleaseVariant(varsDestPath); @@ -1277,33 +1292,33 @@ extern "C" HRESULT DAPI XmlSaveDocumentToBuffer( // create stream hr = ::CreateStreamOnHGlobal(NULL, TRUE, &pStream); - ExitOnFailure(hr, "Failed to create stream."); + XmlExitOnFailure(hr, "Failed to create stream."); // write document to stream vtDestination.vt = VT_UNKNOWN; vtDestination.punkVal = (IUnknown*)pStream; hr = pixdDocument->save(vtDestination); - ExitOnFailure(hr, "Failed to save document."); + XmlExitOnFailure(hr, "Failed to save document."); // get stream size hr = pStream->Stat(&statstg, STATFLAG_NONAME); - ExitOnFailure(hr, "Failed to get stream size."); + XmlExitOnFailure(hr, "Failed to get stream size."); // allocate buffer pbDest = static_cast(MemAlloc((SIZE_T)statstg.cbSize.LowPart, TRUE)); - ExitOnNull(pbDest, hr, E_OUTOFMEMORY, "Failed to allocate destination buffer."); + XmlExitOnNull(pbDest, hr, E_OUTOFMEMORY, "Failed to allocate destination buffer."); // read data from stream li.QuadPart = 0; hr = pStream->Seek(li, STREAM_SEEK_SET, NULL); - ExitOnFailure(hr, "Failed to seek stream."); + XmlExitOnFailure(hr, "Failed to seek stream."); hr = pStream->Read(pbDest, statstg.cbSize.LowPart, &cbRead); if (cbRead < statstg.cbSize.LowPart) { hr = E_FAIL; } - ExitOnFailure(hr, "Failed to read stream content to buffer."); + XmlExitOnFailure(hr, "Failed to read stream content to buffer."); // return value *ppbDest = pbDest; -- cgit v1.2.3-55-g6feb