summaryrefslogtreecommitdiff
path: root/src/debug/di/rsappdomain.cpp
blob: b293896bc51581312aa5334dbc6ec05a522c2975 (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
// 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.
//*****************************************************************************
// File: RsAppDomain.cpp
// 

//
//*****************************************************************************
#include "stdafx.h"
#include "primitives.h"
#include "safewrap.h"

#include "check.h"

#include <tlhelp32.h>
#include "wtsapi32.h"

#ifndef SM_REMOTESESSION
#define SM_REMOTESESSION 0x1000
#endif

#include "corpriv.h"
#include "../../dlls/mscorrc/resource.h"
#include <limits.h>


/* ------------------------------------------------------------------------- *
 * AppDomain class methods
 * ------------------------------------------------------------------------- */

//
// Create a CordbAppDomain object based on a pointer to the AppDomain instance 
// in the CLR.  Pre-populates some cached information about the AppDomain
// from the CLR using DAC.
//
// Arguments:
//    pProcess    - the CordbProcess object that this AppDomain is part of
//    vmAppDomain - the address in the CLR of the AppDomain object this corresponds to.
//                  This will be used to read any additional information about the AppDomain.
//
// Assumptions:
//    The IMetaSig object should have been allocated by
//    IMDInternal on a valid metadata blob
//
//
CordbAppDomain::CordbAppDomain(CordbProcess *  pProcess, VMPTR_AppDomain vmAppDomain)
  : CordbBase(pProcess, LsPtrToCookie(vmAppDomain.ToLsPtr()), enumCordbAppDomain),    
    m_AppDomainId(0),    
    m_breakpoints(17),
    m_sharedtypes(3),
    m_modules(17),
    m_assemblies(9),
    m_vmAppDomain(vmAppDomain)
{
    // This may throw out of the Ctor on error.

    // @dbgtodo  reliability: we should probably tolerate failures here and keep track
    // of whether our ADID is valid or not, and requery if necessary.
    m_AppDomainId = m_pProcess->GetDAC()->GetAppDomainId(m_vmAppDomain);    
    
    LOG((LF_CORDB,LL_INFO10000, "CAD::CAD: this:0x%x (void*)this:0x%x<%d>\n", this, (void *)this, m_AppDomainId));

#ifdef _DEBUG
    m_assemblies.DebugSetRSLock(pProcess->GetProcessLock());
    m_modules.DebugSetRSLock(pProcess->GetProcessLock());
    m_breakpoints.DebugSetRSLock(pProcess->GetProcessLock());
    m_sharedtypes.DebugSetRSLock(pProcess->GetProcessLock());
#endif

}

/*
    A list of which resources owened by this object are accounted for.

    RESOLVED:
        // AddRef() in CordbHashTable::GetBase for a special InProc case
        // AddRef() on the DB_IPCE_CREATE_APP_DOMAIN event from the LS
        // Release()ed in Neuter
        CordbProcess        *m_pProcess;

        WCHAR               *m_szAppDomainName; // Deleted in ~CordbAppDomain

        // Cleaned up in Neuter
        CordbHashTable      m_assemblies;
        CordbHashTable      m_sharedtypes;
        CordbHashTable      m_modules;
        CordbHashTable      m_breakpoints; // Disconnect()ed in ~CordbAppDomain

    private:
*/

CordbAppDomain::~CordbAppDomain()
{

    // We expect to be Neutered before being released. Neutering will release our process ref
    _ASSERTE(IsNeutered());
}


// Neutered by process. Once we're neutered, we lose our backpointer to the CordbProcess object, and
// thus can't do things like call GetProcess() or Continue().
void CordbAppDomain::Neuter()
{
    // This check prevents us from calling this twice and underflowing the internal ref count!
    if (IsNeutered())
    {
        return;
    }
    _ASSERTE(GetProcess()->ThreadHoldsProcessLock());

    //
    // Disconnect any active breakpoints
    //
    {
        CordbBreakpoint* entry;
        HASHFIND find;

        for (entry =  m_breakpoints.FindFirst(&find);
             entry != NULL;
             entry =  m_breakpoints.FindNext(&find))
        {
            entry->Disconnect();
        }
    }

    // Mark as neutered so that our children can tell the appdomain has now
    // exited.
    CordbBase::Neuter();

    //
    // Purge neuter lists.
    //
    m_TypeNeuterList.NeuterAndClear(GetProcess());
    m_SweepableNeuterList.NeuterAndClear(GetProcess());


    m_assemblies.NeuterAndClear(GetProcess()->GetProcessLock());
    m_modules.NeuterAndClear(GetProcess()->GetProcessLock());
    m_sharedtypes.NeuterAndClear(GetProcess()->GetProcessLock());
    m_breakpoints.NeuterAndClear(GetProcess()->GetProcessLock());

}


HRESULT CordbAppDomain::QueryInterface(REFIID id, void **ppInterface)
{
    if (id == IID_ICorDebugAppDomain)
    {
        *ppInterface = (ICorDebugAppDomain*)this;
    }
    else if (id == IID_ICorDebugAppDomain2)
    {
        *ppInterface = (ICorDebugAppDomain2*)this;
    }
    else if (id == IID_ICorDebugAppDomain3)
    {
        *ppInterface = (ICorDebugAppDomain3*)this;
    }
    else if (id == IID_ICorDebugAppDomain4)
    {
        *ppInterface = (ICorDebugAppDomain4*)this;
    }
    else if (id == IID_ICorDebugController)
        *ppInterface = (ICorDebugController*)(ICorDebugAppDomain*)this;
    else if (id == IID_IUnknown)
        *ppInterface = (IUnknown*)(ICorDebugAppDomain*)this;
    else
    {
        *ppInterface = NULL;
        return E_NOINTERFACE;
    }

    ExternalAddRef();
    return S_OK;
}


//---------------------------------------------------------------------------------------
//
// Ensure the AppDomain friendly name has been set.
//
// Return value:
//    S_OK on success, or a failure code if we couldn't read the name for some reason.
//    There shouldn't be any reason in practice for this to fail other than a corrupt
//    process image.
//
// Assumptions:
//    The AppDomain object has already been initialized to know about
//    it's corresponding VM appdomain.
//    InvalidateName is called whenever the name may have changed to prompt us to re-fetch.
//
//---------------------------------------------------------------------------------------
HRESULT CordbAppDomain::RefreshName()
{
    if (m_strAppDomainName.IsSet())
    {
        // If we already have a valid name, we're done.
        return S_OK;
    }

    // Use DAC to get the name.
    
    _ASSERTE(!m_vmAppDomain.IsNull());
    IDacDbiInterface * pDac = NULL;
    HRESULT hr = S_OK;
    EX_TRY
    {
        pDac = m_pProcess->GetDAC();

    #ifdef _DEBUG
        // For debug, double-check the cached value against getting the AD via an AppDomainId.
        VMPTR_AppDomain pAppDomain = pDac->GetAppDomainFromId(m_AppDomainId);
        _ASSERTE(m_vmAppDomain == pAppDomain);
    #endif

        // Get the actual string contents.
        pDac->GetAppDomainFullName(m_vmAppDomain, &m_strAppDomainName);

        // Now that m_strAppDomainName is set, don't fail without clearing it.        
    }
    EX_CATCH_HRESULT(hr);

    _ASSERTE(SUCCEEDED(hr) == m_strAppDomainName.IsSet());
   
    return hr;
}


HRESULT CordbAppDomain::Stop(DWORD dwTimeout)
{
    FAIL_IF_NEUTERED(this);
    PUBLIC_API_ENTRY(this);
    return (m_pProcess->StopInternal(dwTimeout, this->GetADToken()));
}

HRESULT CordbAppDomain::Continue(BOOL fIsOutOfBand)
{
    PUBLIC_API_ENTRY(this);
    FAIL_IF_NEUTERED(this);
    return m_pProcess->ContinueInternal(fIsOutOfBand);
}

HRESULT CordbAppDomain::IsRunning(BOOL *pbRunning)
{
    PUBLIC_API_ENTRY(this);
    VALIDATE_POINTER_TO_OBJECT(pbRunning, BOOL *);
    FAIL_IF_NEUTERED(this);

    *pbRunning = !m_pProcess->GetSynchronized();

    return S_OK;
}

HRESULT CordbAppDomain::HasQueuedCallbacks(ICorDebugThread *pThread, BOOL *pbQueued)
{
    PUBLIC_API_ENTRY(this);
    FAIL_IF_NEUTERED(this);

    VALIDATE_POINTER_TO_OBJECT_OR_NULL(pThread,ICorDebugThread *);
    VALIDATE_POINTER_TO_OBJECT(pbQueued,BOOL *);

    return m_pProcess->HasQueuedCallbacks (pThread, pbQueued);
}

HRESULT CordbAppDomain::EnumerateThreads(ICorDebugThreadEnum **ppThreads)
{
    // @TODO E_NOIMPL this
    //
    // (use Process::EnumerateThreads and let users filter their own data)
    HRESULT hr = S_OK;
    PUBLIC_API_BEGIN(this);
    {
        ValidateOrThrow(ppThreads);

        RSInitHolder<CordbEnumFilter> pThreadEnum(
                new CordbEnumFilter(GetProcess(), GetProcess()->GetContinueNeuterList()));

        GetProcess()->PrepopulateThreadsOrThrow();

        RSInitHolder<CordbHashTableEnum> pEnum;
        GetProcess()->BuildThreadEnum(this, NULL, pEnum.GetAddr());

        // This builds up auxillary list. don't need pEnum after this.
        hr = pThreadEnum->Init(pEnum, this);
        IfFailThrow(hr);
    
        pThreadEnum.TransferOwnershipExternal(ppThreads);
    }
    PUBLIC_API_END(hr);
    return hr;
}


HRESULT CordbAppDomain::SetAllThreadsDebugState(CorDebugThreadState state,
                                   ICorDebugThread *pExceptThisThread)
{
    PUBLIC_API_ENTRY(this);
    FAIL_IF_NEUTERED(this);
    ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());

    return m_pProcess->SetAllThreadsDebugState(state, pExceptThisThread);
}

