summaryrefslogtreecommitdiff
path: root/src/dlls/dbgshim/dbgshim.cpp
blob: 4d6dc5a6e3543d6e806c59de4cf4ae70b4fa5788 (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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
// 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.
//*****************************************************************************
// DbgShim.cpp
// 
// This contains the APIs for creating a telesto managed-debugging session. These APIs serve to locate an
// mscordbi.dll for a given telesto dll and then instantiate the ICorDebug object.
// 
//*****************************************************************************

#include <winwrap.h>
#include <utilcode.h>
#include <log.h>
#include <tlhelp32.h>
#include <cor.h>
#include <sstring.h>
#ifndef FEATURE_PAL
#include <securityutil.h>
#endif

#include <ex.h>
#include <cordebug.h> // for Version nunmbers
#include <pedecoder.h>
#include <getproductversionnumber.h>
#include <dbgenginemetrics.h>

#ifndef FEATURE_PAL
#define PSAPI_VERSION 2
#include <psapi.h>
#endif

#include "dbgshim.h"

/*

// Here's a High-level overview of the API usage

From the debugger:
A debugger calls GetStartupNotificationEvent(pid of debuggee) to get an event, which is signalled when
that process loads a Telesto.  The debugger thus waits on that event, and when it's signalled, it can call
EnumerateCLRs / CloseCLREnumeration to get an array of Telestos in the target process (including the one
that was just loaded). It can then call CreateVersionStringFromModule, CreateDebuggingInterfaceFromVersion 
to attach to any or all Telestos of interest.

From the debuggee:
When a new Telesto spins up, it checks for the startup event (created via GetStartupNotificationEvent), and 
if it exists, it will:
- signal it
- wait on the "Continue" event, thus giving a debugger a chance to attach to the telesto

Notes:
- There is no CreateProcess (Launch) case. All Launching is really an "Early-attach case".

*/

#ifdef FEATURE_PAL
#define INITIALIZE_SHIM { if (PAL_InitializeDLL() != 0) return E_FAIL; }
#else
#define INITIALIZE_SHIM
#endif

// Contract for public APIs. These must be NOTHROW.
#define PUBLIC_CONTRACT \
    INITIALIZE_SHIM \
    CONTRACTL \
    { \
        NOTHROW; \
    } \
    CONTRACTL_END;

//-----------------------------------------------------------------------------
// Public API.
//
// CreateProcessForLaunch - a stripped down version of the Windows CreateProcess
// that can be supported cross-platform.
//
//-----------------------------------------------------------------------------
HRESULT
CreateProcessForLaunch(
    __in LPWSTR lpCommandLine,
    __in BOOL bSuspendProcess,
    __in LPVOID lpEnvironment,
    __in LPCWSTR lpCurrentDirectory,
    __out PDWORD pProcessId,
    __out HANDLE *pResumeHandle)
{
    PUBLIC_CONTRACT;

    PROCESS_INFORMATION processInfo;
    STARTUPINFOW startupInfo;
    DWORD dwCreationFlags = 0;

    ZeroMemory(&processInfo, sizeof(processInfo));
    ZeroMemory(&startupInfo, sizeof(startupInfo));

    startupInfo.cb = sizeof(startupInfo);

    if (bSuspendProcess)
    {
        dwCreationFlags = CREATE_SUSPENDED;
    }

    BOOL result = CreateProcessW(
        NULL,
        lpCommandLine,
        NULL,
        NULL,
        FALSE,
        dwCreationFlags,
        lpEnvironment,
        lpCurrentDirectory,
        &startupInfo,
        &processInfo);

    if (!result) {
        *pProcessId = 0;
        *pResumeHandle = NULL;
        return HRESULT_FROM_WIN32(GetLastError());
    }

    if (processInfo.hProcess != NULL)
    {
        CloseHandle(processInfo.hProcess);
    }

    *pProcessId = processInfo.dwProcessId;
    *pResumeHandle = processInfo.hThread;

    return S_OK;
}

//-----------------------------------------------------------------------------
// Public API.
//
// ResumeProcess - to be used with the CreateProcessForLaunch resume handle
//
//-----------------------------------------------------------------------------
HRESULT
ResumeProcess(
    __in HANDLE hResumeHandle)
{
    PUBLIC_CONTRACT;
    if (ResumeThread(hResumeHandle) == (DWORD)-1)
    {
        return HRESULT_FROM_WIN32(GetLastError());
    }
    return S_OK;
}

//-----------------------------------------------------------------------------
// Public API.
//
// CloseResumeHandle - to be used with the CreateProcessForLaunch resume handle
//
//-----------------------------------------------------------------------------
HRESULT
CloseResumeHandle(
    __in HANDLE hResumeHandle)
{
    PUBLIC_CONTRACT;
    if (!CloseHandle(hResumeHandle))
    {
        return HRESULT_FROM_WIN32(GetLastError());
    }
    return S_OK;
}

#ifdef FEATURE_PAL

static
void
RuntimeStartupHandler(
    char *pszModulePath,
    HMODULE hModule,
    PVOID parameter);

#else // FEATURE_PAL

static
DWORD
StartupHelperThread(
    LPVOID p);

static
HRESULT 
GetContinueStartupEvent(
    DWORD debuggeePID, 
    LPCWSTR szTelestoFullPath,
    __out HANDLE *phContinueStartupEvent);

#endif // FEATURE_PAL

// Functions that we'll look for in the loaded Mscordbi module.
typedef HRESULT (STDAPICALLTYPE *FPCoreCLRCreateCordbObject)(
    int iDebuggerVersion, 
    DWORD pid, 
    HMODULE hmodTargetCLR, 
    IUnknown **ppCordb);

//
// Helper class for RegisterForRuntimeStartup
//
class RuntimeStartupHelper
{
    LONG m_ref;
    DWORD m_processId;
    PSTARTUP_CALLBACK m_callback;
    PVOID m_parameter;
#ifdef FEATURE_PAL
    PVOID m_unregisterToken;
#else
    bool m_canceled;
    HANDLE m_startupEvent;
    DWORD m_threadId;
    HANDLE m_threadHandle;
#endif // FEATURE_PAL

public:
    RuntimeStartupHelper(DWORD dwProcessId, PSTARTUP_CALLBACK pfnCallback, PVOID parameter) :
        m_ref(1),
        m_processId(dwProcessId),
        m_callback(pfnCallback),
        m_parameter(parameter),
#ifdef FEATURE_PAL
        m_unregisterToken(NULL)
#else
        m_canceled(false),
        m_startupEvent(NULL),
        m_threadId(0),
        m_threadHandle(NULL)
#endif // FEATURE_PAL
    {
    }

    ~RuntimeStartupHelper()
    {
#ifndef FEATURE_PAL
        if (m_startupEvent != NULL)
        {
            CloseHandle(m_startupEvent);
        }
        if (m_threadHandle != NULL)
        {
            CloseHandle(m_threadHandle);
        }
#endif // FEATURE_PAL
    }

    LONG AddRef()
    {
        LONG ref = InterlockedIncrement(&m_ref);
        return ref;
    }

    LONG Release()
    {
        LONG ref = InterlockedDecrement(&m_ref);
        if (ref == 0)
        {
            delete this;
        }
        return ref;
    }

#ifdef FEATURE_PAL

    HRESULT Register()
    {
        DWORD pe = PAL_RegisterForRuntimeStartup(m_processId, RuntimeStartupHandler, this, &m_unregisterToken);
        if (pe != NO_ERROR)
        {
            return HRESULT_FROM_WIN32(pe);
        }
        return S_OK;
    }

    void Unregister()
    {
        PAL_UnregisterForRuntimeStartup(m_unregisterToken);
    }

    void InvokeStartupCallback(char *pszModulePath, HMODULE hModule)
    {
        IUnknown *pCordb = NULL;
        HMODULE hMod = NULL;
        HRESULT hr = S_OK;

        // If either of these are NULL, there was an error from the PAL
        // callback. GetLastError returns the error code from the PAL.
        if (pszModulePath == NULL || hModule == NULL)
        {
            hr = HRESULT_FROM_WIN32(GetLastError());
            goto exit;
        }

        PAL_CPP_TRY
        {
            FPCoreCLRCreateCordbObject fpCreate = NULL;
            char dbiPath[MAX_LONGPATH];

            char *pszLast = strrchr(pszModulePath, DIRECTORY_SEPARATOR_CHAR_A);
            if (pszLast == NULL)
            {
                _ASSERT(!"InvokeStartupCallback: can find separator in coreclr path\n");
                hr = E_INVALIDARG;
                goto exit;
            }

            strncpy_s(dbiPath, _countof(dbiPath), pszModulePath, pszLast - pszModulePath);
            strcat_s(dbiPath, _countof(dbiPath), DIRECTORY_SEPARATOR_STR_A MAKEDLLNAME_A("mscordbi"));

            hMod = LoadLibraryA(dbiPath);
            if (hMod == NULL)
            {
                hr = CORDBG_E_DEBUG_COMPONENT_MISSING;
                goto exit;
            }

            fpCreate = (FPCoreCLRCreateCordbObject)GetProcAddress(hMod, "CoreCLRCreateCordbObject");
            if (fpCreate == NULL)
            {
                hr = CORDBG_E_INCOMPATIBLE_PROTOCOL;
                goto exit;
            }

            HRESULT hr = fpCreate(CorDebugVersion_2_0, m_processId, hModule, &pCordb);
            _ASSERTE((pCordb == NULL) == FAILED(hr));
            if (FAILED(hr))
            {
                goto exit;
            }

            m_callback(pCordb, m_parameter, S_OK);
        }
        PAL_CPP_CATCH_ALL
        {
            hr = E_FAIL;
            goto exit;
        }
        PAL_CPP_ENDTRY

    exit:
        if (FAILED(hr))
        {
            _ASSERTE(pCordb == NULL);

            if (hMod != NULL)
            {
                FreeLibrary(hMod);
            }

            // Invoke the callback on error
            m_callback(NULL, m_parameter, hr);
        }
    }

#else // FEATURE_PAL

    HRESULT Register()
    {
        HRESULT hr = GetStartupNotificationEvent(m_processId, &m_startupEvent);
        if (FAILED(hr))
        {
            goto exit;
        }

        // Add a reference for the thread handler
        AddRef();

        m_threadHandle = CreateThread(
            NULL,
            0,
            ::StartupHelperThread,
            this,
            0,
            &m_threadId);

        if (m_threadHandle == NULL)
        {
            hr = E_OUTOFMEMORY;
            Release();
            goto exit;
        }

    exit:
        return hr;
    }

    HRESULT InternalEnumerateCLRs(HANDLE** ppHandleArray, _In_reads_(*pdwArrayLength) LPWSTR** ppStringArray, DWORD* pdwArrayLength)
    {
        int numTries = 0;
        HRESULT hr;

        while (numTries < 25)
        {
            // EnumerateCLRs uses the OS API CreateToolhelp32Snapshot which can return ERROR_BAD_LENGTH or 
            // ERROR_PARTIAL_COPY. If we get either of those, we try wait 1/10th of a second try again (that
            // is the recommendation of the OS API owners)
            hr = EnumerateCLRs(m_processId, ppHandleArray, ppStringArray, pdwArrayLength);
            if ((hr != HRESULT_FROM_WIN32(ERROR_PARTIAL_COPY)) && (hr != HRESULT_FROM_WIN32(ERROR_BAD_LENGTH)))
            {
                break;
            }
            Sleep(100);
            numTries++;
        }

        return hr;
    }

    void WakeRuntimes(HANDLE *handleArray, DWORD arrayLength)
    {
        if (handleArray != NULL)
        {
            for (int i = 0; i < (int)arrayLength; i++)
            {
                HANDLE h = handleArray[i];
                if (h != NULL && h != INVALID_HANDLE_VALUE)
                {
                    SetEvent(h);
                }
            }
        }
    }

    void Unregister()
    {
        m_canceled = true;

        HANDLE *handleArray = NULL;
        LPWSTR *stringArray = NULL;
        DWORD arrayLength = 0;

        // Wake up runtime(s)
        HRESULT hr = InternalEnumerateCLRs(&handleArray, &stringArray, &arrayLength);
        if (SUCCEEDED(hr))
        {
            WakeRuntimes(handleArray, arrayLength);
            CloseCLREnumeration(handleArray, stringArray, arrayLength);
        }

        // Wake up worker thread
        SetEvent(m_startupEvent);

        // Don't need to wake up and wait for the worker thread if called on it
        if (m_threadId != GetCurrentThreadId())
        {
            // Wait for work thread to exit
            WaitForSingleObject(m_threadHandle, INFINITE);
        }
    }

    HRESULT InvokeStartupCallback(bool *pCoreClrExists)
    {
        HANDLE *handleArray = NULL;
        LPWSTR *stringArray = NULL;
        DWORD arrayLength = 0;
        HRESULT hr = S_OK;

        PAL_CPP_TRY
        {
            IUnknown *pCordb = NULL;
            WCHAR verStr[MAX_LONGPATH];
            DWORD verLen;

            *pCoreClrExists = FALSE;

            hr = InternalEnumerateCLRs(&handleArray, &stringArray, &arrayLength);
            if (FAILED(hr))
            {
                goto exit;
            }

            for (int i = 0; i < (int)arrayLength; i++)
            {
                *pCoreClrExists = TRUE;

                hr = CreateVersionStringFromModule(m_processId, stringArray[i], verStr, _countof(verStr), &verLen);
                if (FAILED(hr))
                {
                    goto exit;
                }

                hr = CreateDebuggingInterfaceFromVersion(verStr, &pCordb);
                if (FAILED(hr))
                {
                    goto exit;
                }

                m_callback(pCordb, m_parameter, S_OK);

                // Currently only the first coreclr module in a process is supported
                break;
            }
        }
        PAL_CPP_CATCH_ALL
        {
            hr = E_FAIL;
            goto exit;
        }
        PAL_CPP_ENDTRY

    exit:
        if (*pCoreClrExists)
        {
            // Wake up all the runtimes
            WakeRuntimes(handleArray, arrayLength);
        }
        CloseCLREnumeration(handleArray, stringArray, arrayLength);

        return hr;
    }

    void StartupHelperThread()
    {
        bool coreclrExists = false;

        HRESULT hr = InvokeStartupCallback(&coreclrExists);
        // Because the target process is suspended on create, the toolhelp apis fail with the below errors even
        // with the retry logic in InternalEnumerateCLRs.
        if (SUCCEEDED(hr) || (hr == HRESULT_FROM_WIN32(ERROR_PARTIAL_COPY)) || (hr == HRESULT_FROM_WIN32(ERROR_BAD_LENGTH)))
        {
            if (!coreclrExists && !m_canceled)
            {
                // Wait until the coreclr runtime (debuggee) starts up
                if (WaitForSingleObject(m_startupEvent, INFINITE) == WAIT_OBJECT_0)
                {
                    if (!m_canceled)
                    {
                        hr = InvokeStartupCallback(&coreclrExists);
                        if (SUCCEEDED(hr))
                        {
                            // We should always find a coreclr module
                            _ASSERTE(coreclrExists);
                        }
                    }
                }
                else
                {
                    hr = HRESULT_FROM_WIN32(GetLastError());
                }
            }
        }

        if (FAILED(hr) && !m_canceled)
        {
            m_callback(NULL, m_parameter, hr);
        }
    }

#endif // FEATURE_PAL
};

#ifdef FEATURE_PAL

static
void
RuntimeStartupHandler(char *pszModulePath, HMODULE hModule, PVOID parameter)
{
    RuntimeStartupHelper *helper = (RuntimeStartupHelper *)parameter;
    helper->InvokeStartupCallback(pszModulePath, hModule);
}

#else // FEATURE_PAL

static
DWORD 
StartupHelperThread(LPVOID p)
{
    RuntimeStartupHelper *helper = (RuntimeStartupHelper *)p;
    helper->StartupHelperThread();
    helper->Release();
    return 0;
}

#endif // FEATURE_PAL

//-----------------------------------------------------------------------------
// Public API.
//
// RegisterForRuntimeStartup -- executes the callback when the coreclr runtime 
//      starts in the specified process. The callback is passed the proper ICorDebug
//      instance for the version of the runtime or an error if something fails. This
//      API works for launch and attach (and even the attach scenario if the runtime
//      hasn't been loaded yet) equally on both xplat and Windows. The callback is 
//      always called on a separate thread. This API returns immediately.
//
//      The callback is invoked when the coreclr runtime module is loaded during early 
//      initialization. The runtime is blocked during initialization until the callback 
//      returns.
//
//      If the runtime is already loaded in the process (as in the normal attach case),
//      the callback is executed and the runtime is not blocked.
//
//      The callback is always invoked on a separate thread and this API returns immediately.
//
//      Only the first coreclr module instance found in the target process is currently 
//      supported.
//
// dwProcessId -- process id of the target process
// pfnCallback -- invoked when coreclr runtime starts
// parameter -- data to pass to callback
// ppUnregisterToken -- pointer to put the UnregisterForRuntimeStartup token.
//
//-----------------------------------------------------------------------------
HRESULT
RegisterForRuntimeStartup(
    __in DWORD dwProcessId,
    __in PSTARTUP_CALLBACK pfnCallback,
    __in PVOID parameter,
    __out PVOID *ppUnregisterToken)
{
    PUBLIC_CONTRACT;

    if (pfnCallback == NULL || ppUnregisterToken == NULL)
    {
        return E_INVALIDARG;
    }

    HRESULT hr = S_OK;

    RuntimeStartupHelper *helper = new (nothrow) RuntimeStartupHelper(dwProcessId, pfnCallback, parameter);
    if (helper == NULL)
    {
        hr = E_OUTOFMEMORY;
    }
    else
    {
        hr = helper->Register();
        if (FAILED(hr))
        {
            helper->Release();
            helper = NULL;
        }
    }

    *ppUnregisterToken = helper;
    return hr;
}

//-----------------------------------------------------------------------------
// Public API.
//
// UnregisterForRuntimeStartup -- stops/cancels runtime startup notification. Needs
//      to be called during the debugger's shutdown to cleanup the internal data.
//
//    This API can be called in the startup callback. Otherwise, it will block until
//    the callback thread finishes and no more callbacks will be initiated after this
//    API returns.
//
// pUnregisterToken -- unregister token from RegisterForRuntimeStartup or NULL.
//-----------------------------------------------------------------------------
HRESULT
UnregisterForRuntimeStartup(
    __in PVOID pUnregisterToken)
{
    PUBLIC_CONTRACT;

    if (pUnregisterToken != NULL)
    {
        RuntimeStartupHelper *helper = (RuntimeStartupHelper *)pUnregisterToken;
        helper->Unregister();
        helper->Release();
    }

    return S_OK;
}

//-----------------------------------------------------------------------------
// Public API.
//
// GetStartupNotificationEvent -- creates a global, named event that is PID-
//      qualified (i.e. process global) that is used to notify the debugger of 
//      any CLR instance startup in the process.
// 
// debuggeePID -- process ID of the target process
// phStartupEvent -- out param for the returned event handle
//
//-----------------------------------------------------------------------------
#define StartupNotifyEventNamePrefix W("TelestoStartupEvent_")
#define SessionIdPrefix W("Session\\")

// NULL terminator is included in sizeof(StartupNotifyEventNamePrefix)    
const int cchEventNameBufferSize = (sizeof(StartupNotifyEventNamePrefix) + sizeof(SessionIdPrefix)) / sizeof(WCHAR) 
                                    + 8  // + hex process id DWORD 
                                    + 10 // + decimal session id DWORD 
                                    + 1;  // '\' after session id
                                        
HRESULT 
GetStartupNotificationEvent(
    __in DWORD debuggeePID,
    __out HANDLE* phStartupEvent)
{
    PUBLIC_CONTRACT;

    if (phStartupEvent == NULL)
        return E_INVALIDARG;

#ifndef FEATURE_PAL
    HRESULT hr;
    DWORD currentSessionId = 0, debuggeeSessionId = 0;
    if (!ProcessIdToSessionId(GetCurrentProcessId(), &currentSessionId))
    {
        return HRESULT_FROM_WIN32(GetLastError());   
    }

    if (!ProcessIdToSessionId(debuggeePID, &debuggeeSessionId))
    {
        return HRESULT_FROM_WIN32(GetLastError());   
    }

    // Here we could just add "Global\" to the event name and this would solve cross-session debugging scenario, but that would require event name change 
    // in CoreCLR, and break backward compatibility. Instead if we see that debugee is in a different session, we explicitly create startup event 
    // in that session (by adding "Session\#\"). We could do it even for our own session, but that's vaguely documented behavior and we'd 
    // like to use it as little as possible.
    WCHAR szEventName[cchEventNameBufferSize];
    if (currentSessionId == debuggeeSessionId)
    {
        swprintf_s(szEventName, cchEventNameBufferSize, StartupNotifyEventNamePrefix W("%08x"), debuggeePID);
    } 
    else
    {
        swprintf_s(szEventName, cchEventNameBufferSize, SessionIdPrefix W("%u\\") StartupNotifyEventNamePrefix W("%08x"), debuggeeSessionId, debuggeePID);  
    }

    // Determine an appropriate ACL and SECURITY_ATTRIBUTES to apply to this event.  We use the same logic
    // here as the debugger uses for other events (like the setup-sync-event).  Specifically, this does
    // the work to ensure a debuggee running as another user, or with a low integrity level can signal 
    // this event.
    PACL pACL = NULL;
    SECURITY_ATTRIBUTES * pSA = NULL;
    IfFailRet(SecurityUtil::GetACLOfPid(debuggeePID, &pACL));
    SecurityUtil secUtil(pACL);

    HandleHolder hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, debuggeePID);
    if (hProcess == NULL)
    {
        return HRESULT_FROM_WIN32(GetLastError());
    }

    IfFailRet(secUtil.Init(hProcess));
    IfFailRet(secUtil.GetSA(&pSA));

    HANDLE startupEvent = WszCreateEvent(pSA, 
                                FALSE,  // false -> auto-reset
                                FALSE,  // false -> initially non-signaled
                                szEventName);
    DWORD dwStatus = GetLastError();
    if (NULL == startupEvent)
    {
        // if the event already exists, try to open it, otherwise we fail.

        if (ERROR_ALREADY_EXISTS != dwStatus)
            return E_FAIL;

        startupEvent = WszOpenEvent(SYNCHRONIZE, FALSE, szEventName);

        if (NULL == startupEvent)
            return E_FAIL;
    }

    *phStartupEvent = startupEvent;
    return S_OK;
#else
    *phStartupEvent = NULL;
    return E_NOTIMPL;
#endif // FEATURE_PAL
}
// Refer to clr\src\mscoree\mscorwks_ntdef.src.
const WORD kOrdinalForMetrics = 2;

