summaryrefslogtreecommitdiff
path: root/src/utilcode/posterror.cpp
blob: c0f66c4f7f4a40ff9a0754b9918790fb5a20063c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//*****************************************************************************
// PostErrors.cpp
//
// This module contains the error handling/posting code for the engine.  It
// is assumed that all methods may be called by a dispatch client, and therefore
// errors are always posted using IErrorInfo.
//

//*****************************************************************************
#include "stdafx.h"                     // Standard header.

#ifndef FEATURE_UTILCODE_NO_DEPENDENCIES

#include <utilcode.h>                   // Utility helpers.
#include <corerror.h>
#include "../dlls/mscorrc/resource.h"
#include "ex.h"

#include <posterror.h>

#if !defined(lengthof)
#define lengthof(x) (sizeof(x)/sizeof(x[0]))
#endif

// Local prototypes.
HRESULT FillErrorInfo(LPCWSTR szMsg, DWORD dwHelpContext);

void GetResourceCultureCallbacks(
        FPGETTHREADUICULTURENAMES* fpGetThreadUICultureNames,
        FPGETTHREADUICULTUREID* fpGetThreadUICultureId)
{
    WRAPPER_NO_CONTRACT;
    CCompRC::GetDefaultCallbacks(
        fpGetThreadUICultureNames, 
        fpGetThreadUICultureId
    );
}
//*****************************************************************************
// Set callbacks to get culture info
//*****************************************************************************
void SetResourceCultureCallbacks(
    FPGETTHREADUICULTURENAMES fpGetThreadUICultureNames,    
    FPGETTHREADUICULTUREID fpGetThreadUICultureId       // TODO: Don't rely on the LCID, only the name
)
{
    WRAPPER_NO_CONTRACT;
    CCompRC::SetDefaultCallbacks(
        fpGetThreadUICultureNames,
        fpGetThreadUICultureId
    );

}

//*****************************************************************************
// Public function to load a resource string
//*****************************************************************************
STDAPI UtilLoadStringRC(
    UINT iResourceID, 
    __out_ecount(iMax) LPWSTR szBuffer, 
    int iMax, 
    int bQuiet
)
{
    WRAPPER_NO_CONTRACT;
    return UtilLoadResourceString(bQuiet? CCompRC::Optional : CCompRC::Required,iResourceID, szBuffer, iMax);
}

HRESULT UtilLoadResourceString(CCompRC::ResourceCategory eCategory, UINT iResourceID, __out_ecount (iMax) LPWSTR szBuffer, int iMax)
{
    CONTRACTL
    {
        DISABLED(NOTHROW);
        GC_NOTRIGGER;
    }
    CONTRACTL_END;

    HRESULT retVal = E_OUTOFMEMORY;

    SString::Startup();
    EX_TRY
    {
        CCompRC *pResourceDLL = CCompRC::GetDefaultResourceDll();

        if (pResourceDLL != NULL)
        {
            retVal = pResourceDLL->LoadString(eCategory, iResourceID, szBuffer, iMax);
        }
    }
    EX_CATCH
    {
        // Catch any errors and return E_OUTOFMEMORY;
        retVal = E_OUTOFMEMORY;
    }
    EX_END_CATCH(SwallowAllExceptions);

    return retVal;
}