HRESULT CordbAppDomain::Detach()
{
    PUBLIC_REENTRANT_API_ENTRY(this); // may be called from IMDA::Detach
    FAIL_IF_NEUTERED(this);

    return E_NOTIMPL;
}

HRESULT CordbAppDomain::Terminate(unsigned int exitCode)
{
    PUBLIC_API_ENTRY(this);
    FAIL_IF_NEUTERED(this);
    return E_NOTIMPL;
}

void CordbAppDomain::AddToTypeList(CordbBase *pObject)
{
    INTERNAL_API_ENTRY(this);
    _ASSERTE(pObject != NULL);
    RSLockHolder lockHolder(GetProcess()->GetProcessLock());
    this->m_TypeNeuterList.Add(GetProcess(), pObject);
}


HRESULT CordbAppDomain::CanCommitChanges(
    ULONG cSnapshots,
    ICorDebugEditAndContinueSnapshot *pSnapshots[],
    ICorDebugErrorInfoEnum **pError)
{
    return E_NOTIMPL;
}

HRESULT CordbAppDomain::CommitChanges(
    ULONG cSnapshots,
    ICorDebugEditAndContinueSnapshot *pSnapshots[],
    ICorDebugErrorInfoEnum **pError)
{
    return E_NOTIMPL;
}