//-----------------------------------------------------------------------------
// The CLR_ENGINE_METRICS is a static struct in coreclr.dll.  It's exported by coreclr.dll at ordinal 2 in
// the export address table.  This function returns the CLR_ENGINE_METRICS and the RVA to the continue
// startup event for a coreclr.dll specified by its full path.
// 
// Arguments:
//   szTelestoFullPath - (in) full path of telesto
//   pEngineMetricsOut - (out) filled in based on metrics from target telesto. 
//   pdwRVAContinueStartupEvent - (out; optional) return the RVA to the continue startup event
//   
// Returns:
//   Throwss on error.
//   
// Notes:
//     When VS pops up the attach dialog box, it is actually enumerating all the processes on the machine 
//     (if the appropiate checkbox is checked) and checking each process to see if a DLL named "coreclr.dll" 
//     is loaded.  If there is one, we will go down this code path, but there is no guarantee that the 
//     coreclr.dll is ours.  A malicious user can be running a process with a bogus coreclr.dll loaded.
//     That's why we need to be extra careful reading coreclr.dll in this function.
//-----------------------------------------------------------------------------
static
void 
GetTargetCLRMetrics(
    LPCWSTR szTelestoFullPath, 
    CLR_ENGINE_METRICS *pEngineMetricsOut, 
    DWORD *pdwRVAContinueStartupEvent = NULL)
{
    CONTRACTL
    {
        THROWS;
    }
    CONTRACTL_END;

    CONSISTENCY_CHECK(szTelestoFullPath != NULL);
    CONSISTENCY_CHECK(pEngineMetricsOut != NULL);

#ifndef FEATURE_PAL
    HRESULT hr = S_OK;

    HandleHolder hCoreClrFile = WszCreateFile(szTelestoFullPath, 
                                              GENERIC_READ, 
                                              FILE_SHARE_READ, 
                                              NULL,                 // default security descriptor 
                                              OPEN_EXISTING, 
                                              FILE_ATTRIBUTE_NORMAL, 
                                              NULL);
    if (hCoreClrFile == INVALID_HANDLE_VALUE)
    {
        ThrowLastError();
    }

    DWORD cbFileHigh = 0;
    DWORD cbFileLow = GetFileSize(hCoreClrFile, &cbFileHigh);
    if (cbFileLow == INVALID_FILE_SIZE)
    {
        ThrowLastError();
    }

    // A maximum size of 100 MB should be more than enough for coreclr.dll.
    if ((cbFileHigh != 0) || (cbFileLow > 0x6400000) || (cbFileLow == 0))
    {
        ThrowHR(E_FAIL);
    }

    HandleHolder hCoreClrMap = WszCreateFileMapping(hCoreClrFile, NULL, PAGE_READONLY, cbFileHigh, cbFileLow, NULL);
    if (hCoreClrMap == NULL)
    {
        ThrowLastError();
    }

    MapViewHolder hCoreClrMapView = MapViewOfFile(hCoreClrMap, FILE_MAP_READ, 0, 0, 0);
    if (hCoreClrMapView == NULL)
    {
        ThrowLastError();
    }

    // At this point we have read the file into the process, but be careful because it is flat, i.e. not mapped.
    // We need to translate RVAs into file offsets, but fortunately PEDecoder can do all of that for us.
    PEDecoder pedecoder(hCoreClrMapView, (COUNT_T)cbFileLow);

    // Check the NT headers.
    if (!pedecoder.CheckNTFormat())
    {
        ThrowHR(E_FAIL);
    }

    // At this point we can safely read anything in the NT headers.

    if (!pedecoder.HasDirectoryEntry(IMAGE_DIRECTORY_ENTRY_EXPORT) || 
        !pedecoder.CheckDirectoryEntry(IMAGE_DIRECTORY_ENTRY_EXPORT))
    {
        ThrowHR(E_FAIL);
    }
    IMAGE_DATA_DIRECTORY * pExportDirectoryEntry = pedecoder.GetDirectoryEntry(IMAGE_DIRECTORY_ENTRY_EXPORT);

    // At this point we can safely read the IMAGE_DATA_DIRECTORY of the export directory.

    if (!pedecoder.CheckDirectory(pExportDirectoryEntry))
    {
        ThrowHR(E_FAIL);
    }
    IMAGE_EXPORT_DIRECTORY * pExportDir = 
        reinterpret_cast<IMAGE_EXPORT_DIRECTORY *>(pedecoder.GetDirectoryData(pExportDirectoryEntry));

    // At this point we have checked that everything in the export directory is readable.

    // Check to make sure the ordinal we have fits in the table in the export directory.
    // The "base" here is like the starting index of the arrays in the export directory.
    if ((pExportDir->Base > kOrdinalForMetrics) ||
        (pExportDir->NumberOfFunctions < (kOrdinalForMetrics - pExportDir->Base)))
    {
        ThrowHR(E_FAIL);
    }
    DWORD dwRealIndex = kOrdinalForMetrics - pExportDir->Base;

    // Check that we can read the RVA at the element (specified by the ordinal) in the export address table.
    // Then read the RVA to the CLR_ENGINE_METRICS.
    if (!pedecoder.CheckRva(pExportDir->AddressOfFunctions, (dwRealIndex + 1) * sizeof(DWORD)))
    {
        ThrowHR(E_FAIL);
    }
    DWORD rvaMetrics = *reinterpret_cast<DWORD *>(
        pedecoder.GetRvaData(pExportDir->AddressOfFunctions + dwRealIndex * sizeof(DWORD)));

    // Make sure we can safely read the CLR_ENGINE_METRICS at the RVA we have retrieved.
    if (!pedecoder.CheckRva(rvaMetrics, sizeof(*pEngineMetricsOut)))
    {
        ThrowHR(E_FAIL);
    }

    // Finally, copy the CLR_ENGINE_METRICS into the output buffer.
    CLR_ENGINE_METRICS * pMetricsInFile = reinterpret_cast<CLR_ENGINE_METRICS *>(pedecoder.GetRvaData(rvaMetrics));
    *pEngineMetricsOut = *pMetricsInFile;

    // At this point, we have retrieved the CLR_ENGINE_METRICS from the target process and 
    // stored it in output buffer.
    if (pEngineMetricsOut->cbSize != sizeof(*pEngineMetricsOut))
    {
        ThrowHR(E_INVALIDARG);
    }

    if (pdwRVAContinueStartupEvent != NULL)
    {
        // Note that the pointer stored in the CLR_ENGINE_METRICS is assuming that the DLL is loaded at its
        // preferred base address.  We need to translate that to an RVA.
        if (((SIZE_T)pEngineMetricsOut->phContinueStartupEvent < (SIZE_T)pedecoder.GetPreferredBase()) ||
            ((SIZE_T)pEngineMetricsOut->phContinueStartupEvent > 
                ((SIZE_T)pedecoder.GetPreferredBase() + pedecoder.GetVirtualSize())))
        {
            ThrowHR(E_FAIL);
        }

        DWORD rvaContinueStartupEvent = 
            (DWORD)((SIZE_T)pEngineMetricsOut->phContinueStartupEvent - (SIZE_T)pedecoder.GetPreferredBase());

        // We can't use CheckRva() here because for unmapped files it actually checks the RVA against the file 
        // size as well.  We have already checked the RVA above.  Now just check that the entire HANDLE
        // falls in the loaded image.
        if ((rvaContinueStartupEvent + sizeof(HANDLE)) > pedecoder.GetVirtualSize())
        {
            ThrowHR(E_FAIL);
        }

        *pdwRVAContinueStartupEvent = rvaContinueStartupEvent;
    }

    // Holder will call FreeLibrary()
#else 
    //TODO: So far on POSIX systems we only support one version of debugging interface
    // in future we might want to detect it the same way we do it on Windows.
    pEngineMetricsOut->cbSize = sizeof(*pEngineMetricsOut);
    pEngineMetricsOut->dwDbiVersion = CorDebugLatestVersion; 
    pEngineMetricsOut->phContinueStartupEvent = NULL;

    if (pdwRVAContinueStartupEvent != NULL)
    {
        *pdwRVAContinueStartupEvent = NULL;
    }
#endif // FEATURE_PAL
}