//*****************************************************************************
// Format a Runtime Error message.
//*****************************************************************************
HRESULT __cdecl FormatRuntimeErrorVa(        
    __inout_ecount(cchMsg) WCHAR       *rcMsg,                 // Buffer into which to format.         
    ULONG       cchMsg,                 // Size of buffer, characters.          
    HRESULT     hrRpt,                  // The HR to report.                    
    va_list     marker)                 // Optional args.                       
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
    }
    CONTRACTL_END;
        
    WCHAR       rcBuf[512];             // Resource string.
    HRESULT     hr;
    
    // Ensure nul termination.
    *rcMsg = W('\0');

    // If this is one of our errors or if it is simply a resource ID, then grab the error from the rc file.
    if ((HRESULT_FACILITY(hrRpt) == FACILITY_URT) || (HIWORD(hrRpt) == 0))
    {
        hr = UtilLoadStringRC(LOWORD(hrRpt), rcBuf, NumItems(rcBuf), true);
        if (hr == S_OK)
        {
            _vsnwprintf_s(rcMsg, cchMsg, _TRUNCATE, rcBuf, marker);
        }
    }
    // Otherwise it isn't one of ours, so we need to see if the system can
    // find the text for it.
    else
    {
        if (WszFormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
                0, hrRpt, 0,
                rcMsg, cchMsg, 0/*<TODO>@todo: marker</TODO>*/))
        {
            hr = S_OK;

            // System messages contain a trailing \r\n, which we don't want normally.
            size_t iLen = wcslen(rcMsg);
            if (iLen > 3 && rcMsg[iLen - 2] == '\r' && rcMsg[iLen - 1] == '\n')
                rcMsg[iLen - 2] = '\0';
        }
        else
            hr = HRESULT_FROM_GetLastError();
    }

    // If we failed to find the message anywhere, then issue a hard coded message.
    if (FAILED(hr))
    {
        _snwprintf_s(rcMsg, cchMsg, _TRUNCATE, W("Common Language Runtime Internal error: 0x%08x"), hrRpt);
        DEBUG_STMT(DbgWriteEx(rcMsg));
    }

    return hrRpt;    
} // FormatRuntimeErrorVa

//*****************************************************************************
// Format a Runtime Error message, varargs.
//*****************************************************************************
HRESULT __cdecl FormatRuntimeError(
    __out_ecount(cchMsg) WCHAR       *rcMsg,                 // Buffer into which to format.
    ULONG       cchMsg,                 // Size of buffer, characters.
    HRESULT     hrRpt,                  // The HR to report.
    ...)                                // Optional args.
{
    WRAPPER_NO_CONTRACT;
    va_list     marker;                 // User text.
    va_start(marker, hrRpt);
    hrRpt = FormatRuntimeErrorVa(rcMsg, cchMsg, hrRpt, marker);
    va_end(marker);
    return hrRpt;
}

#ifdef FEATURE_COMINTEROP        
//*****************************************************************************
// Create, fill out and set an error info object.  Note that this does not fill
// out the IID for the error object; that is done elsewhere.
//*****************************************************************************
HRESULT FillErrorInfo(                  // Return status.
    LPCWSTR     szMsg,                  // Error message.
    DWORD       dwHelpContext)          // Help context.
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
    }
    CONTRACTL_END;

    ICreateErrorInfo *pICreateErr = NULL;      // Error info creation Iface pointer.
    IErrorInfo *pIErrInfo = NULL;       // The IErrorInfo interface.
    HRESULT     hr;                     // Return status.

    // Get the ICreateErrorInfo pointer.
    hr = S_OK;
    EX_TRY
    {
        hr = CreateErrorInfo(&pICreateErr);
    }
    EX_CATCH
    {
        hr = GET_EXCEPTION()->GetHR();
    }
    EX_END_CATCH(SwallowAllExceptions);

    if (FAILED(hr))
        return (hr);

    // Set message text description.
    if (FAILED(hr = pICreateErr->SetDescription((LPWSTR) szMsg)))
        goto Exit1;

    // suppress PreFast warning about passing literal string to non-const API.
    // This API (ICreateErrorInfo::SetHelpFile) is documented to take a const argument, but
    // we can't put const in the signature because it would break existing implementors of
    // the API. 
#ifdef _PREFAST_
#pragma prefast(push)
#pragma warning(disable:6298)
#endif

    // Set the help file and help context.
    //<TODO>@todo: we don't have a help file yet.</TODO>
    if (FAILED(hr = pICreateErr->SetHelpFile(const_cast<wchar_t*>(W("complib.hlp")))) ||
        FAILED(hr = pICreateErr->SetHelpContext(dwHelpContext)))
        goto Exit1;