/*
 * GetProcess returns the process containing the app domain
 */
HRESULT CordbAppDomain::GetProcess(ICorDebugProcess **ppProcess)
{
    PUBLIC_REENTRANT_API_ENTRY(this);
    FAIL_IF_NEUTERED(this);

    VALIDATE_POINTER_TO_OBJECT(ppProcess,ICorDebugProcess **);

    _ASSERTE (m_pProcess != NULL);

    *ppProcess = static_cast<ICorDebugProcess *> (m_pProcess);
    m_pProcess->ExternalAddRef();

    return S_OK;
}

//---------------------------------------------------------------------------------------
//
// Callback for assembly enumeration.
//
// Arguments:
//      vmDomainAssembly - new assembly to add
//      pThis - user data for CordbAppDomain to add assembly too
//
//
// Assumptions:
//    Invoked as callback from code:CordbAppDomain::PrepopulateAssemblies 
//
// Notes: 
//

// static
void CordbAppDomain::AssemblyEnumerationCallback(VMPTR_DomainAssembly vmDomainAssembly, void * pThis)
{   
    CordbAppDomain * pAppDomain = static_cast<CordbAppDomain *> (pThis);
    INTERNAL_DAC_CALLBACK(pAppDomain->GetProcess());

    // This lookup will cause the cache to be populated if we haven't seen this assembly before.
    pAppDomain->LookupOrCreateAssembly(vmDomainAssembly);
}


//---------------------------------------------------------------------------------------
//
// Cache a new assembly 
//
// Arguments:
//      vmDomainAssembly - new assembly to add to cache
//
// Return Value:
//    Pointer to Assembly in cache.
//    NULL on failure, and sets unrecoverable error.
//
// Assumptions:
//    Caller guarantees assembly is not already added.
//    Called under the stop-go lock.
//
// Notes:
//    
CordbAssembly * CordbAppDomain::CacheAssembly(VMPTR_DomainAssembly vmDomainAssembly)
{
    INTERNAL_API_ENTRY(GetProcess());

    VMPTR_Assembly vmAssembly;
    GetProcess()->GetDAC()->GetAssemblyFromDomainAssembly(vmDomainAssembly, &vmAssembly);

    RSInitHolder<CordbAssembly> pAssembly(new CordbAssembly(this, vmAssembly, vmDomainAssembly));

    return pAssembly.TransferOwnershipToHash(&m_assemblies);
}

CordbAssembly * CordbAppDomain::CacheAssembly(VMPTR_Assembly vmAssembly)
{
    INTERNAL_API_ENTRY(GetProcess());

    RSInitHolder<CordbAssembly> pAssembly(new CordbAssembly(this, vmAssembly, VMPTR_DomainAssembly()));

    return pAssembly.TransferOwnershipToHash(&m_assemblies);
}

//---------------------------------------------------------------------------------------
//
// Build up cache of assmeblies 
//
// Arguments:
//
// Return Value:
//    Throws on error.
//
// Assumptions:
//    This is an non-invasive inspection operation called when the debuggee is stopped.
//
// Notes:
//    This can safely be called multiple times.
//