// Returns true iff the module represents CoreClr.
static
bool 
IsCoreClr(
    const WCHAR* pModulePath)
{
    _ASSERTE(pModulePath != NULL); 

    //strip off everything up to and including the last slash in the path to get name
    const WCHAR* pModuleName = pModulePath;
    while(wcschr(pModuleName, DIRECTORY_SEPARATOR_CHAR_W) != NULL)
    {
        pModuleName = wcschr(pModuleName, DIRECTORY_SEPARATOR_CHAR_W);
        pModuleName++; // pass the slash
    }

    // MAIN_CLR_MODULE_NAME_W gets changed for desktop builds, so we directly code against the CoreClr name.
    return _wcsicmp(pModuleName, MAKEDLLNAME_W(W("coreclr"))) == 0;
}

// Returns true iff the module sent is named CoreClr.dll and has the metrics expected in it's PE header.
static
bool 
IsCoreClrWithGoodHeader(
    HANDLE hProcess,
    HMODULE hModule)
{
    HRESULT hr = S_OK;

    WCHAR modulePath[MAX_LONGPATH];
    modulePath[0] = W('\0');
    if(0 == GetModuleFileNameEx(hProcess, hModule, modulePath, MAX_LONGPATH))
    {
        return false;
    }
    else
    {
        modulePath[MAX_LONGPATH-1] = 0; // on older OS'es this doesn't get null terminated automatically on truncation
    }

    if (IsCoreClr(modulePath))
    {
        // We don't care about the particular error returned, only that
        // what we tried wasn't a 'real' coreclr.dll.
        EX_TRY
        {
            CLR_ENGINE_METRICS metricsStruct;
            GetTargetCLRMetrics(modulePath, &metricsStruct); // throws

            // If we got this far, then we think it's a good one.
        }
        EX_CATCH_HRESULT(hr);
        return (hr == S_OK);
    }

    return false;
}

