summaryrefslogtreecommitdiff
path: root/src/debug/di/shimlocaldatatarget.cpp
blob: 66dd64a02d5ed0394473379b831168bc705c57c3 (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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
//*****************************************************************************

// 
// File: ShimLocalDataTarget.cpp
//
//*****************************************************************************
#include "stdafx.h"
#include "safewrap.h"

#include "check.h" 

#include <limits.h>

#include "shimpriv.h"
#include "shimdatatarget.h"


// The Shim's Live data-target is allowed to call OS APIs directly.
// see code:RSDebuggingInfo#UseDataTarget.
#undef ReadProcessMemory
#undef WriteProcessMemory


class ShimLocalDataTarget : public ShimDataTarget
{
public:
    ShimLocalDataTarget(DWORD processId, HANDLE hProcess);

    ~ShimLocalDataTarget();

    virtual void Dispose();

    //
    // ICorDebugMutableDataTarget.
    //

    virtual HRESULT STDMETHODCALLTYPE GetPlatform( 
        CorDebugPlatform *pPlatform);

    virtual HRESULT STDMETHODCALLTYPE ReadVirtual( 
        CORDB_ADDRESS address,
        BYTE * pBuffer,
        ULONG32 request,
        ULONG32 *pcbRead);

    virtual HRESULT STDMETHODCALLTYPE WriteVirtual( 
        CORDB_ADDRESS address,
        const BYTE * pBuffer,
        ULONG32 request);

    virtual HRESULT STDMETHODCALLTYPE GetThreadContext(
        DWORD dwThreadID,
        ULONG32 contextFlags,
        ULONG32 contextSize,
        BYTE * context);

    virtual HRESULT STDMETHODCALLTYPE SetThreadContext(
        DWORD dwThreadID,
        ULONG32 contextSize,
        const BYTE * context);

    virtual HRESULT STDMETHODCALLTYPE ContinueStatusChanged(
        DWORD dwThreadId,
        CORDB_CONTINUE_STATUS dwContinueStatus);

private:
    // Handle to the process. We own this.
    HANDLE m_hProcess;
};


// Determines whether the target and host are running on compatible platforms.
// Arguments:
//     input: hTargetProcess - handle for the target process
// Return Value: TRUE iff both target and host are both Wow64 or neither is. 
// Note: throws
BOOL CompatibleHostAndTargetPlatforms(HANDLE hTargetProcess)
{
    // get the platform for the host process
    BOOL fHostProcessIsWow64 = FALSE;
    BOOL fSuccess = FALSE;            
    HANDLE hHostProcess = GetCurrentProcess();

    fSuccess = IsWow64Process(hHostProcess, &fHostProcessIsWow64);
    CloseHandle(hHostProcess);
    hHostProcess = NULL;

    if (!fSuccess)
    {
        ThrowHR(HRESULT_FROM_GetLastError());
    }
    
    //  get the platform for the target process
    if (hTargetProcess == NULL)
    {
        ThrowHR(HRESULT_FROM_GetLastError());
    }

    BOOL fTargetProcessIsWow64 = FALSE;
    fSuccess = IsWow64Process(hTargetProcess, &fTargetProcessIsWow64);

    if (!fSuccess)
    {
        ThrowHR(HRESULT_FROM_GetLastError());
    }

    // We don't want to expose the IPC block if one process is x86 and
    // the other is ia64 or amd64
    if (fTargetProcessIsWow64 != fHostProcessIsWow64)
    {
        return FALSE;
    }
    else
    {
        return TRUE;
    }
} // CompatibleHostAndTargetPlatforms

// Helper macro to check for failure conditions at the start of data-target methods.
#define ReturnFailureIfStateNotOk() \
    if (m_hr != S_OK) \
    { \
        return m_hr; \
    }

//---------------------------------------------------------------------------------------
//
// ctor for ShimLocalDataTarget. 
//
// Arguments:
//      processId - pid of live process.
//      hProcess - handle to kernel process object.
//
// Assumptions:
//    Shim takes ownership of handle hProcess.
//

ShimLocalDataTarget::ShimLocalDataTarget(DWORD processId, HANDLE hProcess)    
{
    m_ref = 0;

    m_processId = processId;
    m_hProcess = hProcess;

    m_hr = S_OK;

    m_fpContinueStatusChanged = NULL;
    m_pContinueStatusChangedUserData = NULL;
}

//---------------------------------------------------------------------------------------
//
// dctor for ShimLocalDataTarget. 
//
ShimLocalDataTarget::~ShimLocalDataTarget()
{
    Dispose();
}


//---------------------------------------------------------------------------------------
//
// Dispose all resources and neuter the object.
//
//
//
// Notes:
//    Release all resources (such as the handle to the process we got in the ctor).
//    May be called multiple times.
//    All other non-trivial APIs (eg, not IUnknown) will fail after this.
//

void ShimLocalDataTarget::Dispose()
{
    if (m_hProcess != NULL)
    {
        CloseHandle(m_hProcess);
        m_hProcess = NULL;
    }
    m_hr = CORDBG_E_OBJECT_NEUTERED;
}

//---------------------------------------------------------------------------------------
//
// Construction method for data-target
//
// Arguments:
//      processId - (input) live OS process ID to build a data-target for.
//      ppDataTarget - (output) new data-target instance. This gets addreffed.
//
// Return Value:
//    S_OK on success.
//
// Assumptions:
//    pid must be for local, same architecture, process.
//    Caller must have security permissions for OpenProcess()
//    Caller must release *ppDataTarget.
//

HRESULT BuildPlatformSpecificDataTarget(MachineInfo machineInfo,
                                        DWORD processId, 
                                        ShimDataTarget ** ppDataTarget)
{
    HRESULT hr = S_OK;
    HANDLE hProcess = NULL;
    ShimLocalDataTarget * pLocalDataTarget = NULL;
    
    *ppDataTarget = NULL;
    
    hProcess = OpenProcess(
        PROCESS_DUP_HANDLE        |
        PROCESS_QUERY_INFORMATION |
        PROCESS_TERMINATE         |
        PROCESS_VM_OPERATION      |
        PROCESS_VM_READ           |
        PROCESS_VM_WRITE          |
        SYNCHRONIZE,
        FALSE,
        processId);

    if (hProcess == NULL)
    {
        hr = HRESULT_FROM_GetLastError();
        goto Label_Exit;
    }

    EX_TRY
    {
        if (!CompatibleHostAndTargetPlatforms(hProcess))
        {
            hr = CORDBG_E_UNCOMPATIBLE_PLATFORMS;
            goto Label_Exit;
        }
    }
    EX_CATCH_HRESULT(hr);
    if (FAILED(hr))
    {
        goto Label_Exit;
    }
    pLocalDataTarget = new (nothrow) ShimLocalDataTarget(processId, hProcess);
    if (pLocalDataTarget == NULL)
    {
        hr = E_OUTOFMEMORY;
        goto Label_Exit;
    }

    // ShimLocalDataTarget now has ownership of Handle.
    hProcess = NULL;

    _ASSERTE(SUCCEEDED(hr));
    *ppDataTarget = pLocalDataTarget;
    pLocalDataTarget->AddRef(); // must addref out-parameters

Label_Exit:
    if (FAILED(hr))
    {
        if (hProcess != NULL)
        {
            CloseHandle(hProcess);
        }
        delete pLocalDataTarget;
    }    

    return hr;
}

// impl of interface method ICorDebugDataTarget::GetPlatform
HRESULT STDMETHODCALLTYPE
ShimLocalDataTarget::GetPlatform( 
        CorDebugPlatform *pPlatform)
{
    // Assume that we're running on Windows for now.
#if defined(DBG_TARGET_X86)
    *pPlatform = CORDB_PLATFORM_WINDOWS_X86;
#elif defined(DBG_TARGET_AMD64)
    *pPlatform = CORDB_PLATFORM_WINDOWS_AMD64;
#elif defined(DBG_TARGET_ARM)
    *pPlatform = CORDB_PLATFORM_WINDOWS_ARM;
#elif defined(DBG_TARGET_ARM64)
    *pPlatform = CORDB_PLATFORM_WINDOWS_ARM64;
#else
#error Unknown Processor.
#endif
    return S_OK;
}

// impl of interface method ICorDebugDataTarget::ReadVirtual
HRESULT STDMETHODCALLTYPE
ShimLocalDataTarget::ReadVirtual( 
    CORDB_ADDRESS address,
    PBYTE pBuffer,
    ULONG32 cbRequestSize,
    ULONG32 *pcbRead)
{
    ReturnFailureIfStateNotOk();


    // ReadProcessMemory will fail if any part of the
    // region to read does not have read access.  This
    // routine attempts to read the largest valid prefix
    // so it has to break up reads on page boundaries.

    HRESULT hrStatus = S_OK;
    ULONG32 totalDone = 0;
    SIZE_T read;
    ULONG32 readSize;

    while (cbRequestSize > 0)
    {
        // Calculate bytes to read and don't let read cross
        // a page boundary.
        readSize = OS_PAGE_SIZE - (ULONG32)(address & (OS_PAGE_SIZE - 1));
        readSize = min(cbRequestSize, readSize);

        if (!ReadProcessMemory(m_hProcess, (PVOID)(ULONG_PTR)address,
                               pBuffer, readSize, &read))
        {
            if (totalDone == 0)
            {
                // If we haven't read anything indicate failure.
                hrStatus = HRESULT_FROM_GetLastError();
            }
            break;
        }

        totalDone += (ULONG32)read;
        address += read;
        pBuffer += read;
        cbRequestSize -= (ULONG32)read;
    }

    *pcbRead = totalDone;
    return hrStatus;
}

// impl of interface method ICorDebugMutableDataTarget::WriteVirtual
HRESULT STDMETHODCALLTYPE
ShimLocalDataTarget::WriteVirtual( 
    CORDB_ADDRESS pAddress,
    const BYTE * pBuffer,
    ULONG32 cbRequestSize)
{
    ReturnFailureIfStateNotOk();

    SIZE_T cbWritten;
    BOOL fWriteOk = WriteProcessMemory(m_hProcess, CORDB_ADDRESS_TO_PTR(pAddress), pBuffer, cbRequestSize, &cbWritten);
    if (fWriteOk)
    {
        _ASSERTE(cbWritten == cbRequestSize);  // MSDN docs say this must always be true
        return S_OK;
    }
    else
    {
        return HRESULT_FROM_GetLastError();
    }
}

HRESULT STDMETHODCALLTYPE
ShimLocalDataTarget::GetThreadContext(
    DWORD dwThreadID,
    ULONG32 contextFlags,
    ULONG32 contextSize,
    BYTE * pContext)
{
    ReturnFailureIfStateNotOk();
    // @dbgtodo - Ideally we should cache the thread handles so that we don't need to 
    // open and close the thread handles every time.

    HRESULT hr = E_FAIL;

    if (!CheckContextSizeForBuffer(contextSize, pContext))
    {
        return E_INVALIDARG;
    }
    
    HandleHolder hThread = OpenThread(
        THREAD_GET_CONTEXT | THREAD_SET_CONTEXT | THREAD_QUERY_INFORMATION , 
        FALSE, // thread handle is not inheritable. 
        dwThreadID);

    if (hThread != NULL)
    {
        DT_CONTEXT * pCtx = reinterpret_cast<DT_CONTEXT *>(pContext);
        pCtx->ContextFlags = contextFlags;

        if (DbiGetThreadContext(hThread, pCtx))
        {
            hr = S_OK;
        }
    }

    // hThread destructed automatically
    return hr;
}

// impl of interface method ICorDebugMutableDataTarget::SetThreadContext
HRESULT STDMETHODCALLTYPE
ShimLocalDataTarget::SetThreadContext(
    DWORD dwThreadID,
    ULONG32 contextSize,
    const BYTE * pContext)
{
    ReturnFailureIfStateNotOk();
    HRESULT hr = E_FAIL;

    if (!CheckContextSizeForBuffer(contextSize, pContext))
    {
        return E_INVALIDARG;
    }

    
    HandleHolder hThread = OpenThread(
        THREAD_GET_CONTEXT | THREAD_SET_CONTEXT | THREAD_QUERY_INFORMATION, 
        FALSE, // thread handle is not inheritable.
        dwThreadID);

    if (hThread != NULL)
    {
        if (DbiSetThreadContext(hThread, reinterpret_cast<const DT_CONTEXT *>(pContext)))
        {
            hr = S_OK;
        }
    }

    // hThread destructed automatically
    return hr;
}

// Public implementation of ICorDebugMutableDataTarget::ContinueStatusChanged
HRESULT STDMETHODCALLTYPE
ShimLocalDataTarget::ContinueStatusChanged(
    DWORD dwThreadId,
    CORDB_CONTINUE_STATUS dwContinueStatus)
{
    ReturnFailureIfStateNotOk();
    if (m_fpContinueStatusChanged != NULL)
    {
        return m_fpContinueStatusChanged(m_pContinueStatusChangedUserData, dwThreadId, dwContinueStatus);
    }
    return E_NOTIMPL;
}