void CordbAppDomain::PrepopulateAssembliesOrThrow()
{
    INTERNAL_API_ENTRY(GetProcess());

    RSLockHolder lockHolder(GetProcess()->GetProcessLock());

    if (!GetProcess()->IsDacInitialized())
    {
        return;
    }

    // DD-primitive  that invokes a callback.   
    GetProcess()->GetDAC()->EnumerateAssembliesInAppDomain(
        this->m_vmAppDomain,
        CordbAppDomain::AssemblyEnumerationCallback,
        this); // user data
}

//---------------------------------------------------------------------------------------
//
// Public API tp EnumerateAssemblies enumerates all assemblies in the app domain
//
// Arguments:
//      ppAssemblies - OUT: get enumerator
//
// Return Value:
//    S_OK on success.
//
//
// Notes:
//    This will prepopulate the list of assemblies (useful for non-invasive case
//    where we don't get debug event).
//

HRESULT CordbAppDomain::EnumerateAssemblies(ICorDebugAssemblyEnum **ppAssemblies)
{
    HRESULT hr = S_OK;
    PUBLIC_API_BEGIN(this);
    {
        ValidateOrThrow(ppAssemblies);
        *ppAssemblies = NULL;

        PrepopulateAssembliesOrThrow();
        
        RSInitHolder<CordbHashTableEnum> pEnum;
        CordbHashTableEnum::BuildOrThrow(
            this, 
            GetProcess()->GetContinueNeuterList(), // ownership
            &m_assemblies,
            IID_ICorDebugAssemblyEnum,
            pEnum.GetAddr());
        pEnum.TransferOwnershipExternal(ppAssemblies);

    }
    PUBLIC_API_END(hr);
    return hr;
}

// Implement public interface
HRESULT CordbAppDomain::GetModuleFromMetaDataInterface(
                                                  IUnknown *pIMetaData,
                                                  ICorDebugModule **ppModule)
{
    PUBLIC_API_ENTRY(this);
    FAIL_IF_NEUTERED(this);
    VALIDATE_POINTER_TO_OBJECT(pIMetaData, IUnknown *);
    VALIDATE_POINTER_TO_OBJECT(ppModule, ICorDebugModule **);

    

    HRESULT hr = S_OK;

    ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());

    *ppModule = NULL;

    EX_TRY
    {
        CordbModule * pModule = GetModuleFromMetaDataInterface(pIMetaData);
        _ASSERTE(pModule != NULL); // thrown on error
        
        *ppModule = static_cast<ICorDebugModule*> (pModule);
        pModule->ExternalAddRef();        
    }
    EX_CATCH_HRESULT(hr);


    return hr;
}

// Gets a CordbModule that has the given metadata interface
//
// Arguments:
//     pIMetaData - metadata interface
//
// Returns:
//     CordbModule whose associated metadata matches the metadata interface provided here
//     Throws on error. Returns non-null
//
CordbModule * CordbAppDomain::GetModuleFromMetaDataInterface(IUnknown *pIMetaData)
{
    HRESULT hr = S_OK;
        
    RSExtSmartPtr<IMetaDataImport> pImport;
    RSLockHolder lockHolder(GetProcess()->GetProcessLock());  // need for module enumeration      

    // Grab the interface we need...
    hr = pIMetaData->QueryInterface(IID_IMetaDataImport, (void**)&pImport);
    if (FAILED(hr))
    {
        ThrowHR(E_INVALIDARG);
    }

    // Get the mvid of the given module.
    GUID matchMVID;
    hr = pImport->GetScopeProps(NULL, 0, 0, &matchMVID);
    IfFailThrow(hr);

    CordbModule* pModule;
    HASHFIND findmodule;

    PrepopulateModules();

    for (pModule =  m_modules.FindFirst(&findmodule);
         pModule != NULL;
         pModule =  m_modules.FindNext(&findmodule))
    {
        IMetaDataImport * pImportCurrent = pModule->GetMetaDataImporter(); // throws
        _ASSERTE(pImportCurrent != NULL);
        
        // Get the mvid of this module
        GUID MVID;
        hr = pImportCurrent->GetScopeProps(NULL, 0, 0, &MVID);
        IfFailThrow(hr);

        if (MVID == matchMVID)
        {
            return pModule;
        }        
    }

    ThrowHR(E_INVALIDARG);
}

HRESULT CordbAppDomain::EnumerateBreakpoints(ICorDebugBreakpointEnum **ppBreakpoints)
{
    PUBLIC_API_ENTRY(this);
    FAIL_IF_NEUTERED(this);
    ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
    VALIDATE_POINTER_TO_OBJECT(ppBreakpoints, ICorDebugBreakpointEnum **);

    HRESULT hr = S_OK;
    EX_TRY
    {
        RSInitHolder<CordbHashTableEnum> pEnum;
        CordbHashTableEnum::BuildOrThrow(
            this, 
            GetProcess()->GetContinueNeuterList(), // ownership
            &m_breakpoints,
            IID_ICorDebugBreakpointEnum,
            pEnum.GetAddr());

        pEnum.TransferOwnershipExternal(ppBreakpoints);
    }
    EX_CATCH_HRESULT(hr);
    return hr;
}