//-----------------------------------------------------------------------------
// Public API.
//
// EnumerateCLRs -- returns an array of full paths to each coreclr.dll in the
//      target process.  Also returns a corresponding array of continue events
//      that *MUST* be signaled by the caller in order to allow the CLRs in the
//      target process to proceed.
//
// debuggeePID -- process ID of the target process
// ppHandleArrayOut -- out parameter in which an array of handles is returned.
//      the length of this array is returned by the pdwArrayLengthOut out param
// ppStringArrayOut -- out parameter in which an array of full paths to each
//      coreclr.dll in the process is returned.  The length of this array is the
//      same as the handle array and is returned by the pdwArrayLengthOut param
// pdwArrayLengthOut -- out param in which the length of the two returned arrays
//      are returned.
//
// Notes:
//   Callers use  code:CloseCLREnumeration to free the returned arrays.
//-----------------------------------------------------------------------------
HRESULT 
EnumerateCLRs(
    DWORD debuggeePID, 
    __out HANDLE** ppHandleArrayOut,
    __out LPWSTR** ppStringArrayOut,
    __out DWORD* pdwArrayLengthOut)
{
    PUBLIC_CONTRACT;

    // All out params must be non-NULL.
    if ((ppHandleArrayOut == NULL) || (ppStringArrayOut == NULL) || (pdwArrayLengthOut == NULL))
        return E_INVALIDARG;

    HandleHolder hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, debuggeePID);
    if (NULL == hProcess)
        return E_FAIL;

    // These shouldn't be freed
    HMODULE modules[1000];
    DWORD cbNeeded;
    if(!EnumProcessModules(hProcess, modules, sizeof(modules), &cbNeeded))
    {
        return HRESULT_FROM_WIN32(GetLastError());
    }

    //
    // count the number of coreclr.dll entries
    //
    DWORD count = 0;
    DWORD countModules = cbNeeded/sizeof(HMODULE);
    for(DWORD i = 0; i < countModules; i++)
    {
        if (IsCoreClrWithGoodHeader(hProcess, modules[i]))
        {
            count++;
        }
    }

    // If we didn't find anything, no point in continuing.
    if (count == 0)
    {
        *ppHandleArrayOut = NULL;
        *ppStringArrayOut = NULL;
        *pdwArrayLengthOut = 0;

        return S_OK;
    }

    size_t cbEventArrayData     = sizeof(HANDLE) * count;               // event array data
    size_t cbStringArrayData    = sizeof(LPWSTR) * count;               // string array data
    size_t cbStringData         = sizeof(WCHAR)  * count * MAX_LONGPATH;    // strings data
    size_t cbBuffer             = cbEventArrayData + cbStringArrayData + cbStringData;

    BYTE* pOutBuffer = new (nothrow) BYTE[cbBuffer];
    if (NULL == pOutBuffer)
        return E_OUTOFMEMORY;

    ZeroMemory(pOutBuffer, cbBuffer);

    HANDLE* pEventArray     = (HANDLE*) &pOutBuffer[0];
    LPWSTR* pStringArray    = (LPWSTR*) &pOutBuffer[cbEventArrayData];
    WCHAR*  pStringData     = (WCHAR*)  &pOutBuffer[cbEventArrayData + cbStringArrayData];
    DWORD idx = 0;

    // There's no guarantee that another coreclr hasn't loaded already anyhow,
    // so if we get the corner case that the second time through we enumerate
    // more coreclrs, just ignore the extras.
    // This mismatch could happen when
    // a) take module shapshot
    // b) underlying file is opened for exclusive access/deleted/moved/ACL'd etc so we can't open it
    // c) count is determined
    // d) file is closed/copied/moved/ACL'd etc so we can find/open it again
    // e) this loop runs
    // Thus the loop checks idx < count

    for(DWORD i = 0; i < countModules && idx < count; i++)
    {
        if (IsCoreClrWithGoodHeader(hProcess, modules[i]))
        {
            // fill in path
            pStringArray[idx] = &pStringData[idx * MAX_LONGPATH];
            GetModuleFileNameEx(hProcess, modules[i], pStringArray[idx], MAX_LONGPATH);

#ifndef FEATURE_PAL
            // fill in event handle -- if GetContinueStartupEvent fails, it will still return 
            // INVALID_HANDLE_VALUE in hContinueStartupEvent, which is what we want.  we don't
            // want to bail out of the enumeration altogether if we can't get an event from
            // one telesto.

            HANDLE hContinueStartupEvent = INVALID_HANDLE_VALUE;
            HRESULT hr = GetContinueStartupEvent(debuggeePID, pStringArray[idx], &hContinueStartupEvent);
            _ASSERTE(SUCCEEDED(hr) == (hContinueStartupEvent != INVALID_HANDLE_VALUE));

            pEventArray[idx] = hContinueStartupEvent;
#else
            pEventArray[idx] = NULL;
#endif // FEATURE_PAL

            idx++;
        }
    }

    // Patch things up so CloseCLREnumeration() can still have it's
    // pointer arithmatic checks succeed, and the user doesn't see a 'dead' entry.
    // Specifically, it's expected that pEventArray and pStringArray point to the
    // same contiguous chunk of memory so that pStringArray == pEventArray[*pdwArrayLengthOut].
    // This is expected to be a very rare case.
    if (idx < count)
    {
        // Move the string pointers back.
        LPWSTR* pSATemp = (LPWSTR*)&pOutBuffer[sizeof(HANDLE)*idx];
        for (DWORD i = 0; i < idx; i++)
        {
            pSATemp[i] = pStringArray[i];
        }

        // Fix up string array pointer.
        pStringArray = (LPWSTR*)&pOutBuffer[sizeof(HANDLE)*idx];

        // Strings themselves don't need moved.
    }

    *ppHandleArrayOut = pEventArray;
    *ppStringArrayOut = pStringArray;
    *pdwArrayLengthOut = idx;

    return S_OK;
}