#ifdef _PREFAST_
#pragma prefast(pop)
#endif

    // Get the IErrorInfo pointer.
    if (FAILED(hr = pICreateErr->QueryInterface(IID_IErrorInfo, (PVOID *) &pIErrInfo)))
        goto Exit1;

    // Save the error and release our local pointers.
    {
        // If we get here, we have loaded oleaut32.dll.
        CONTRACT_VIOLATION(ThrowsViolation);
        SetErrorInfo(0L, pIErrInfo);
    }

Exit1:
    pICreateErr->Release();
    if (pIErrInfo) {
        pIErrInfo->Release();
    }
    return hr;
}
#endif // FEATURE_COMINTEROP        

//*****************************************************************************
// This function will post an error for the client.  If the LOWORD(hrRpt) can
// be found as a valid error message, then it is loaded and formatted with
// the arguments passed in.  If it cannot be found, then the error is checked
// against FormatMessage to see if it is a system error.  System errors are
// not formatted so no add'l parameters are required.  If any errors in this
// process occur, hrRpt is returned for the client with no error posted.
//*****************************************************************************
extern "C"
HRESULT __cdecl PostErrorVA(                      // Returned error.
    HRESULT     hrRpt,                  // Reported error.
    va_list     marker)                  // Error arguments.
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        ENTRY_POINT;
    }
    CONTRACTL_END;

#ifdef FEATURE_COMINTEROP        

    const DWORD cchMsg = 4096;
    WCHAR      *rcMsg = (WCHAR*)alloca(cchMsg * sizeof(WCHAR));             // Error message.
    HRESULT     hr;

    BEGIN_ENTRYPOINT_NOTHROW;

    // Return warnings without text.
    if (!FAILED(hrRpt))
        goto ErrExit;        

    // If we are already out of memory or out of stack or the thread is in some bad state,
    // we don't want throw gasoline on the fire by calling ErrorInfo stuff below (which can
    // trigger a delayload of oleaut32.dll). We don't need to embellish transient errors
    // so just return this without text.
    if (Exception::IsTransient(hrRpt))
    {
        goto ErrExit;
    }

    // Format the error.
    FormatRuntimeErrorVa(rcMsg, cchMsg, hrRpt, marker);

    // Turn the error into a posted error message.  If this fails, we still
    // return the original error message since a message caused by our error
    // handling system isn't going to give you a clue about the original error.
    hr = FillErrorInfo(rcMsg, LOWORD(hrRpt));
    _ASSERTE(hr == S_OK);

ErrExit:

    END_ENTRYPOINT_NOTHROW;

#endif // FEATURE_COMINTEROP        

    return (hrRpt);
} // PostErrorVA

#endif //!FEATURE_UTILCODE_NO_DEPENDENCIES

//*****************************************************************************
// This function will post an error for the client.  If the LOWORD(hrRpt) can
// be found as a valid error message, then it is loaded and formatted with
// the arguments passed in.  If it cannot be found, then the error is checked
// against FormatMessage to see if it is a system error.  System errors are
// not formatted so no add'l parameters are required.  If any errors in this
// process occur, hrRpt is returned for the client with no error posted.
//*****************************************************************************
extern "C"
HRESULT __cdecl PostError(
    HRESULT hrRpt,      // Reported error.
    ...)                // Error arguments.
{
#ifndef FEATURE_UTILCODE_NO_DEPENDENCIES
    WRAPPER_NO_CONTRACT;
    va_list     marker;                 // User text.
    va_start(marker, hrRpt);
    hrRpt = PostErrorVA(hrRpt, marker);
    va_end(marker);
#endif //!FEATURE_UTILCODE_NO_DEPENDENCIES
    return hrRpt;
}