HRESULT CordbAppDomain::EnumerateSteppers(ICorDebugStepperEnum **ppSteppers)
{
    PUBLIC_API_ENTRY(this);
    FAIL_IF_NEUTERED(this);
    ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
    VALIDATE_POINTER_TO_OBJECT(ppSteppers,ICorDebugStepperEnum **);

    HRESULT hr = S_OK;
    EX_TRY
    {
        //
        // !!! m_steppers may be modified while user is enumerating,
        // if steppers complete (if process is running)
        //

        RSInitHolder<CordbHashTableEnum> pEnum;
        CordbHashTableEnum::BuildOrThrow(
            GetProcess(), 
            GetProcess()->GetContinueNeuterList(),  // ownership
            &(m_pProcess->m_steppers),
            IID_ICorDebugStepperEnum,
            pEnum.GetAddr());

        pEnum.TransferOwnershipExternal(ppSteppers);
    }
    EX_CATCH_HRESULT(hr);
    return hr;
}


//---------------------------------------------------------------------------------------
//
// CordbAppDomain::IsAttached - always returns true
//
// Arguments:
//    pfAttached - out parameter, will be set to TRUE
//
// Return Value:
//    CORDB_E_OBJECT_NEUTERED if the AppDomain has been neutered 
//    E_INVALIDARG if pbAttached is null
//    Otherwise always returns S_OK.
//
// Notes:
//    Prior to V3, we used to keep track of a per-appdomain attached status.
//    Debuggers were required to explicitly attach to every AppDomain, so this
//    did not provide any actual functionality.  In V3, there is no longer any
//    concept of per-AppDomain attach/detach.  This API is provided for compatibility.
//

HRESULT CordbAppDomain::IsAttached(BOOL *pfAttached)
{
    PUBLIC_API_ENTRY(this);
    FAIL_IF_NEUTERED(this);
    VALIDATE_POINTER_TO_OBJECT(pfAttached, BOOL *);

    *pfAttached = TRUE;

    return S_OK;
}


//---------------------------------------------------------------------------------------
//
// CordbAppDomain::Attach - does nothing
//
// Arguments:
//
// Return Value:
//    CORDB_E_OBJECT_NEUTERED if the AppDomain has been neutered 
//    Otherwise always returns S_OK.
//
// Notes:
//    Prior to V3, we used to keep track of a per-appdomain attached status.
//    Debuggers were required to explicitly attach to every AppDomain, so this
//    did not provide any actual functionality.  In V3, there is no longer any
//    concept of per-AppDomain attach/detach.  This API is provided for compatibility.
//

HRESULT CordbAppDomain::Attach()
{
    PUBLIC_API_ENTRY(this);
    FAIL_IF_NEUTERED(this);
    ATT_REQUIRE_STOPPED_MAY_FAIL(m_pProcess);

    return S_OK;
}

/*
 * GetName returns the name of the app domain.
 */
HRESULT CordbAppDomain::GetName(ULONG32 cchName,
                                ULONG32 *pcchName,
                                __out_ecount_part_opt(cchName, *pcchName) WCHAR szName[])
{
    HRESULT hr = S_OK;
    PUBLIC_API_BEGIN(this)
    {
        // Some reasonable defaults
        if (szName)
            *szName = 0;

        if (pcchName)
            *pcchName = 0;


        // Lazily refresh.
        IfFailThrow(RefreshName());

        const WCHAR * pName = m_strAppDomainName;
        _ASSERTE(pName != NULL); 

        hr = CopyOutString(pName, cchName, pcchName, szName);
    }
    PUBLIC_API_END(hr);
    return hr;
}

/*
 * GetObject returns the runtime app domain object.
 * Note: this is lazily initialized and may be NULL
 */
HRESULT CordbAppDomain::GetObject(ICorDebugValue **ppObject)
{
    PUBLIC_API_ENTRY(this);
    FAIL_IF_NEUTERED(this);
    VALIDATE_POINTER_TO_OBJECT(ppObject,ICorDebugObjectValue **);

    ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());

    _ASSERTE(!m_vmAppDomain.IsNull());
    IDacDbiInterface * pDac = NULL;
    HRESULT hr = S_OK;
    EX_TRY
    {
        pDac = m_pProcess->GetDAC();
        VMPTR_OBJECTHANDLE vmObjHandle = pDac->GetAppDomainObject(m_vmAppDomain);
        if (!vmObjHandle.IsNull())
        {
            ICorDebugReferenceValue * pRefValue = NULL;
            hr = CordbReferenceValue::BuildFromGCHandle(this, vmObjHandle, &pRefValue);
            *ppObject = pRefValue;
        }
        else
        {
            *ppObject = NULL;
            hr = S_FALSE;
        }
    }
    EX_CATCH_HRESULT(hr);

    return hr;
}

/*
 * Get the ID of the app domain.
 */