//-----------------------------------------------------------------------------
// Public API.
//
// CloseCLREnumeration -- used to free resources allocated by EnumerateCLRs
//
// pHandleArray -- handle array originally returned by EnumerateCLRs
// pStringArray -- string array originally returned by EnumerateCLRs
// dwArrayLength -- array length originally returned by EnumerateCLRs
//
//-----------------------------------------------------------------------------
HRESULT 
CloseCLREnumeration(
    __in HANDLE* pHandleArray,
    __in LPWSTR* pStringArray,
    __in DWORD dwArrayLength)
{
    PUBLIC_CONTRACT;

    if ((pHandleArray + dwArrayLength) != (HANDLE*)pStringArray)
        return E_INVALIDARG;

    // It's possible that EnumerateCLRs found nothing to enumerate, in which case
    // pointers and count are zeroed.  If a debugger calls this function in that
    // case, let's not try to delete [] on NULL.
    if (pHandleArray == NULL)
        return S_OK;

#ifndef FEATURE_PAL
    for (DWORD i = 0; i < dwArrayLength; i++)
    {
        HANDLE hTemp = pHandleArray[i];
        if (   (NULL != hTemp)
            && (INVALID_HANDLE_VALUE != hTemp))
        {
            CloseHandle(hTemp);
        }
    }
#endif // FEATURE_PAL

    delete[] pHandleArray;
    return S_OK;
}

//-----------------------------------------------------------------------------
// Get the base address of a module from the remote process.
//
// Returns:
//  - On success, base address (in remote process) of mscoree, 
//  - NULL  if the module is not loaded.
//  - else Throws. *ppBaseAddress = NULL
//-----------------------------------------------------------------------------
static
BYTE* 
GetRemoteModuleBaseAddress(
    DWORD dwPID,
    LPCWSTR szFullModulePath)
{
    CONTRACTL
    {
        THROWS;
    }
    CONTRACTL_END;

    HandleHolder hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwPID);
    if (NULL == hProcess)
    {
        ThrowHR(E_FAIL);
    }

    // These shouldn't be freed
    HMODULE modules[1000];
    DWORD cbNeeded;
    if(!EnumProcessModules(hProcess, modules, sizeof(modules), &cbNeeded))
    {
        ThrowHR(HRESULT_FROM_WIN32(GetLastError()));
    }

    DWORD countModules = min(cbNeeded, sizeof(modules)) / sizeof(HMODULE);
    for(DWORD i = 0; i < countModules; i++)
    {
        WCHAR modulePath[MAX_LONGPATH];
        if(0 == GetModuleFileNameEx(hProcess, modules[i], modulePath, MAX_LONGPATH))
        {
            continue;
        }
        else
        {
            modulePath[MAX_LONGPATH-1] = 0; // on older OS'es this doesn't get null terminated automatically
            if (_wcsicmp(modulePath, szFullModulePath) == 0)
            {                
                return (BYTE*) modules[i];
            }
        }
    }

    // Successfully enumerated modules but couldn't find the requested one.
    return NULL;
}

// DBI version: max 8 hex chars
// SEMICOLON: 1
// PID: max 8 hex chars
// SEMICOLON: 1
// HMODULE: max 16 hex chars (64-bit)
// SEMICOLON: 1
// PROTOCOL STRING: (variable length)
const int c_iMaxVersionStringLen = 8 + 1 + 8 + 1 + 16; // 64-bit hmodule
const int c_iMinVersionStringLen = 8 + 1 + 8 + 1 + 8; // 32-bit hmodule
const int c_idxFirstSemi = 8;
const int c_idxSecondSemi = 17;
const WCHAR *c_versionStrFormat = W("%08x;%08x;%p");

//-----------------------------------------------------------------------------
// Public API.
// Given a path to a coreclr.dll, get the Version string.
// 
// Arguments:
//   pidDebuggee - OS process ID of debuggee.
//   szModuleName - a full or relative path to a valid coreclr.dll in the debuggee.
//   pBuffer - the buffer to fill the version string into
//     if pdwLength != NULL, we set *pdwLength to the length of the version string on 
//     output (including the null terminator).
//   cchBuffer - length of pBuffer on input in characters
//
// Returns:
//  S_OK - on success.
//  E_INVALIDARG - 
//  HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER) if the buffer is too small.
//  COR_E_FILENOTFOUND - module is not found in a given debugee process
//  
// Notes:
//   The null-terminated version string including null, is 
//   copied to pVersion on output. Thus *pdwLength == wcslen(pBuffer)+1.
//   The version string is an opaque string that can only be passed back to other 
//   DbgShim APIs.
//-----------------------------------------------------------------------------
HRESULT 
CreateVersionStringFromModule(
    __in DWORD pidDebuggee,
    __in LPCWSTR szModuleName,
    __out_ecount_part(cchBuffer, *pdwLength) LPWSTR pBuffer,
    __in DWORD cchBuffer,
    __out DWORD* pdwLength)
{
    PUBLIC_CONTRACT;

    if (szModuleName == NULL)
    {
        return E_INVALIDARG;
    }

    // it is ok for both to be null (to query the required buffer size) or both to be non-null.
    if ((pBuffer == NULL) != (cchBuffer == 0))
    {
        return E_INVALIDARG;
    }

    SIZE_T nLengthWithNull = c_iMaxVersionStringLen + 1;
    _ASSERTE(nLengthWithNull > 0);
    
    if (pdwLength != NULL)
    {
        *pdwLength = (DWORD) nLengthWithNull;
    }
    
    if (nLengthWithNull > cchBuffer)
    {
        return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
    }
    else if (pBuffer != NULL)
    {

        HRESULT hr = S_OK;
        EX_TRY
        {        
            CorDebugInterfaceVersion dbiVersion = CorDebugInvalidVersion;
            BYTE* hmodTargetCLR = NULL;
            CLR_ENGINE_METRICS metricsStruct;

            GetTargetCLRMetrics(szModuleName, &metricsStruct); // throws
            dbiVersion = (CorDebugInterfaceVersion) metricsStruct.dwDbiVersion;

            hmodTargetCLR = GetRemoteModuleBaseAddress(pidDebuggee, szModuleName); // throws
            if (hmodTargetCLR == NULL)
            {
                hr = COR_E_FILENOTFOUND;
            } 
            else 
            {
                swprintf_s(pBuffer, cchBuffer, c_versionStrFormat, dbiVersion, pidDebuggee, hmodTargetCLR);    
            }
        }
        EX_CATCH_HRESULT(hr);
        return hr;
    }

    return S_OK;
}