HRESULT CordbAppDomain::GetID (ULONG32 *pId)
{
    PUBLIC_REENTRANT_API_ENTRY(this);
    OK_IF_NEUTERED(this);
    VALIDATE_POINTER_TO_OBJECT(pId, ULONG32 *);

    *pId = m_AppDomainId;

    return S_OK;
}

//---------------------------------------------------------------------------------------
//  Remove an assembly from the ICorDebug cache.
//
//  Arguments:
//     vmDomainAssembly - token to remove.
//
//  Notes:
//     This is the opposite of code:CordbAppDomain::LookupOrCreateAssembly.
//     This only need to be called at assembly unload events.
void CordbAppDomain::RemoveAssemblyFromCache(VMPTR_DomainAssembly vmDomainAssembly)
{
    // This will handle if the assembly is not in the hash. 
    // This could happen if we attach right before an assembly-unload event.
    m_assemblies.RemoveBase(VmPtrToCookie(vmDomainAssembly));
}

//---------------------------------------------------------------------------------------
// Lookup (or create) the CordbAssembly for the given VMPTR_DomainAssembly
//
// Arguments:
//     vmDomainAssembly - CLR token for the Assembly.
//
// Returns:
//     a CordbAssembly object for the given CLR assembly. This may be from the cache,
//     or newly created if not yet in the cache. 
//     Never returns NULL. Throws on error (eg, oom).
//
CordbAssembly * CordbAppDomain::LookupOrCreateAssembly(VMPTR_DomainAssembly vmDomainAssembly)
{
    CordbAssembly * pAssembly = m_assemblies.GetBase(VmPtrToCookie(vmDomainAssembly));
    if (pAssembly != NULL)
    {
        return pAssembly;
    }
    return CacheAssembly(vmDomainAssembly);
}


//
CordbAssembly * CordbAppDomain::LookupOrCreateAssembly(VMPTR_Assembly vmAssembly)
{
    CordbAssembly * pAssembly = m_assemblies.GetBase(VmPtrToCookie(vmAssembly));
    if (pAssembly != NULL)
    {
        return pAssembly;
    }
    return CacheAssembly(vmAssembly);
}


//---------------------------------------------------------------------------------------
// Lookup or create a module within the appdomain
//
// Arguments:
//    vmDomainFile - non-null module to lookup
// 
// Returns:
//    a CordbModule object for the given cookie. Object may be from the cache, or created
//    lazily. 
//    Never returns null.  Throws on error.
//
// Notes:
//    If you don't know which appdomain the module is in, use code:CordbProcess::LookupOrCreateModule.
//
CordbModule* CordbAppDomain::LookupOrCreateModule(VMPTR_Module vmModule, VMPTR_DomainFile vmDomainFile)
{
    INTERNAL_API_ENTRY(this);
    CordbModule * pModule;
    
    RSLockHolder lockHolder(GetProcess()->GetProcessLock()); // @dbgtodo  locking: push this up.
    
    _ASSERTE(!vmDomainFile.IsNull() || !vmModule.IsNull());

    // check to see if the module is present in this app domain
    pModule = m_modules.GetBase(vmDomainFile.IsNull() ? VmPtrToCookie(vmModule) : VmPtrToCookie(vmDomainFile));
    if (pModule != NULL)
    {
        return pModule;
    }
    
    if (vmModule.IsNull())
        GetProcess()->GetDAC()->GetModuleForDomainFile(vmDomainFile, &vmModule);
    
    RSInitHolder<CordbModule> pModuleInit(new CordbModule(GetProcess(), vmModule, vmDomainFile));
    pModule = pModuleInit.TransferOwnershipToHash(&m_modules);

    // The appdomains should match.
    GetProcess()->TargetConsistencyCheck(pModule->GetAppDomain() == this);

    return pModule;
}


CordbModule* CordbAppDomain::LookupOrCreateModule(VMPTR_DomainFile vmDomainFile)
{
    INTERNAL_API_ENTRY(this);
    
    _ASSERTE(!vmDomainFile.IsNull());
    return LookupOrCreateModule(VMPTR_Module::NullPtr(), vmDomainFile);
}



//---------------------------------------------------------------------------------------
// Callback invoked by DAC for each module in an assembly. Used to populate RS module cache.
//
// Arguments:
//     vmModule - module from enumeration
//     pUserData - user data, a 'this' pointer to the CordbAssembly to add to.
//
// Notes:
//    This is called from code:CordbAppDomain::PrepopulateModules invoking DAC, which
//    invokes this callback.

// static
void CordbAppDomain::ModuleEnumerationCallback(VMPTR_DomainFile vmModule, void * pUserData)
{
    CONTRACTL
    {
        THROWS;
    }
    CONTRACTL_END;

    CordbAppDomain * pAppDomain = static_cast<CordbAppDomain *> (pUserData);
    INTERNAL_DAC_CALLBACK(pAppDomain->GetProcess());

    pAppDomain->LookupOrCreateModule(vmModule);
}