//-----------------------------------------------------------------------------
// Parse a version string into useful data.
// 
// Arguments:
//    szDebuggeeVersion - (in) null terminated version string 
//    piDebuggerVersion - (out) interface number that the debugger expects to use.
//    pdwPidDebuggee    - (out) OS process ID of debuggee
//    phmodTargetCLR    - (out) module handle of CoreClr within the debuggee.
//
// Returns:
//    S_OK on success. Else failures.
//    
// Notes:
//    The version string is coming from the target CoreClr and in the case of a corrupted target, could be
//    an arbitrary string. It should be treated as untrusted public input.
//-----------------------------------------------------------------------------
static
HRESULT 
ParseVersionString(
    LPCWSTR szDebuggeeVersion, 
    CorDebugInterfaceVersion *piDebuggerVersion,
    DWORD *pdwPidDebuggee, 
    HMODULE *phmodTargetCLR)
{
    if ((piDebuggerVersion == NULL) ||
        (pdwPidDebuggee == NULL) ||
        (phmodTargetCLR == NULL) ||
        (wcslen(szDebuggeeVersion) < c_iMinVersionStringLen) ||
        (W(';') != szDebuggeeVersion[c_idxFirstSemi]) ||
        (W(';') != szDebuggeeVersion[c_idxSecondSemi]))
    {
        return E_INVALIDARG;
    }

    int numFieldsAssigned = swscanf_s(szDebuggeeVersion, c_versionStrFormat, piDebuggerVersion, pdwPidDebuggee, phmodTargetCLR);
    if (numFieldsAssigned != 3)
    {
        return E_FAIL;
    }

    return S_OK;
}

//-----------------------------------------------------------------------------
// Appends "\mscordbi.dll" to the path. This converts a directory name into the full path to mscordbi.dll.
// 
// Arguments:
//    szFullDbiPath - (in/out): on input, the directory containing dbi. On output, the full path to dbi.dll.
//-----------------------------------------------------------------------------
static
void 
AppendDbiDllName(SString & szFullDbiPath)
{
    const WCHAR * pDbiDllName = DIRECTORY_SEPARATOR_STR_W MAKEDLLNAME_W(W("mscordbi"));
    szFullDbiPath.Append(pDbiDllName);
}

//-----------------------------------------------------------------------------
// Return a path to the dbi next to the runtime, if present.
// 
// Arguments:
//    pidDebuggee - OS process ID of debuggee
//    hmodTargetCLR - handle to CoreClr within debuggee process
//    szFullDbiPath - (out) the full path of Mscordbi.dll next to the debuggee's CoreClr.dll.
// 
// Notes:
//    This just calculates a filename and does not determine if the file actually exists. 
//-----------------------------------------------------------------------------
static
void 
GetDbiFilenameNextToRuntime(
    DWORD pidDebuggee, 
    HMODULE hmodTargetCLR, 
    SString & szFullDbiPath, 
    SString & szFullCoreClrPath)
{
    szFullDbiPath.Clear();

    // 
    // Step 1: (pid, hmodule) --> full path
    // 
    HandleHolder hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pidDebuggee);
    WCHAR modulePath[MAX_LONGPATH];
    if(0 == GetModuleFileNameEx(hProcess, hmodTargetCLR, modulePath, MAX_LONGPATH))
    {
        ThrowHR(E_FAIL);
    }
    
    // 
    // Step 2: 'Coreclr.dll' --> 'mscordbi.dll' 
    // 
    WCHAR * pCoreClrPath = modulePath;
    WCHAR * pLast = wcsrchr(pCoreClrPath, DIRECTORY_SEPARATOR_CHAR_W);
    if (pLast == NULL)
    {
        ThrowHR(E_FAIL);
    }

    //   c:\abc\coreclr.dll
    //   01234567890
    //   c:\abc\mscordbi.dll
    
    // Copy everything up to but not including the last '\', thus excluding '\coreclr.dll'
    // Then append '\mscordbi.dll' to get a full path to dbi.
    COUNT_T len = (COUNT_T) (pLast - pCoreClrPath); // length not including final '\'
    szFullDbiPath.Set(pCoreClrPath, len);

    AppendDbiDllName(szFullDbiPath);
    
    szFullCoreClrPath.Set(pCoreClrPath, (COUNT_T)wcslen(pCoreClrPath));
}


//---------------------------------------------------------------------------------------
//
// The current policy is that the DBI DLL must live right next to the coreclr DLL.  We check the product
// version number of both of them to make sure they match.
//
// Arguments:
//    szFullDbiPath     - full path to mscordbi.dll
//    szFullCoreClrPath - full path to coreclr.dll
//
// Return Value:
//    true if the versions match
//
static
bool 
CheckDbiAndRuntimeVersion(
    SString & szFullDbiPath,
    SString & szFullCoreClrPath)
{
#ifndef FEATURE_PAL
    DWORD dwDbiVersionMS = 0;
    DWORD dwDbiVersionLS = 0;
    DWORD dwCoreClrVersionMS = 0;
    DWORD dwCoreClrVersionLS = 0;

    // The version numbers follow the convention used by VS_FIXEDFILEINFO.
    GetProductVersionNumber(szFullDbiPath, &dwDbiVersionMS, &dwDbiVersionLS);
    GetProductVersionNumber(szFullCoreClrPath, &dwCoreClrVersionMS, &dwCoreClrVersionLS);

    if ((dwDbiVersionMS == dwCoreClrVersionMS) &&
        (dwDbiVersionLS == dwCoreClrVersionLS))
    {
        return true;
    }
    else
    {
        return false;
    }
#else
    return true;
#endif // FEATURE_PAL
}