//
// Use DAC to preopulate the list of modules for this assembly
//
// Notes:
//     This may pick up modules for which a load notification has not yet been dispatched.
void CordbAppDomain::PrepopulateModules()
{
    INTERNAL_API_ENTRY(GetProcess()); 

    if (!GetProcess()->IsDacInitialized())
    {
        return;
    } 
    
    RSLockHolder lockHolder(GetProcess()->GetProcessLock());

    // Want to make sure we don't double-add modules.
    // Modules for all assemblies are stored in 1 giant hash in the AppDomain, so 
    // we don't have a good way of querying if this specific assembly needs to be prepopulated.
    // We'll check before adding each module that it's unique.

    PrepopulateAssembliesOrThrow();
    
    HASHFIND hashfind;

    for (CordbAssembly * pAssembly = m_assemblies.FindFirst(&hashfind);
         pAssembly != NULL;
         pAssembly = m_assemblies.FindNext(&hashfind))
    {

        // DD-primitive  that invokes a callback.   
        GetProcess()->GetDAC()->EnumerateModulesInAssembly(
            pAssembly->GetDomainAssemblyPtr(),
            CordbAppDomain::ModuleEnumerationCallback,
            this); // user data

    }
}

//-----------------------------------------------------------------------------
// 
// Get a type that represents an array or pointer of the given type.
//
// Arguments:
//   elementType - determines if this will be an array or a pointer
//   nRank - Rank of the array to make
//   pTypeArg - The type of array element or pointer.
//   ppResultType - OUT: out parameter to hold outgoing CordbType.
//
// Returns:
//   S_OK on success. Else failure.
//
HRESULT CordbAppDomain::GetArrayOrPointerType(CorElementType elementType,
                                              ULONG32 nRank,
                                              ICorDebugType * pTypeArg,
                                              ICorDebugType ** ppResultType)
{
    PUBLIC_API_ENTRY(this);
    FAIL_IF_NEUTERED(this);
    VALIDATE_POINTER_TO_OBJECT(ppResultType, ICorDebugType **);
    ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());

    CordbType * pResultType = NULL;

    if (!(elementType == ELEMENT_TYPE_PTR && nRank == 0) &&
        !(elementType == ELEMENT_TYPE_BYREF && nRank == 0) &&
        !(elementType == ELEMENT_TYPE_SZARRAY && nRank == 1) &&
        !(elementType == ELEMENT_TYPE_ARRAY))
    {
        return E_INVALIDARG;
    }

    HRESULT hr = CordbType::MkType(
        this, 
        elementType, 
        (ULONG) nRank, 
        static_cast<CordbType *>(pTypeArg), 
        &pResultType);

    if (FAILED(hr))
    {
        return hr;
    }
    
    _ASSERTE(pResultType != NULL);

    pResultType->ExternalAddRef();

    *ppResultType = pResultType;
    return hr;

}


//-----------------------------------------------------------------------------
// 
// Get a type that represents a function pointer with signature of the types given.
//
// Arguments:
//   cTypeArgs - count of the number of entries in rgpTypeArgs
//   rgpTypeArgs - Array of types
//   ppResultType - OUT: out parameter to hold outgoing CordbType.
//
// Returns:
//   S_OK on success. Else failure.
//
HRESULT CordbAppDomain::GetFunctionPointerType(ULONG32 cTypeArgs,
                                               ICorDebugType * rgpTypeArgs[],
                                               ICorDebugType ** ppResultType)
{
    PUBLIC_API_ENTRY(this);
    FAIL_IF_NEUTERED(this);
    VALIDATE_POINTER_TO_OBJECT(ppResultType, ICorDebugType **);
    ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());

    // Prefast overflow check:
    S_UINT32 allocSize = S_UINT32(cTypeArgs) * S_UINT32(sizeof(CordbType *));

    if (allocSize.IsOverflow())
    {
        return E_INVALIDARG;
    }

    CordbType ** ppTypeInstantiations = reinterpret_cast<CordbType **>(_alloca(allocSize.Value()));

    for (unsigned int i = 0; i < cTypeArgs; i++)
    {
        ppTypeInstantiations[i] = (CordbType *) rgpTypeArgs[i];
    }


    Instantiation typeInstantiation(cTypeArgs, ppTypeInstantiations);

    CordbType * pType;

    HRESULT hr = CordbType::MkType(this, ELEMENT_TYPE_FNPTR, &typeInstantiation, &pType);

    if (FAILED(hr))
    {
        return hr;
    }
    
    _ASSERTE(pType != NULL);

    pType->ExternalAddRef();

    *ppResultType = static_cast<ICorDebugType *>(pType);

    return hr;

}

//
// ICorDebugAppDomain3
//