//-----------------------------------------------------------------------------
// Public API.
// Given a version string, create the matching mscordbi.dll for it.
// Create a managed debugging interface for the specified version.
//
// Parameters:
//    iDebuggerVersion - the version of interface the debugger (eg, Cordbg) expects.
//    szDebuggeeVersion - the version of the debuggee. This will map to a version of mscordbi.dll
//    ppCordb - the outparameter used to return the debugging interface object.
//
// Return:
//  S_OK on success. *ppCordb will be non-null.
//  CORDBG_E_INCOMPATIBLE_PROTOCOL - if the proper DBI is not available. This can be a very common error if
//    the right debug pack is not installed.
//  else Error. (*ppCordb will be null)
//-----------------------------------------------------------------------------
HRESULT 
CreateDebuggingInterfaceFromVersionEx(
    __in int iDebuggerVersion,
    __in LPCWSTR szDebuggeeVersion,
    __out IUnknown ** ppCordb)
{
    PUBLIC_CONTRACT;

    HRESULT hrIgnore = S_OK; // ignored HResult
    HRESULT hr = S_OK;
    HMODULE hMod = NULL;
    IUnknown * pCordb = NULL;
    FPCoreCLRCreateCordbObject fpCreate2 = NULL;

    LOG((LF_CORDB, LL_EVERYTHING, "Calling CreateDebuggerInterfaceFromVersion, ver=%S\n", szDebuggeeVersion));

    if ((szDebuggeeVersion == NULL) || (ppCordb == NULL))
    {
        hr = E_INVALIDARG;
        goto Exit;
    }

    //
    // Step 1: Parse version information into internal data structures
    // 

    CorDebugInterfaceVersion iTargetVersion;  // the CorDebugInterfaceVersion (CorDebugVersion_2_0)
    DWORD pidDebuggee;     // OS process ID of the debuggee
    HMODULE hmodTargetCLR; // module of Telesto in target (the clrInstanceId)

    hr = ParseVersionString(szDebuggeeVersion, &iTargetVersion, &pidDebuggee, &hmodTargetCLR);
    if (FAILED(hr))
        goto Exit;

    //
    // Step 2:  Find the proper dbi module (mscordbi) and load it.
    // 

    // Check for dbi next to target CLR.
    // This will be very common for internal developer setups, but not common in end-user setups.
    EX_TRY
    {
        SString szFullDbiPath;
        SString szFullCoreClrPath;

        GetDbiFilenameNextToRuntime(pidDebuggee, hmodTargetCLR, szFullDbiPath, szFullCoreClrPath);

        if (!CheckDbiAndRuntimeVersion(szFullDbiPath, szFullCoreClrPath))
        {
            hr = CORDBG_E_INCOMPATIBLE_PROTOCOL;
            goto Exit;
        }

        // We calculated where dbi would be, but haven't yet verified if it's there.
        // Try to load it. We're using this to check for file existence.

        // Issue:951525: coreclr mscordbi load fails on downlevel OS since LoadLibraryEx can't find 
        // dependent forwarder DLLs. Force LoadLibrary to look for dependencies in szFullDbiPath plus the default
        // search paths.
#ifndef FEATURE_PAL
        hMod = WszLoadLibraryEx(szFullDbiPath, NULL, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);
#else
        hMod = LoadLibraryExW(szFullDbiPath, NULL, 0);
#endif
    }
    EX_CATCH_HRESULT(hrIgnore); // failure leaves hMod null

    // Couldn't find Dbi, likely because the right debug pack is not installed. Failure.
    if (NULL == hMod)
    {
        // Check for the following two HRESULTs and return them specifically.  These are returned by 
        // CreateToolhelp32Snapshot() and could be transient errors.  The debugger may choose to retry.
        if ((hrIgnore == HRESULT_FROM_WIN32(ERROR_PARTIAL_COPY)) || (hrIgnore == HRESULT_FROM_WIN32(ERROR_BAD_LENGTH)))
        {
            hr = hrIgnore;
        }
        else
        {
            hr = CORDBG_E_DEBUG_COMPONENT_MISSING;
        }
        goto Exit;
    }

    //
    // Step 3: Now that module is loaded, instantiate an ICorDebug.
    // 
    fpCreate2 = (FPCoreCLRCreateCordbObject)GetProcAddress(hMod, "CoreCLRCreateCordbObject");
    if (fpCreate2 == NULL)
    {
        // New-style creation API didn't exist - this DBI must be the wrong version, for the Mix07 protocol
        hr = CORDBG_E_INCOMPATIBLE_PROTOCOL;
        goto Exit;
    }

    // Invoke to instantiate an ICorDebug. This export was introduced after the Mix'07 release.
    hr = fpCreate2(iDebuggerVersion, pidDebuggee, hmodTargetCLR, &pCordb);
    _ASSERTE((pCordb == NULL) == FAILED(hr));

Exit:
    if (FAILED(hr))
    {
        if (pCordb != NULL)
        {
            pCordb->Release();
            pCordb = NULL;
        }

        if (hMod != NULL)
        {
            _ASSERTE(pCordb == NULL);
            FreeLibrary(hMod);
        }
    }

    // Set our outparam.
    *ppCordb = pCordb;

    // On success case, mscordbi.dll is leaked. 
    // - We never give the caller back the module handle, so our caller can't do FreeLibrary(). 
    // - ICorDebug can't unload itself. 

    return hr;
}

//-----------------------------------------------------------------------------
// Public API.
// Superceded by CreateDebuggingInterfaceFromVersionEx in SLv4.
// Given a version string, create the matching mscordbi.dll for it.
// Create a managed debugging interface for the specified version.
//
// Parameters:
//    szDebuggeeVersion - the version of the debuggee. This will map to a version of mscordbi.dll
//    ppCordb - the outparameter used to return the debugging interface object.
//
// Return:
//  S_OK on success. *ppCordb will be non-null.
//  CORDBG_E_INCOMPATIBLE_PROTOCOL - if the proper DBI is not available. This can be a very common error if
//    the right debug pack is not installed.
//  else Error. (*ppCordb will be null)
//-----------------------------------------------------------------------------
HRESULT 
CreateDebuggingInterfaceFromVersion(
    __in LPCWSTR szDebuggeeVersion, 
    __out IUnknown ** ppCordb
)
{
    PUBLIC_CONTRACT;

    return CreateDebuggingInterfaceFromVersionEx(CorDebugVersion_2_0, szDebuggeeVersion, ppCordb);
}

#ifndef FEATURE_PAL

//------------------------------------------------------------------------------
// Manually retrieves the "continue startup" event from the correct CLR instance
// in the target process.
// 
// Arguments:
//    debuggeePID - (in) OS Process ID of debuggee
//    szTelestoFullPath - (in) full path to telesto within the process.
//    phContinueStartupEvent - (out) 
//    
// Returns:
//   S_OK on success. 
//------------------------------------------------------------------------------
HRESULT 
GetContinueStartupEvent(
    DWORD debuggeePID, 
    LPCWSTR szTelestoFullPath,
    __out HANDLE* phContinueStartupEvent)
{
    if ((phContinueStartupEvent == NULL) || (szTelestoFullPath == NULL))
        return E_INVALIDARG;

    HRESULT hr = S_OK;
    EX_TRY
    {
        *phContinueStartupEvent = INVALID_HANDLE_VALUE;

        DWORD  dwCoreClrContinueEventOffset = 0;
        CLR_ENGINE_METRICS metricsStruct;
        
        GetTargetCLRMetrics(szTelestoFullPath, &metricsStruct, &dwCoreClrContinueEventOffset); // throws


        BYTE* pbBaseAddress = GetRemoteModuleBaseAddress(debuggeePID, szTelestoFullPath); // throws


        HandleHolder hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, debuggeePID);
        if (NULL == hProcess)
            ThrowHR(E_FAIL);

        HANDLE continueEvent = NULL;

        SIZE_T nBytesRead;
        if (!ReadProcessMemory(hProcess, pbBaseAddress + dwCoreClrContinueEventOffset, &continueEvent, 
            sizeof(continueEvent), &nBytesRead))
        {
            ThrowHR(E_FAIL);
        }

        if (NULL != continueEvent)
        {
            if (!DuplicateHandle(hProcess, continueEvent, GetCurrentProcess(), &continueEvent, 
                EVENT_MODIFY_STATE, FALSE, 0))
            {
                ThrowHR(E_FAIL);
            }
        }

        *phContinueStartupEvent = continueEvent;
    }
    EX_CATCH_HRESULT(hr)
    return hr;
}

#endif // !FEATURE_PAL

#if defined(FEATURE_CORESYSTEM)
#include "debugshim.h"
#endif

//-----------------------------------------------------------------------------
// Public API.
//
// Parameters:
//  clsid
//  riid
//  ppInterface
//
// Return:
//  S_OK on success.
//-----------------------------------------------------------------------------
HRESULT 
CLRCreateInstance(
    REFCLSID clsid,
    REFIID riid, 
    LPVOID *ppInterface)
{
#if defined(FEATURE_CORESYSTEM)

    if (ppInterface == NULL)
        return E_POINTER;

    if (clsid != CLSID_CLRDebugging || riid != IID_ICLRDebugging)
        return E_NOINTERFACE;
    
#if defined(FEATURE_CORESYSTEM)
    GUID skuId = CLR_ID_ONECORE_CLR;
#elif defined(FEATURE_CORECLR)
    GUID skuId = CLR_ID_CORECLR;
#else
    GUID skuId = CLR_ID_V4_DESKTOP;
#endif
    
    CLRDebuggingImpl *pDebuggingImpl = new CLRDebuggingImpl(skuId);
    return pDebuggingImpl->QueryInterface(riid, ppInterface);
#else
    return E_NOTIMPL;
#endif
}