HRESULT CordbAppDomain::GetCachedWinRTTypesForIIDs(
                        ULONG32               cGuids,
                        GUID                * iids,
                        ICorDebugTypeEnum * * ppTypesEnum)
{
#if !defined(FEATURE_COMINTEROP)

    return E_NOTIMPL;

#else

    HRESULT hr = S_OK;
    PUBLIC_API_ENTRY(this);
    FAIL_IF_NEUTERED(this);
    ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());

    _ASSERTE(!m_vmAppDomain.IsNull());


    EX_TRY
    {
        *ppTypesEnum = NULL;

        DacDbiArrayList<DebuggerIPCE_ExpandedTypeData> dacTypes;
        DacDbiArrayList<GUID> dacGuids;

        IDacDbiInterface* pDAC = GetProcess()->GetDAC();

        dacGuids.Init(iids, cGuids);

        // retrieve type info from LS
        pDAC->GetCachedWinRTTypesForIIDs(m_vmAppDomain, dacGuids, &dacTypes);

        // synthesize CordbType instances
        int cItfs = dacTypes.Count();
        NewArrayHolder<CordbType*> pTypes(NULL);

        if (cItfs > 0)
        {
            pTypes = new CordbType*[cItfs];
            for (int n = 0; n < cItfs; ++n)
            {
                hr = CordbType::TypeDataToType(this, 
                                               &(dacTypes[n]), 
                                               &pTypes[n]);
            }
        }

        // build a type enumerator
        CordbTypeEnum* pTypeEnum = CordbTypeEnum::Build(this, GetProcess()->GetContinueNeuterList(), cItfs, pTypes);
        if ( pTypeEnum == NULL )
        {
            IfFailThrow(E_OUTOFMEMORY);
        }

        (*ppTypesEnum) = static_cast<ICorDebugTypeEnum*> (pTypeEnum);
        pTypeEnum->ExternalAddRef();

    }
    EX_CATCH_HRESULT(hr);

    return hr;

#endif // !defined(FEATURE_COMINTEROP)
}

HRESULT CordbAppDomain::GetCachedWinRTTypes(
                        ICorDebugGuidToTypeEnum * * ppTypesEnum)
{
#if !defined(FEATURE_COMINTEROP)

    return E_NOTIMPL;

#else

    HRESULT hr = S_OK;
    PUBLIC_API_ENTRY(this);
    FAIL_IF_NEUTERED(this);
    ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());

    EX_TRY
    {
        *ppTypesEnum = NULL;

        DacDbiArrayList<GUID> guids;
        DacDbiArrayList<DebuggerIPCE_ExpandedTypeData> types;

        IDacDbiInterface* pDAC = GetProcess()->GetDAC();

        // retrieve type info from LS
        pDAC->GetCachedWinRTTypes(m_vmAppDomain, &guids, &types);

        _ASSERTE(guids.Count() == types.Count());
        if (guids.Count() != types.Count())
            IfFailThrow(E_FAIL);

        int cnt = types.Count();

        RsGuidToTypeMapping* pMap = new RsGuidToTypeMapping[cnt];

        for (int i = 0; i < cnt; ++i)
        {
            pMap[i].iid = guids[i];
            CordbType* pType;
            hr = CordbType::TypeDataToType(this, &(types[i]), &pType);
            if (SUCCEEDED(hr))
            {
                pMap[i].spType.Assign(pType);
            }
            else
            {
                // spType stays NULL
            }
        }

        CordbGuidToTypeEnumerator * enumerator = new CordbGuidToTypeEnumerator(GetProcess(), &pMap, cnt);
        _ASSERTE(pMap == NULL);
        GetProcess()->GetContinueNeuterList()->Add(GetProcess(), enumerator);

        hr = enumerator->QueryInterface(IID_ICorDebugGuidToTypeEnum, reinterpret_cast<void**>(ppTypesEnum));
        _ASSERTE(SUCCEEDED(hr));
        IfFailThrow(hr);

    }
    EX_CATCH_HRESULT(hr);

    return hr;

#endif // !defined(FEATURE_COMINTEROP)
}

//-----------------------------------------------------------
// ICorDebugAppDomain4
//-----------------------------------------------------------

HRESULT CordbAppDomain::GetObjectForCCW(CORDB_ADDRESS ccwPointer, ICorDebugValue **ppManagedObject)
{
#if defined(FEATURE_COMINTEROP)

    PUBLIC_API_ENTRY(this);
    FAIL_IF_NEUTERED(this);

    VALIDATE_POINTER_TO_OBJECT(ppManagedObject, ICorDebugValue **);
    HRESULT hr = S_OK;

    *ppManagedObject = NULL;

    EX_TRY
    {
        VMPTR_OBJECTHANDLE vmObjHandle = GetProcess()->GetDAC()->GetObjectForCCW(ccwPointer);
        if (vmObjHandle.IsNull())
        {
            hr = E_INVALIDARG;
        }
        else
        {
            ICorDebugReferenceValue *pRefValue = NULL;
            hr = CordbReferenceValue::BuildFromGCHandle(this, vmObjHandle, &pRefValue);
            *ppManagedObject = pRefValue;
        }
    }
    EX_CATCH_HRESULT(hr);

    return hr;

#else

    return E_NOTIMPL;

#endif // defined(FEATURE_COMINTEROP)
}