siginfo.cpp 182.9 KB
Newer Older
D
dotnet-bot 已提交
1 2
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
3 4 5 6 7 8 9 10 11 12 13 14 15
//
// siginfo.cpp
//
// Signature parsing code
//


#include "common.h"

#include "siginfo.hpp"
#include "clsload.hpp"
#include "vars.hpp"
#include "excep.h"
16
#include "gcheaputilities.h"
17 18 19 20 21 22 23 24
#include "field.h"
#include "eeconfig.h"
#include "runtimehandles.h" // for SignatureNative
#include "winwrap.h"
#include <formattype.h>
#include "sigbuilder.h"
#include "../md/compiler/custattr.h"
#include <corhlprpriv.h>
25
#include "argdestination.h"
D
Dong-Heon Jung 已提交
26
#include "multicorejit.h"
27 28

/*******************************************************************/
29
const CorTypeInfo::CorTypeInfoEntry CorTypeInfo::info[ELEMENT_TYPE_MAX] =
30 31 32 33 34 35 36 37 38
{
#define TYPEINFO(enumName,nameSpace,className,size,gcType,isArray,isPrim,isFloat,isModifier,isGenVar) \
    { nameSpace, className, enumName, size, gcType, isArray, isPrim, isFloat, isModifier, isGenVar },
#include "cortypeinfo.h"
#   undef TYPEINFO
};

/*******************************************************************/
/* static */
39
CorElementType
40 41 42
CorTypeInfo::FindPrimitiveType(LPCUTF8 name)
{
    LIMITED_METHOD_CONTRACT;
43

44
    _ASSERTE(name != NULL);
45

46
    for (unsigned int i = 1; i < ARRAY_SIZE(CorTypeInfo::info); i++)
47 48 49 50
    {   // can skip ELEMENT_TYPE_END (index 0)
        if ((info[i].className != NULL) && (strcmp(name, info[i].className) == 0))
            return (CorElementType)i;
    }
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
    return ELEMENT_TYPE_END;
}

const ElementTypeInfo gElementTypeInfo[] = {

#ifdef _DEBUG
#define DEFINEELEMENTTYPEINFO(etname, cbsize, gcness, inreg) {(int)(etname),cbsize,gcness,inreg},
#else
#define DEFINEELEMENTTYPEINFO(etname, cbsize, gcness, inreg) {cbsize,gcness,inreg},
#endif

// Meaning of columns:
//
//     name     - The checked build uses this to verify that the table is sorted
//                correctly. This is a lookup table that uses ELEMENT_TYPE_*
//                as an array index.
//
//     cbsize   - The byte size of this value as returned by SizeOf(). SPECIAL VALUE: -1
//                requires type-specific treatment.
//
//     gc       - 0    no embedded objectrefs
//                1    value is an objectref
//                2    value is an interior pointer - promote it but don't scan it
//                3    requires type-specific treatment
//
//     reg      - put in a register?
78
//
79 80
// Note: This table is very similar to the one in file:corTypeInfo.h with these exceptions:
//  reg column is missing in corTypeInfo.h
81
//  ELEMENT_TYPE_VAR, ELEMENT_TYPE_GENERICINST, ELEMENT_TYPE_MVAR ... size -1 vs. TARGET_POINTER_SIZE in corTypeInfo.h
82 83
//  ELEMENT_TYPE_CMOD_REQD, ELEMENT_TYPE_CMOD_OPT, ELEMENT_TYPE_INTERNAL ... size -1 vs. 0 in corTypeInfo.h
//  ELEMENT_TYPE_INTERNAL ... GC type is TYPE_GC_NONE vs. TYPE_GC_OTHER in corTypeInfo.h
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
//                    name                         cbsize                gc             reg
DEFINEELEMENTTYPEINFO(ELEMENT_TYPE_END,            -1,                   TYPE_GC_NONE,  0)
DEFINEELEMENTTYPEINFO(ELEMENT_TYPE_VOID,           0,                    TYPE_GC_NONE,  0)
DEFINEELEMENTTYPEINFO(ELEMENT_TYPE_BOOLEAN,        1,                    TYPE_GC_NONE,  1)
DEFINEELEMENTTYPEINFO(ELEMENT_TYPE_CHAR,           2,                    TYPE_GC_NONE,  1)

DEFINEELEMENTTYPEINFO(ELEMENT_TYPE_I1,             1,                    TYPE_GC_NONE,  1)
DEFINEELEMENTTYPEINFO(ELEMENT_TYPE_U1,             1,                    TYPE_GC_NONE,  1)
DEFINEELEMENTTYPEINFO(ELEMENT_TYPE_I2,             2,                    TYPE_GC_NONE,  1)
DEFINEELEMENTTYPEINFO(ELEMENT_TYPE_U2,             2,                    TYPE_GC_NONE,  1)

DEFINEELEMENTTYPEINFO(ELEMENT_TYPE_I4,             4,                    TYPE_GC_NONE,  1)
DEFINEELEMENTTYPEINFO(ELEMENT_TYPE_U4,             4,                    TYPE_GC_NONE,  1)
DEFINEELEMENTTYPEINFO(ELEMENT_TYPE_I8,             8,                    TYPE_GC_NONE,  0)
DEFINEELEMENTTYPEINFO(ELEMENT_TYPE_U8,             8,                    TYPE_GC_NONE,  0)

DEFINEELEMENTTYPEINFO(ELEMENT_TYPE_R4,             4,                    TYPE_GC_NONE,  0)
DEFINEELEMENTTYPEINFO(ELEMENT_TYPE_R8,             8,                    TYPE_GC_NONE,  0)
DEFINEELEMENTTYPEINFO(ELEMENT_TYPE_STRING,         TARGET_POINTER_SIZE,  TYPE_GC_REF,   1)
DEFINEELEMENTTYPEINFO(ELEMENT_TYPE_PTR,            TARGET_POINTER_SIZE,  TYPE_GC_NONE,  1)

DEFINEELEMENTTYPEINFO(ELEMENT_TYPE_BYREF,          TARGET_POINTER_SIZE,  TYPE_GC_BYREF, 1)
DEFINEELEMENTTYPEINFO(ELEMENT_TYPE_VALUETYPE,      -1,                   TYPE_GC_OTHER, 0)
DEFINEELEMENTTYPEINFO(ELEMENT_TYPE_CLASS,          TARGET_POINTER_SIZE,  TYPE_GC_REF,   1)
DEFINEELEMENTTYPEINFO(ELEMENT_TYPE_VAR,            -1,                   TYPE_GC_OTHER, 1)

DEFINEELEMENTTYPEINFO(ELEMENT_TYPE_ARRAY,          TARGET_POINTER_SIZE,  TYPE_GC_REF,   1)

DEFINEELEMENTTYPEINFO(ELEMENT_TYPE_GENERICINST,    -1,                   TYPE_GC_OTHER, 0)

115
DEFINEELEMENTTYPEINFO(ELEMENT_TYPE_TYPEDBYREF,     TARGET_POINTER_SIZE*2,TYPE_GC_OTHER, 0)
116 117 118 119 120 121 122 123 124 125 126 127 128
DEFINEELEMENTTYPEINFO(ELEMENT_TYPE_VALUEARRAY_UNSUPPORTED, -1,           TYPE_GC_NONE,  0)
DEFINEELEMENTTYPEINFO(ELEMENT_TYPE_I,              TARGET_POINTER_SIZE,  TYPE_GC_NONE,  1)
DEFINEELEMENTTYPEINFO(ELEMENT_TYPE_U,              TARGET_POINTER_SIZE,  TYPE_GC_NONE,  1)
DEFINEELEMENTTYPEINFO(ELEMENT_TYPE_R_UNSUPPORTED,  -1,                   TYPE_GC_NONE,  0)

DEFINEELEMENTTYPEINFO(ELEMENT_TYPE_FNPTR,          TARGET_POINTER_SIZE,  TYPE_GC_NONE,  1)
DEFINEELEMENTTYPEINFO(ELEMENT_TYPE_OBJECT,         TARGET_POINTER_SIZE,  TYPE_GC_REF,   1)
DEFINEELEMENTTYPEINFO(ELEMENT_TYPE_SZARRAY,        TARGET_POINTER_SIZE,  TYPE_GC_REF,   1)

DEFINEELEMENTTYPEINFO(ELEMENT_TYPE_MVAR,           -1,                   TYPE_GC_OTHER, 1)
DEFINEELEMENTTYPEINFO(ELEMENT_TYPE_CMOD_REQD,      -1,                   TYPE_GC_NONE,  1)
DEFINEELEMENTTYPEINFO(ELEMENT_TYPE_CMOD_OPT,       -1,                   TYPE_GC_NONE,  1)
DEFINEELEMENTTYPEINFO(ELEMENT_TYPE_INTERNAL,       -1,                   TYPE_GC_NONE,  0)
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
};

unsigned GetSizeForCorElementType(CorElementType etyp)
{
        LIMITED_METHOD_DAC_CONTRACT;
        _ASSERTE(gElementTypeInfo[etyp].m_elementType == etyp);
        return gElementTypeInfo[etyp].m_cbSize;
}

#ifndef DACCESS_COMPILE

void SigPointer::ConvertToInternalExactlyOne(Module* pSigModule, SigTypeContext *pTypeContext, SigBuilder * pSigBuilder, BOOL bSkipCustomModifier)
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        STANDARD_VM_CHECK;

        PRECONDITION(CheckPointer(pSigModule));
    }
    CONTRACTL_END

    SigPointer sigStart = *this;

    CorElementType typ = ELEMENT_TYPE_END;

    // Check whether we need to skip custom modifier
    // Only preserve custom modifier when calculating IL stub hash blob
    if (bSkipCustomModifier)
    {
        // GetElemType eats sentinel and custom modifiers
        IfFailThrowBF(GetElemType(&typ), BFA_BAD_COMPLUS_SIG, pSigModule);
    }
    else
163
    {
164 165 166
        BYTE byElemType;

        IfFailThrowBF(SkipAnyVASentinel(), BFA_BAD_COMPLUS_SIG, pSigModule);
167

168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
        // Call GetByte and make sure we don't lose custom modifiers
        IfFailThrowBF(GetByte(&byElemType), BFA_BAD_COMPLUS_SIG, pSigModule);
        typ = (CorElementType) byElemType;
    }

    if (typ == ELEMENT_TYPE_CLASS || typ == ELEMENT_TYPE_VALUETYPE)
    {
        IfFailThrowBF(GetToken(NULL), BFA_BAD_COMPLUS_SIG, pSigModule);
        TypeHandle th = sigStart.GetTypeHandleThrowing(pSigModule, pTypeContext);

        pSigBuilder->AppendElementType(ELEMENT_TYPE_INTERNAL);
        pSigBuilder->AppendPointer(th.AsPtr());
        return;
    }

    if (pTypeContext != NULL)
    {
185
        uint32_t varNum;
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
        if (typ == ELEMENT_TYPE_VAR)
        {
            IfFailThrowBF(GetData(&varNum), BFA_BAD_COMPLUS_SIG, pSigModule);
            THROW_BAD_FORMAT_MAYBE(varNum < pTypeContext->m_classInst.GetNumArgs(), BFA_BAD_COMPLUS_SIG, pSigModule);

            pSigBuilder->AppendElementType(ELEMENT_TYPE_INTERNAL);
            pSigBuilder->AppendPointer(pTypeContext->m_classInst[varNum].AsPtr());
            return;
        }
        if (typ == ELEMENT_TYPE_MVAR)
        {
            IfFailThrowBF(GetData(&varNum), BFA_BAD_COMPLUS_SIG, pSigModule);
            THROW_BAD_FORMAT_MAYBE(varNum < pTypeContext->m_methodInst.GetNumArgs(), BFA_BAD_COMPLUS_SIG, pSigModule);

            pSigBuilder->AppendElementType(ELEMENT_TYPE_INTERNAL);
            pSigBuilder->AppendPointer(pTypeContext->m_methodInst[varNum].AsPtr());
            return;
        }
    }

    pSigBuilder->AppendElementType(typ);

    if (!CorIsPrimitiveType(typ))
    {
        switch (typ)
        {
            default:
                THROW_BAD_FORMAT(BFA_BAD_COMPLUS_SIG, pSigModule);
                break;
            case ELEMENT_TYPE_VAR:
            case ELEMENT_TYPE_MVAR:
                {
218
                    uint32_t varNum;
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
                    // Skip variable number
                    IfFailThrowBF(GetData(&varNum), BFA_BAD_COMPLUS_SIG, pSigModule);
                    pSigBuilder->AppendData(varNum);
                }
                break;
            case ELEMENT_TYPE_OBJECT:
            case ELEMENT_TYPE_STRING:
            case ELEMENT_TYPE_TYPEDBYREF:
                break;

            case ELEMENT_TYPE_BYREF: //fallthru
            case ELEMENT_TYPE_PTR:
            case ELEMENT_TYPE_PINNED:
            case ELEMENT_TYPE_SZARRAY:
                ConvertToInternalExactlyOne(pSigModule, pTypeContext, pSigBuilder, bSkipCustomModifier);
                break;

            case ELEMENT_TYPE_FNPTR:
                ConvertToInternalSignature(pSigModule, pTypeContext, pSigBuilder, bSkipCustomModifier);
                break;

            case ELEMENT_TYPE_ARRAY:
                {
                    ConvertToInternalExactlyOne(pSigModule, pTypeContext, pSigBuilder, bSkipCustomModifier);

244
                    uint32_t rank = 0; // Get rank
245 246 247 248 249
                    IfFailThrowBF(GetData(&rank), BFA_BAD_COMPLUS_SIG, pSigModule);
                    pSigBuilder->AppendData(rank);

                    if (rank)
                    {
250
                        uint32_t nsizes = 0;
251 252 253 254 255
                        IfFailThrowBF(GetData(&nsizes), BFA_BAD_COMPLUS_SIG, pSigModule);
                        pSigBuilder->AppendData(nsizes);

                        while (nsizes--)
                        {
256
                            uint32_t data = 0;
257 258 259 260
                            IfFailThrowBF(GetData(&data), BFA_BAD_COMPLUS_SIG, pSigModule);
                            pSigBuilder->AppendData(data);
                        }

261
                        uint32_t nlbounds = 0;
262 263 264 265 266
                        IfFailThrowBF(GetData(&nlbounds), BFA_BAD_COMPLUS_SIG, pSigModule);
                        pSigBuilder->AppendData(nlbounds);

                        while (nlbounds--)
                        {
267
                            uint32_t data = 0;
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
                            IfFailThrowBF(GetData(&data), BFA_BAD_COMPLUS_SIG, pSigModule);
                            pSigBuilder->AppendData(data);
                        }
                    }
                }
                break;

            case ELEMENT_TYPE_INTERNAL:
                {
                    // this check is not functional in DAC and provides no security against a malicious dump
                    // the DAC is prepared to receive an invalid type handle
#ifndef DACCESS_COMPILE
                    if (pSigModule->IsSigInIL(m_ptr))
                        THROW_BAD_FORMAT(BFA_BAD_COMPLUS_SIG, pSigModule);
#endif

                    TypeHandle hType;

                    IfFailThrowBF(GetPointer((void**)&hType), BFA_BAD_COMPLUS_SIG, pSigModule);

                    pSigBuilder->AppendPointer(hType.AsPtr());
                }
                break;

            case ELEMENT_TYPE_GENERICINST:
                {
                    TypeHandle genericType = GetGenericInstType(pSigModule);

                    pSigBuilder->AppendElementType(ELEMENT_TYPE_INTERNAL);
                    pSigBuilder->AppendPointer(genericType.AsPtr());

299
                    uint32_t argCnt = 0; // Get number of parameters
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
                    IfFailThrowBF(GetData(&argCnt), BFA_BAD_COMPLUS_SIG, pSigModule);
                    pSigBuilder->AppendData(argCnt);

                    while (argCnt--)
                    {
                        ConvertToInternalExactlyOne(pSigModule, pTypeContext, pSigBuilder, bSkipCustomModifier);
                    }
                }
                break;

            // Note: the following is only for correctly computing IL stub hash for modifiers in order to support C++ scenarios
            case ELEMENT_TYPE_CMOD_OPT:
            case ELEMENT_TYPE_CMOD_REQD:
                {
                    mdToken tk;
                    IfFailThrowBF(GetToken(&tk), BFA_BAD_COMPLUS_SIG, pSigModule);
316
                    TypeHandle th = ClassLoader::LoadTypeDefOrRefThrowing(pSigModule, tk);
317
                    pSigBuilder->AppendElementType(ELEMENT_TYPE_INTERNAL);
318
                    pSigBuilder->AppendPointer(th.AsPtr());
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
                    ConvertToInternalExactlyOne(pSigModule, pTypeContext, pSigBuilder, bSkipCustomModifier);
                }
                break;
        }
    }
}

void SigPointer::ConvertToInternalSignature(Module* pSigModule, SigTypeContext *pTypeContext, SigBuilder * pSigBuilder, BOOL bSkipCustomModifier)
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        STANDARD_VM_CHECK;

        PRECONDITION(CheckPointer(pSigModule));
    }
    CONTRACTL_END

    BYTE uCallConv = 0;
    IfFailThrowBF(GetByte(&uCallConv), BFA_BAD_COMPLUS_SIG, pSigModule);

    if ((uCallConv & IMAGE_CEE_CS_CALLCONV_MASK) == IMAGE_CEE_CS_CALLCONV_FIELD)
        THROW_BAD_FORMAT(BFA_UNEXPECTED_FIELD_SIGNATURE, pSigModule);

    pSigBuilder->AppendByte(uCallConv);

    // Skip type parameter count
    if (uCallConv & IMAGE_CEE_CS_CALLCONV_GENERIC)
    {
349
        uint32_t nParams = 0;
350 351 352 353 354
        IfFailThrowBF(GetData(&nParams), BFA_BAD_COMPLUS_SIG, pSigModule);
        pSigBuilder->AppendData(nParams);
    }

    // Get arg count;
355
    uint32_t cArgs = 0;
356 357 358 359 360 361
    IfFailThrowBF(GetData(&cArgs), BFA_BAD_COMPLUS_SIG, pSigModule);
    pSigBuilder->AppendData(cArgs);

    cArgs++; // +1 for return type

    // Skip args.
362
    while (cArgs)
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
    {
        ConvertToInternalExactlyOne(pSigModule, pTypeContext, pSigBuilder, bSkipCustomModifier);
        cArgs--;
    }
}
#endif // DACCESS_COMPILE


//---------------------------------------------------------------------------------------
//
// Default constructor for creating an empty Signature, i.e. with a NULL raw PCCOR_SIGNATURE pointer.
//

Signature::Signature()
{
    LIMITED_METHOD_CONTRACT;

    m_pSig = NULL;
    m_cbSig = 0;
}

//---------------------------------------------------------------------------------------
//
// Primary constructor for creating a Signature.
//
// Arguments:
//    pSig  - raw PCCOR_SIGNATURE pointer
//    cbSig - length of the signature
//

Signature::Signature(PCCOR_SIGNATURE pSig,
                     DWORD           cbSig)
{
    LIMITED_METHOD_CONTRACT;
    SUPPORTS_DAC;   // host-only data structure - not marshalled

    m_pSig = pSig;
    m_cbSig = cbSig;
}

//---------------------------------------------------------------------------------------
//
// Check if the Signature is empty, i.e. has a NULL raw PCCOR_SIGNATURE
//
// Return Value:
//    TRUE if the raw PCCOR_SIGNATURE is NULL
//

BOOL Signature::IsEmpty() const
{
    LIMITED_METHOD_CONTRACT;
    SUPPORTS_DAC;
    return (m_pSig == NULL);
}

//---------------------------------------------------------------------------------------
//
// Create a SigParser over the Signature.  In DAC builds, grab the signature bytes from out of process first.
//
// Return Value:
//    a SigpParser for this particular Signature
//

SigParser Signature::CreateSigParser() const
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

#if defined(DACCESS_COMPILE)
    // Copy the signature bytes from the target process.
    PCCOR_SIGNATURE pTargetSig = (PCCOR_SIGNATURE)DacInstantiateTypeByAddress((TADDR)m_pSig, m_cbSig, true);
    return SigParser(pTargetSig, m_cbSig);
#else  // !DACCESS_COMPILE
    return SigParser(m_pSig, m_cbSig);
#endif // !DACCESS_COMPILE
}

//---------------------------------------------------------------------------------------
//
// Create a SigPointer over the Signature.  In DAC builds, grab the signature bytes from out of process first.
//
// Return Value:
//    a SigPointer for this particular Signature
//

SigPointer Signature::CreateSigPointer() const
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

#if defined(DACCESS_COMPILE)
    // Copy the signature bytes from the target process.
    PCCOR_SIGNATURE pTargetSig = (PCCOR_SIGNATURE)DacInstantiateTypeByAddress((TADDR)m_pSig, m_cbSig, true);
    return SigPointer(pTargetSig, m_cbSig);
#else  // !DACCESS_COMPILE
    return SigPointer(m_pSig, m_cbSig);
#endif // !DACCESS_COMPILE
}

//---------------------------------------------------------------------------------------
//
// Pretty-print the Signature.  This is just a wrapper over code:PrettyPrintSig().
//
// Arguments:
//    pszMethodName - the name of the method in question
//    pqbOut        - a CQuickBytes array for allocating memory
//    pIMDI         - a IMDInternalImport interface for resolving tokens
//
// Return Value:
//    whatever PrettyPrintSig() returns
//

void Signature::PrettyPrint(const CHAR * pszMethodName,
                            CQuickBytes * pqbOut,
                            IMDInternalImport * pIMDI) const
{
    WRAPPER_NO_CONTRACT;
    PrettyPrintSig(this->GetRawSig(), this->GetRawSigLen(), pszMethodName, pqbOut, pIMDI, NULL);
}

//---------------------------------------------------------------------------------------
//
A
Adeel Mujahid 已提交
495
// Get the raw signature pointer contained in this Signature.
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
//
// Return Value:
//    the raw signature pointer
//
// Notes:
//    Use this ONLY IF there is no other way to do what you want to do!
//    In most cases you just want a SigParser/SigPointer from the Signature.
//

PCCOR_SIGNATURE Signature::GetRawSig() const
{
    LIMITED_METHOD_CONTRACT;
    SUPPORTS_DAC;
    return m_pSig;
}

//---------------------------------------------------------------------------------------
//
A
Adeel Mujahid 已提交
514
// Get the length of the raw signature contained in this Signature.
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
//
// Return Value:
//    the length of the raw signature
//
// Notes:
//    Use this ONLY IF there is no other way to do what you want to do!
//    In most cases you just want a SigParser/SigPointer from the Signature.
//

DWORD Signature::GetRawSigLen() const
{
    LIMITED_METHOD_DAC_CONTRACT;
    return m_cbSig;
}


//---------------------------------------------------------------------------------------
532
//
533
// Constructor.
534
//
535
void MetaSig::Init(
536 537 538 539
    PCCOR_SIGNATURE        szMetaSig,
    DWORD                  cbMetaSig,
    Module *               pModule,
    const SigTypeContext * pTypeContext,
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
    MetaSigKind            kind)
{
    CONTRACTL
    {
        CONSTRUCTOR_CHECK;
        NOTHROW;
        MODE_ANY;
        GC_NOTRIGGER;
        FORBID_FAULT;
        PRECONDITION(CheckPointer(szMetaSig));
        PRECONDITION(CheckPointer(pModule));
        PRECONDITION(CheckPointer(pTypeContext, NULL_OK));
        SUPPORTS_DAC;
    }
    CONTRACTL_END


#ifdef _DEBUG
    FillMemory(this, sizeof(*this), 0xcc);
#endif

    // Copy the type context
    SigTypeContext::InitTypeContext(pTypeContext,&m_typeContext);
    m_pModule = pModule;

    SigPointer psig(szMetaSig, cbMetaSig);

    HRESULT hr;

    switch (kind)
    {
        case sigLocalVars:
        {
573
            uint32_t data = 0;
574 575
            IfFailGo(psig.GetCallingConvInfo(&data)); // Store calling convention
            m_CallConv = (BYTE)data;
576

577 578 579 580 581 582 583 584
            IfFailGo(psig.GetData(&data));  // Store number of arguments.
            m_nArgs = data;

            m_pRetType = SigPointer(NULL, 0);
            break;
        }
        case sigMember:
        {
585
            uint32_t data = 0;
586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
            IfFailGo(psig.GetCallingConvInfo(&data)); // Store calling convention
            m_CallConv = (BYTE)data;

            // Store type parameter count
            if (m_CallConv & IMAGE_CEE_CS_CALLCONV_GENERIC)
            {
                IfFailGo(psig.GetData(NULL));
            }

            IfFailGo(psig.GetData(&data));  // Store number of arguments.
            m_nArgs = data;
            m_pRetType = psig;
            IfFailGo(psig.SkipExactlyOne());
            break;
        }
        case sigField:
        {
603
            uint32_t data = 0;
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
            IfFailGo(psig.GetCallingConvInfo(&data)); // Store calling convention
            m_CallConv = (BYTE)data;

            m_nArgs = 1; //There's only 1 'arg' - the type.
            m_pRetType = SigPointer(NULL, 0);
            break;
        }
        default:
        {
            UNREACHABLE();
            goto ErrExit;
        }
    }

    m_pStart = psig;
    m_flags = 0;
620

621 622 623 624 625 626 627 628 629
    // Reset the iterator fields
    Reset();

    return;

ErrExit:
    // Invalid signature or parameter
    m_CallConv = 0;
    INDEBUG(m_CallConv = 0xff;)
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
    m_nArgs = 0;
    m_pRetType = SigPointer(NULL, 0);
} // MetaSig::MetaSig


// Helper constructor that constructs a method signature MetaSig from a MethodDesc
// IMPORTANT: if classInst/methodInst is omitted and the MethodDesc is shared between generic
// instantiations then the instantiation info for the method will be representative.  This
// is OK for GC, field layout etc. but not OK where exact types matter.
//
// Also, if used on a shared instantiated method descriptor or instance method in a shared generic struct
// then the calling convention is fixed up to include the extra dictionary argument
//
// For method descs from array types the "instantiation" is set to the element type of the array
// This lets us use VAR in the signatures for Get, Set and Address
MetaSig::MetaSig(MethodDesc *pMD, Instantiation classInst, Instantiation methodInst)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    SigTypeContext typeContext(pMD, classInst, methodInst);

    PCCOR_SIGNATURE pSig;
    DWORD cbSigSize;
    pMD->GetSig(&pSig, &cbSigSize);

662
    Init(pSig, cbSigSize, pMD->GetModule(), &typeContext);
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682

    if (pMD->RequiresInstArg())
        SetHasParamTypeArg();
}

MetaSig::MetaSig(MethodDesc *pMD, TypeHandle declaringType)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    SigTypeContext typeContext(pMD, declaringType);
    PCCOR_SIGNATURE pSig;
    DWORD cbSigSize;
    pMD->GetSig(&pSig, &cbSigSize);

683
    Init(pSig, cbSigSize, pMD->GetModule(), &typeContext);
684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706

    if (pMD->RequiresInstArg())
        SetHasParamTypeArg();
}

#ifdef _DEBUG
//*******************************************************************************
static BOOL MethodDescMatchesSig(MethodDesc* pMD, PCCOR_SIGNATURE pSig, DWORD cSig, Module * pModule)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        INJECT_FAULT(COMPlusThrowOM());
        MODE_ANY;
    }
    CONTRACTL_END

    PCCOR_SIGNATURE pSigOfMD;
    DWORD cSigOfMD;
    pMD->GetSig(&pSigOfMD, &cSigOfMD);

    return MetaSig::CompareMethodSigs(pSig, cSig, pModule, NULL,
707
                                      pSigOfMD, cSigOfMD, pMD->GetModule(), NULL, FALSE);
708 709 710 711 712 713 714 715 716 717 718 719 720 721 722
}
#endif // _DEBUG

MetaSig::MetaSig(BinderMethodID id)
{
    CONTRACTL
    {
        CONSTRUCTOR_CHECK;
        THROWS;
        MODE_ANY;
        GC_TRIGGERS;
        INJECT_FAULT(COMPlusThrowOM());
    }
    CONTRACTL_END

723
    Signature sig = CoreLibBinder::GetMethodSignature(id);
724

725 726
    _ASSERTE(MethodDescMatchesSig(CoreLibBinder::GetMethod(id),
        sig.GetRawSig(), sig.GetRawSigLen(), CoreLibBinder::GetModule()));
727

728
    Init(sig.GetRawSig(), sig.GetRawSigLen(), CoreLibBinder::GetModule(), NULL);
729 730 731 732 733 734 735 736 737 738 739 740 741 742
}

MetaSig::MetaSig(LPHARDCODEDMETASIG pwzMetaSig)
{
    CONTRACTL
    {
        CONSTRUCTOR_CHECK;
        THROWS;
        MODE_ANY;
        GC_TRIGGERS;
        INJECT_FAULT(COMPlusThrowOM());
    }
    CONTRACTL_END

743
    Signature sig = CoreLibBinder::GetSignature(pwzMetaSig);
744

745
    Init(sig.GetRawSig(), sig.GetRawSigLen(), CoreLibBinder::GetModule(), NULL);
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
}

// Helper constructor that constructs a field signature MetaSig from a FieldDesc
// IMPORTANT: the classInst is omitted then the instantiation info for the field
// will be representative only as FieldDescs can be shared
//
MetaSig::MetaSig(FieldDesc *pFD, TypeHandle declaringType)
{
    CONTRACTL
    {
        CONSTRUCTOR_CHECK;
        NOTHROW;
        MODE_ANY;
        GC_NOTRIGGER;
        PRECONDITION(CheckPointer(pFD));
    }
    CONTRACTL_END

    PCCOR_SIGNATURE pSig;
    DWORD           cSig;

    pFD->GetSig(&pSig, &cSig);

    SigTypeContext typeContext(pFD, declaringType);

    Init(pSig, cSig, pFD->GetModule(),&typeContext, sigField);
}

//---------------------------------------------------------------------------------------
775
//
776 777
// Returns type of current argument index. Returns ELEMENT_TYPE_END
// if already past end of arguments.
778 779
//
CorElementType
780 781 782 783 784 785 786 787 788 789 790 791
MetaSig::PeekArg() const
{
    WRAPPER_NO_CONTRACT;

    if (m_iCurArg == m_nArgs)
    {
        return ELEMENT_TYPE_END;
    }
    return m_pWalk.PeekElemTypeClosed(GetModule(), &m_typeContext);
}

//---------------------------------------------------------------------------------------
792
//
793 794
// Returns type of current argument index. Returns ELEMENT_TYPE_END
// if already past end of arguments.
795 796
//
CorElementType
797 798 799 800 801 802 803 804 805 806 807 808
MetaSig::PeekArgNormalized(TypeHandle * pthValueType) const
{
    WRAPPER_NO_CONTRACT;

    if (m_iCurArg == m_nArgs)
    {
        return ELEMENT_TYPE_END;
    }
    return m_pWalk.PeekElemTypeNormalized(m_pModule, &m_typeContext, pthValueType);
}

//---------------------------------------------------------------------------------------
809
//
810 811
// Returns type of current argument, then advances the argument
// index. Returns ELEMENT_TYPE_END if already past end of arguments.
812 813
//
CorElementType
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
MetaSig::NextArg()
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        NOTHROW;
        MODE_ANY;
        GC_NOTRIGGER;
        FORBID_FAULT;
        SUPPORTS_DAC;
    }
    CONTRACTL_END

    m_pLastType = m_pWalk;

    if (m_iCurArg == m_nArgs)
    {
        return ELEMENT_TYPE_END;
    }
    m_iCurArg++;
    CorElementType mt = m_pWalk.PeekElemTypeClosed(GetModule(), &m_typeContext);
    if (FAILED(m_pWalk.SkipExactlyOne()))
    {
        m_pWalk = m_pLastType;
        return ELEMENT_TYPE_END;
    }
    return mt;
}

//---------------------------------------------------------------------------------------
844
//
845 846
// Advance the argument index. Can be used with GetArgProps() to
// to iterate when you do not have a valid type context
847 848
//
void
849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866
MetaSig::SkipArg()
{
    WRAPPER_NO_CONTRACT;

    m_pLastType = m_pWalk;

    if (m_iCurArg < m_nArgs)
    {
        m_iCurArg++;
        if (FAILED(m_pWalk.SkipExactlyOne()))
        {
            m_pWalk = m_pLastType;
            m_iCurArg = m_nArgs;
        }
    }
}

//---------------------------------------------------------------------------------------
867
//
868
// reset: goto start pos
869 870
//
VOID
871 872 873 874 875 876 877 878 879 880 881 882
MetaSig::Reset()
{
    LIMITED_METHOD_DAC_CONTRACT;

    m_pWalk = m_pStart;
    m_iCurArg  = 0;
    return;
}

#ifndef DACCESS_COMPILE

//---------------------------------------------------------------------------------------
883 884
//
BOOL
885
IsTypeRefOrDef(
886 887
    LPCSTR   szClassName,
    Module * pModule,
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
    mdToken  token)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        FORBID_FAULT;
        MODE_ANY;
    }
    CONTRACTL_END

    LPCUTF8  pclsname;
    LPCUTF8 pszNamespace;

    IMDInternalImport *pInternalImport = pModule->GetMDImport();

    if (TypeFromToken(token) == mdtTypeDef)
    {
        if (FAILED(pInternalImport->GetNameOfTypeDef(token, &pclsname, &pszNamespace)))
        {
            return false;
        }
    }
    else if (TypeFromToken(token) == mdtTypeRef)
    {
        if (FAILED(pInternalImport->GetNameOfTypeRef(token, &pszNamespace, &pclsname)))
        {
            return false;
        }
    }
    else
    {
            return false;
    }
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
    // If the namespace is not the same.
    int iLen = (int)strlen(pszNamespace);
    if (iLen)
    {
        if (strncmp(szClassName, pszNamespace, iLen) != 0)
            return(false);

        if (szClassName[iLen] != NAMESPACE_SEPARATOR_CHAR)
            return(false);
        ++iLen;
    }

    if (strcmp(&szClassName[iLen], pclsname) != 0)
        return(false);
    return(true);
} // IsTypeRefOrDef

TypeHandle SigPointer::GetTypeHandleNT(Module* pModule,
                                       const SigTypeContext *pTypeContext) const
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        NOTHROW;
        MODE_ANY;
        GC_TRIGGERS;
    }
    CONTRACTL_END

    TypeHandle th;
    EX_TRY
    {
        th = GetTypeHandleThrowing(pModule, pTypeContext);
    }
    EX_CATCH
    {
    }
    EX_END_CATCH(SwallowAllExceptions)
    return(th);
}

#endif // #ifndef DACCESS_COMPILE


#ifdef _PREFAST_
#pragma warning(push)
#pragma warning(disable:21000) // Suppress PREFast warning about overly large function
#endif

// Method: TypeHandle SigPointer::GetTypeHandleThrowing()
// pZapSigContext is only set when decoding zapsigs
974
//
975
TypeHandle SigPointer::GetTypeHandleThrowing(
976
                 ModuleBase *                pModule,
977 978 979 980 981 982
                 const SigTypeContext *      pTypeContext,
                 ClassLoader::LoadTypesFlag  fLoadTypes/*=LoadTypes*/,
                 ClassLoadLevel              level/*=CLASS_LOADED*/,
                 BOOL                        dropGenericArgumentLevel/*=FALSE*/,
                 const Substitution *        pSubst/*=NULL*/,
                 // ZapSigContext is only set when decoding zapsigs
983
                 const ZapSig::Context *     pZapSigContext,
984 985
                 MethodTable *               pMTInterfaceMapOwner,
                 HandleRecursiveGenericsForFieldLayoutLoad *pRecursiveFieldGenericHandling) const
986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001
{
    CONTRACT(TypeHandle)
    {
        INSTANCE_CHECK;
        if (FORBIDGC_LOADER_USE_ENABLED()) NOTHROW; else THROWS;
        MODE_ANY;
        if (FORBIDGC_LOADER_USE_ENABLED()) GC_NOTRIGGER; else GC_TRIGGERS;
        if (FORBIDGC_LOADER_USE_ENABLED()) FORBID_FAULT; else { INJECT_FAULT(COMPlusThrowOM()); }
        if (FORBIDGC_LOADER_USE_ENABLED() || fLoadTypes != ClassLoader::LoadTypes) { LOADS_TYPE(CLASS_LOAD_BEGIN); } else { LOADS_TYPE(level); }
        PRECONDITION(CheckPointer(pModule));
        PRECONDITION(level > CLASS_LOAD_BEGIN && level <= CLASS_LOADED);
        POSTCONDITION(CheckPointer(RETVAL, ((fLoadTypes == ClassLoader::LoadTypes) ? NULL_NOT_OK : NULL_OK)));
        SUPPORTS_DAC;
    }
    CONTRACT_END

1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
    _ASSERTE(!pRecursiveFieldGenericHandling || dropGenericArgumentLevel); // pRecursiveFieldGenericHandling can only be set if dropGenericArgumentLevel is set
    if (pRecursiveFieldGenericHandling != NULL)
    {
        // if pRecursiveFieldGenericHandling is set, we must allow loading types
        _ASSERTE(fLoadTypes == ClassLoader::LoadTypes);
        // if pRecursiveFieldGenericHandling is set, then substitutions must not be enabled.
        _ASSERTE(pSubst == NULL);
        // FORBIDGC_LOADER_USE_ENABLED must not be enabled
        _ASSERTE(!FORBIDGC_LOADER_USE_ENABLED());
        // Zap sig context must be NULL, as this can only happen in the type loader itself
        _ASSERTE(pZapSigContext == NULL);
        // Similarly with the pMTInterfaceMapOwner logic
        _ASSERTE(pMTInterfaceMapOwner == NULL);

        // This may throw an exception using the FullModule
        _ASSERTE(pModule->IsFullModule());
    }
    

1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
    // We have an invariant that before we call a method, we must have loaded all of the valuetype parameters of that
    // method visible from the signature of the method. Normally we do this via type loading before the method is called
    // by walking the signature of the callee method at jit time, and loading all of the valuetype arguments at that time.
    // For NGEN, we record which valuetypes need to be loaded, and force load those types when the caller method is first executed.
    // However, in certain circumstances involving generics the jit does not have the opportunity to observe the complete method
    // signature that may be used a signature walk time. See example below.
    //
    //
//using System;
//
//struct A<T> { }
//struct B<T> { }
//
//interface Interface<T>
//{ A<T> InterfaceFunc(); }
//
//class Base<T>
//{ public virtual B<T> Func() { return default(B<T>); }  }
//
//class C<U,T> where U:Base<T>, Interface<T>
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
//  public static void CallFunc(U u) { u.Func(); }
//  public static void CallInterfaceFunc(U u) { u.InterfaceFunc(); }
//}
//
//class Problem : Base<object>, Interface<object>
//{
//    public A<object> InterfaceFunc() { return new A<object>(); }
//    public override B<object> Func() { return new B<object>(); }
//}
//
//class Test
//{
//    static void Main()
//    {
//        C<Problem, object>.CallFunc(new Problem());
//        C<Problem, object>.CallInterfaceFunc(new Problem());
//    }
//}
//
    // In this example, when CallFunc and CallInterfaceFunc are jitted, the types that will
    // be loaded during JIT time are A<__Canon> and <__Canon>. Thus we need to be able to only
    // search for canonical type arguments during these restricted time periods. IsGCThread() || IsStackWalkerThread() is the current
    // predicate for determining this.

#ifdef _DEBUG
    if ((IsGCThread() || IsStackWalkerThread()) && (fLoadTypes == ClassLoader::LoadTypes))
    {
        // The callers are expected to pass the right arguments in
        _ASSERTE(level == CLASS_LOAD_APPROXPARENTS);
        _ASSERTE(dropGenericArgumentLevel == TRUE);
    }
#endif

    TypeHandle thRet;
    SigPointer     psig = *this;
    CorElementType typ = ELEMENT_TYPE_END;
    IfFailThrowBF(psig.GetElemType(&typ), BFA_BAD_SIGNATURE, pModule);

1080
    if ((typ < ELEMENT_TYPE_MAX) &&
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
        (CorTypeInfo::IsPrimitiveType_NoThrow(typ) || (typ == ELEMENT_TYPE_STRING) || (typ == ELEMENT_TYPE_OBJECT)))
    {
        // case ELEMENT_TYPE_VOID     = 0x01,
        // case ELEMENT_TYPE_BOOLEAN  = 0x02,
        // case ELEMENT_TYPE_CHAR     = 0x03,
        // case ELEMENT_TYPE_I1       = 0x04,
        // case ELEMENT_TYPE_U1       = 0x05,
        // case ELEMENT_TYPE_I2       = 0x06,
        // case ELEMENT_TYPE_U2       = 0x07,
        // case ELEMENT_TYPE_I4       = 0x08,
        // case ELEMENT_TYPE_U4       = 0x09,
        // case ELEMENT_TYPE_I8       = 0x0a,
        // case ELEMENT_TYPE_U8       = 0x0b,
        // case ELEMENT_TYPE_R4       = 0x0c,
        // case ELEMENT_TYPE_R8       = 0x0d,
        // case ELEMENT_TYPE_I        = 0x18,
        // case ELEMENT_TYPE_U        = 0x19,
1098
        //
1099
        // case ELEMENT_TYPE_STRING   = 0x0e,
1100 1101
        // case ELEMENT_TYPE_OBJECT   = 0x1c,
        //
1102
        thRet = TypeHandle(CoreLibBinder::GetElementType(typ));
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
    }
    else
    {
#ifdef _DEBUG_IMPL
        // This verifies that we won't try and load a type
        // if FORBIDGC_LOADER_USE_ENABLED is true.
        //
        // The FORBIDGC_LOADER_USE is limited to very specific scenarios that need to retrieve
        // GC_OTHER typehandles for size and gcroot information. This assert attempts to prevent
        // this abuse from proliferating.
        //
        if (FORBIDGC_LOADER_USE_ENABLED() && (fLoadTypes == ClassLoader::LoadTypes))
        {
            TypeHandle th = GetTypeHandleThrowing(pModule,
                                                  pTypeContext,
                                                  ClassLoader::DontLoadTypes,
                                                  level,
                                                  dropGenericArgumentLevel,
                                                  pSubst,
                                                  pZapSigContext);
            _ASSERTE(!th.IsNull());
        }
#endif
        //
        // pOrigModule is the original module that contained this ZapSig
1128
        //
1129
        ModuleBase * pOrigModule = (pZapSigContext != NULL) ? pZapSigContext->pInfoModule : pModule;
D
Dong-Heon Jung 已提交
1130

1131 1132 1133
        ClassLoader::NotFoundAction  notFoundAction;
        CorInternalStates            tdTypes;

J
Jan Vorlicek 已提交
1134
        switch((DWORD)typ) {
1135 1136 1137 1138 1139 1140 1141 1142 1143
        case ELEMENT_TYPE_TYPEDBYREF:
        {
            thRet = TypeHandle(g_TypedReferenceMT);
            break;
        }

        case ELEMENT_TYPE_NATIVE_VALUETYPE_ZAPSIG:
        {
#ifndef DACCESS_COMPILE
1144 1145 1146
            TypeHandle baseType = psig.GetTypeHandleThrowing(pModule,
                                                             pTypeContext,
                                                             fLoadTypes,
1147 1148
                                                             level,
                                                             dropGenericArgumentLevel,
1149 1150
                                                             pSubst,
                                                             pZapSigContext);
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169
            if (baseType.IsNull())
            {
                thRet = baseType;
            }
            else
            {
                thRet = ClassLoader::LoadNativeValueTypeThrowing(baseType, fLoadTypes, level);
            }
#else
            DacNotImpl();
            thRet = TypeHandle();
#endif
            break;
        }

        case ELEMENT_TYPE_CANON_ZAPSIG:
        {
#ifndef DACCESS_COMPILE
            assert(g_pCanonMethodTableClass != NULL);
1170
            thRet = TypeHandle(g_pCanonMethodTableClass);
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
#else
            DacNotImpl();
            thRet = TypeHandle();
#endif
            break;
        }

        case ELEMENT_TYPE_MODULE_ZAPSIG:
        {
#ifndef DACCESS_COMPILE
1181
            uint32_t ix;
1182
            IfFailThrowBF(psig.GetData(&ix), BFA_BAD_SIGNATURE, pModule);
D
Dong-Heon Jung 已提交
1183 1184 1185 1186 1187 1188 1189 1190 1191 1192
#ifdef FEATURE_MULTICOREJIT
            if (pZapSigContext->externalTokens == ZapSig::MulticoreJitTokens)
            {
                pModule = MulticoreJitManager::DecodeModuleFromIndex(pZapSigContext->pModuleContext, ix);
            }
            else
#endif
            {
                pModule = pZapSigContext->GetZapSigModule()->GetModuleFromIndex(ix);
            }
1193

1194
            if (pModule != NULL)
1195
            {
1196 1197 1198
                thRet = psig.GetTypeHandleThrowing(pModule,
                                                   pTypeContext,
                                                   fLoadTypes,
1199 1200
                                                   level,
                                                   dropGenericArgumentLevel,
1201
                                                   pSubst,
1202 1203
                                                   pZapSigContext);
            }
1204 1205 1206 1207 1208 1209
            else
            {
                // For ReadyToRunCompilation we return a null TypeHandle when we reference a non-local module
                //
                thRet = TypeHandle();
            }
1210 1211 1212 1213 1214 1215 1216 1217 1218 1219
#else
            DacNotImpl();
            thRet = TypeHandle();
#endif
            break;
        }

        case ELEMENT_TYPE_VAR_ZAPSIG:
        {
#ifndef DACCESS_COMPILE
1220
            RID rid;
1221 1222 1223 1224
            IfFailThrowBF(psig.GetData(&rid), BFA_BAD_SIGNATURE, pModule);

            mdGenericParam tkTyPar = TokenFromRid(rid, mdtGenericParam);

1225 1226 1227 1228 1229 1230
            if (!pModule->IsFullModule())
                THROW_BAD_FORMAT(BFA_BAD_COMPLUS_SIG, pOrigModule);

            Module *pNormalModule = static_cast<Module*>(pModule);

            TypeVarTypeDesc *pTypeVarTypeDesc = pNormalModule->LookupGenericParam(tkTyPar);
1231 1232 1233
            if (pTypeVarTypeDesc == NULL && (fLoadTypes == ClassLoader::LoadTypes))
            {
                mdToken tkOwner;
1234
                IfFailThrow(pNormalModule->GetMDImport()->GetGenericParamProps(tkTyPar, NULL, NULL, &tkOwner, NULL, NULL));
1235 1236 1237

                if (TypeFromToken(tkOwner) == mdtMethodDef)
                {
1238
                    MemberLoader::GetMethodDescFromMethodDef(pNormalModule, tkOwner, FALSE);
1239 1240 1241
                }
                else
                {
1242
                    ClassLoader::LoadTypeDefThrowing(pNormalModule, tkOwner,
1243 1244 1245 1246
                        ClassLoader::ThrowIfNotFound,
                        ClassLoader::PermitUninstDefOrRef);
                }

1247
                pTypeVarTypeDesc = pNormalModule->LookupGenericParam(tkTyPar);
1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267
                if (pTypeVarTypeDesc == NULL)
                {
                    THROW_BAD_FORMAT(BFA_BAD_COMPLUS_SIG, pOrigModule);
                }
            }
            thRet = TypeHandle(pTypeVarTypeDesc);
#else
            DacNotImpl();
            thRet = TypeHandle();
#endif
            break;
        }

        case ELEMENT_TYPE_VAR:
        {
            if ((pSubst != NULL) && !pSubst->GetInst().IsNull())
            {
#ifdef _DEBUG_IMPL
                _ASSERTE(!FORBIDGC_LOADER_USE_ENABLED());
#endif
1268
                uint32_t index;
1269 1270 1271
                IfFailThrow(psig.GetData(&index));

                SigPointer inst = pSubst->GetInst();
1272
                for (uint32_t i = 0; i < index; i++)
1273 1274 1275 1276 1277
                {
                    IfFailThrowBF(inst.SkipExactlyOne(), BFA_BAD_SIGNATURE, pOrigModule);
                }

                thRet =  inst.GetTypeHandleThrowing(
1278 1279 1280 1281 1282 1283
                    pSubst->GetModule(),
                    pTypeContext,
                    fLoadTypes,
                    level,
                    dropGenericArgumentLevel,
                    pSubst->GetNext(),
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
                    pZapSigContext);
            }
            else
            {
                thRet = (psig.GetTypeVariableThrowing(pModule, typ, fLoadTypes, pTypeContext));
                if (fLoadTypes == ClassLoader::LoadTypes)
                    ClassLoader::EnsureLoaded(thRet, level);
            }
            break;
        }

        case ELEMENT_TYPE_MVAR:
        {
            thRet = (psig.GetTypeVariableThrowing(pModule, typ, fLoadTypes, pTypeContext));
            if (fLoadTypes == ClassLoader::LoadTypes)
                ClassLoader::EnsureLoaded(thRet, level);
            break;
        }

        case ELEMENT_TYPE_GENERICINST:
        {
            mdTypeDef tkGenericType = mdTypeDefNil;
            Module *pGenericTypeModule = NULL;

            // Before parsing the generic instantiation, determine if the signature tells us its module and token.
            // This is the common case, and when true we can avoid dereferencing the resulting TypeHandle to ask for them.
            bool typeAndModuleKnown = false;
            if (pZapSigContext && pZapSigContext->externalTokens == ZapSig::NormalTokens && psig.IsTypeDef(&tkGenericType))
            {
                typeAndModuleKnown = true;
1314
                pGenericTypeModule = static_cast<Module*>(pModule);
1315 1316
            }

1317
            TypeHandle genericType = psig.GetGenericInstType(pModule, fLoadTypes, level < CLASS_LOAD_APPROXPARENTS ? level : CLASS_LOAD_APPROXPARENTS, pZapSigContext);
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

            if (genericType.IsNull())
            {
                thRet = genericType;
                break;
            }

            if (!typeAndModuleKnown)
            {
                tkGenericType = genericType.GetCl();
                pGenericTypeModule = genericType.GetModule();
            }
            else
            {
                _ASSERTE(tkGenericType == genericType.GetCl());
                _ASSERTE(pGenericTypeModule == genericType.GetModule());
            }

            if (level == CLASS_LOAD_APPROXPARENTS && dropGenericArgumentLevel && genericType.IsInterface())
            {
                thRet = genericType;
                break;
            }

            // The number of type parameters follows
1343
            uint32_t ntypars = 0;
1344 1345 1346 1347 1348 1349 1350 1351
            IfFailThrowBF(psig.GetData(&ntypars), BFA_BAD_SIGNATURE, pOrigModule);

            DWORD dwAllocaSize = 0;
            if (!ClrSafeInt<DWORD>::multiply(ntypars, sizeof(TypeHandle), dwAllocaSize))
                ThrowHR(COR_E_OVERFLOW);

            TypeHandle *thisinst = (TypeHandle*) _alloca(dwAllocaSize);

1352 1353
            bool handlingRecursiveGenericFieldScenario = false;
            SigPointer     psigCopy = psig;
1354

1355 1356 1357 1358 1359 1360
            // For the recursive field handling system, we instantiate over __Canon first, then over Byte and if the
            // types end up with the same GC layout, we can use the __Canon variant to replace instantiations over the specified type
            for (int iRecursiveGenericFieldHandlingPass = 0; handlingRecursiveGenericFieldScenario || iRecursiveGenericFieldHandlingPass == 0 ; iRecursiveGenericFieldHandlingPass++)
            {
                // Finally we gather up the type arguments themselves, loading at the level specified for generic arguments
                for (unsigned i = 0; i < ntypars; i++)
1361
                {
1362 1363 1364
                    ClassLoadLevel argLevel = level;
                    TypeHandle typeHnd = TypeHandle();
                    BOOL argDrop = FALSE;
1365

1366 1367 1368
                    if (dropGenericArgumentLevel)
                    {
                        if (level == CLASS_LOAD_APPROXPARENTS)
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
                            SigPointer tempsig = psig;
                            bool checkTokenForRecursion = false;

                            CorElementType elemType = ELEMENT_TYPE_END;
                            IfFailThrowBF(tempsig.GetElemType(&elemType), BFA_BAD_SIGNATURE, pOrigModule);

                            if (elemType == (CorElementType) ELEMENT_TYPE_MODULE_ZAPSIG)
                            {
                                // Skip over the module index
                                IfFailThrowBF(tempsig.GetData(NULL), BFA_BAD_SIGNATURE, pModule);
                                // Read the next elemType
                                IfFailThrowBF(tempsig.GetElemType(&elemType), BFA_BAD_SIGNATURE, pModule);
                            }

                            if (elemType == ELEMENT_TYPE_GENERICINST)
                            {
                                CorElementType tmpEType = ELEMENT_TYPE_END;
                                IfFailThrowBF(tempsig.GetElemType(&tmpEType), BFA_BAD_SIGNATURE, pOrigModule);

                                if (tmpEType == ELEMENT_TYPE_CLASS)
                                    typeHnd = TypeHandle(g_pCanonMethodTableClass);
                                else if ((pRecursiveFieldGenericHandling != NULL) && (tmpEType == ELEMENT_TYPE_VALUETYPE))
                                    checkTokenForRecursion = true;
                            }
                            else if ((elemType == (CorElementType)ELEMENT_TYPE_CANON_ZAPSIG) ||
                                    (CorTypeInfo::GetGCType_NoThrow(elemType) == TYPE_GC_REF))
                            {
1397
                                typeHnd = TypeHandle(g_pCanonMethodTableClass);
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
                            }
                            else if ((elemType == ELEMENT_TYPE_VALUETYPE) && (pRecursiveFieldGenericHandling != NULL))
                            {
                                checkTokenForRecursion = true;
                            }

                            if (checkTokenForRecursion)
                            {
                                mdToken valueTypeToken = mdTypeDefNil;
                                IfFailThrowBF(tempsig.GetToken(&valueTypeToken), BFA_BAD_SIGNATURE, pOrigModule);
                                if (valueTypeToken == pRecursiveFieldGenericHandling->tkTypeDefToAvoidIfPossible && pOrigModule == pRecursiveFieldGenericHandling->pModuleWithTokenToAvoidIfPossible)
                                {
                                    bool exactSelfRecursionDetected = true;

                                    if (elemType == ELEMENT_TYPE_GENERICINST)
                                    {
                                        // Check to ensure that the type variables in use are for an exact self-referential generic.
                                        // Other cases are possible, but this logic is scoped to exactly self-referential generics.
                                        uint32_t instantiationCount;
                                        IfFailThrowBF(tempsig.GetData(&instantiationCount), BFA_BAD_SIGNATURE, pModule);
                                        for (uint32_t iInstantiation = 0; iInstantiation < instantiationCount; iInstantiation++)
                                        {
                                            IfFailThrowBF(tempsig.GetElemType(&elemType), BFA_BAD_SIGNATURE, pOrigModule);
                                            if (elemType != ELEMENT_TYPE_VAR)
                                            {
                                                exactSelfRecursionDetected = false;
                                                break;
                                            }

                                            uint32_t varIndex;
                                            IfFailThrowBF(tempsig.GetData(&varIndex), BFA_BAD_SIGNATURE, pModule);
                                            if (varIndex != iInstantiation)
                                            {
                                                exactSelfRecursionDetected = false;
                                                break;
                                            }
                                        }
                                    }
                                    if (exactSelfRecursionDetected)
                                    {
                                        handlingRecursiveGenericFieldScenario = true;
                                        if (iRecursiveGenericFieldHandlingPass == 0)
                                        {
                                            typeHnd = TypeHandle(g_pCanonMethodTableClass);
                                        }
                                        else
                                        {
                                            typeHnd = TypeHandle(CoreLibBinder::GetClass(CLASS__BYTE));
                                        }
                                    }
                                }
                            }
                            argDrop = TRUE;
1451
                        }
1452 1453 1454 1455 1456
                        else
                        // We need to make sure that typekey is always restored. Otherwise, we may run into unrestored typehandles while using
                        // the typekey for lookups. It is safe to not drop the levels for initial NGen-specific loading levels since there cannot
                        // be cycles in typekeys.
                        if (level > CLASS_LOAD_APPROXPARENTS)
1457
                        {
1458
                            argLevel = (ClassLoadLevel) (level-1);
1459 1460
                        }
                    }
1461 1462

                    if (typeHnd.IsNull())
1463
                    {
1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483
                        typeHnd = psig.GetTypeHandleThrowing(pOrigModule,
                                                            pTypeContext,
                                                            fLoadTypes,
                                                            argLevel,
                                                            argDrop,
                                                            pSubst,
                                                            pZapSigContext, 
                                                            NULL,
                                                            pRecursiveFieldGenericHandling);
                        if (typeHnd.IsNull())
                        {
                            // Indicate failure by setting thisinst to NULL
                            thisinst = NULL;
                            break;
                        }

                        if (dropGenericArgumentLevel && level == CLASS_LOAD_APPROXPARENTS)
                        {
                            typeHnd = ClassLoader::CanonicalizeGenericArg(typeHnd);
                        }
1484
                    }
1485 1486
                    thisinst[i] = typeHnd;
                    IfFailThrowBF(psig.SkipExactlyOne(), BFA_BAD_SIGNATURE, pOrigModule);
1487 1488
                }

1489 1490
                // If we failed to get all of the instantiation type arguments then we return the null type handle
                if (thisinst == NULL)
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
                    thRet = TypeHandle();
                    break;
                }

                Instantiation genericLoadInst(thisinst, ntypars);

                if (pMTInterfaceMapOwner != NULL && genericLoadInst.ContainsAllOneType(pMTInterfaceMapOwner))
                {
                    thRet = ClassLoader::LoadTypeDefThrowing(pGenericTypeModule, tkGenericType, ClassLoader::ThrowIfNotFound, ClassLoader::PermitUninstDefOrRef, 0, level);
                }
                else
                {
                    // Group together the current signature type context and substitution chain, which
                    // we may later use to instantiate constraints of type arguments that turn out to be
                    // typespecs, i.e. generic types.
                    InstantiationContext instContext(pTypeContext, pSubst);

                    // Now make the instantiated type
                    // The class loader will check the arity
                    // When we know it was correctly computed at NGen time, we ask the class loader to skip that check.
                    TypeHandle thFound = (ClassLoader::LoadGenericInstantiationThrowing(pGenericTypeModule,
                                                                        tkGenericType,
                                                                        genericLoadInst,
                                                                        fLoadTypes, level,
                                                                        &instContext,
                                                                        pZapSigContext && pZapSigContext->externalTokens == ZapSig::NormalTokens));

                    if (!handlingRecursiveGenericFieldScenario)
1520
                    {
1521
                        thRet = thFound;
1522 1523
                        break;
                    }
1524
                    else
1525
                    {
1526 1527 1528 1529 1530 1531
                        if (iRecursiveGenericFieldHandlingPass == 0)
                        {
                            // This is the instantiation over __Canon if we succeed with finding out if the recursion does not affect type layout, we will return this type.
                            thRet = thFound;
                            // Restart with the same sig as we had for the first pass
                            psig = psigCopy;
1532

1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554
                        }
                        else
                        {
                            // At this point thFound is the instantiation over Byte and thRet is set to the instantiation over __Canon.
                            // If the two have the same GC layout, then the field layout is not affected by the type parameters, and the type load can continue 
                            // with just using the __Canon variant.
                            // To simplify the calculation, all we really need to compute is the number of GC pointers in the representation and the Base size.
                            // For if the type parameter is used in field layout, there will be at least 1 more pointer in the __Canon instantiation as compared to the Byte instantiation.

                            SIZE_T objectSizeCanonInstantiation = thRet.AsMethodTable()->GetBaseSize();
                            SIZE_T objectSizeByteInstantion = thFound.AsMethodTable()->GetBaseSize();

                            bool failedLayoutCompare = objectSizeCanonInstantiation != objectSizeByteInstantion;
                            if (!failedLayoutCompare)
                            {
#ifndef DACCESS_COMPILE
                                failedLayoutCompare = CGCDesc::GetNumPointers(thRet.AsMethodTable(), objectSizeCanonInstantiation, 0) !=
                                                      CGCDesc::GetNumPointers(thFound.AsMethodTable(), objectSizeCanonInstantiation, 0);
#else  
                                DacNotImpl();
#endif
                            }
1555

1556 1557 1558 1559 1560 1561 1562 1563
                            if (failedLayoutCompare)
                            {
#ifndef DACCESS_COMPILE
                                static_cast<Module*>(pOrigModule)->ThrowTypeLoadException(pOrigModule->GetMDImport(), pRecursiveFieldGenericHandling->tkTypeDefToAvoidIfPossible, IDS_INVALID_RECURSIVE_GENERIC_FIELD_LOAD);
#else  
                                DacNotImpl();
#endif
                            }
1564

1565 1566 1567 1568 1569
                            // Runtime successfully found a type with the desired layout, return
                            break;
                        }
                    }
                }
1570
            }
1571
            break;
1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583
        }

        case ELEMENT_TYPE_CLASS:
            // intentional fallthru to ELEMENT_TYPE_VALUETYPE
        case ELEMENT_TYPE_VALUETYPE:
        {
            mdTypeRef typeToken = 0;

            IfFailThrowBF(psig.GetToken(&typeToken), BFA_BAD_SIGNATURE, pOrigModule);

            if ((TypeFromToken(typeToken) != mdtTypeRef) && (TypeFromToken(typeToken) != mdtTypeDef))
                THROW_BAD_FORMAT(BFA_UNEXPECTED_TOKEN_AFTER_CLASSVALTYPE, pOrigModule);
1584

1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597
            if (IsNilToken(typeToken))
                THROW_BAD_FORMAT(BFA_UNEXPECTED_TOKEN_AFTER_CLASSVALTYPE, pOrigModule);

            if (fLoadTypes == ClassLoader::LoadTypes)
            {
                notFoundAction = ClassLoader::ThrowButNullV11McppWorkaround;
                tdTypes = tdNoTypes;
            }
            else
            {
                notFoundAction = ClassLoader::ReturnNullIfNotFound;
                tdTypes = tdAllTypes;
            }
1598 1599 1600 1601

            TypeHandle loadedType =
                ClassLoader::LoadTypeDefOrRefThrowing(pModule,
                                                      typeToken,
1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615
                                                      notFoundAction,
                                                      // pZapSigContext is only set when decoding zapsigs
                                                      // ZapSigs use uninstantiated tokens to represent the GenericTypeDefinition
                                                      (pZapSigContext ? ClassLoader::PermitUninstDefOrRef : ClassLoader::FailIfUninstDefOrRef),
                                                      tdTypes,
                                                      level);

            // Everett C++ compiler can generate a TypeRef with RS=0 without respective TypeDef for unmanaged valuetypes,
            // referenced only by pointers to them. For this case we treat this as an ELEMENT_TYPE_VOID, and perform the
            // same operations as the appropriate case block above.
            if (loadedType.IsNull())
            {
                if (TypeFromToken(typeToken) == mdtTypeRef)
                {
1616 1617 1618
                    loadedType = TypeHandle(CoreLibBinder::GetElementType(ELEMENT_TYPE_VOID));
                    thRet = loadedType;
                    break;
1619 1620 1621 1622 1623 1624 1625
                }
            }

#ifndef DACCESS_COMPILE
            //
            // Check that the type that we loaded matches the signature
            //   with regards to ET_CLASS and ET_VALUETYPE
1626
            //
J
Jan Vorlicek 已提交
1627
            if (fLoadTypes == ClassLoader::LoadTypes)
1628
            {
1629 1630
                // Skip this check when using zap sigs; it should have been correctly computed at NGen time
                // and a change from one to the other would have invalidated the image.
1631 1632 1633 1634
                if (pZapSigContext == NULL || pZapSigContext->externalTokens != ZapSig::NormalTokens)
                {
                    bool typFromSigIsClass = (typ == ELEMENT_TYPE_CLASS);
                    bool typLoadedIsClass  = (loadedType.GetSignatureCorElementType() == ELEMENT_TYPE_CLASS);
1635

1636 1637
                    if (typFromSigIsClass != typLoadedIsClass)
                    {
1638
                        if (pModule->GetMDImport()->GetMetadataStreamVersion() != MD_STREAM_VER_1X)
1639
                        {
1640 1641 1642
                            pOrigModule->ThrowTypeLoadException(pModule->GetMDImport(),
                                                                typeToken,
                                                                BFA_CLASSLOAD_VALUETYPEMISMATCH);
1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660
                        }
                    }
                }

                // Assert that our reasoning above was valid (that there is never a zapsig that gets this wrong)
                _ASSERTE(((typ == ELEMENT_TYPE_CLASS) == (loadedType.GetSignatureCorElementType() == ELEMENT_TYPE_CLASS)) ||
                          pZapSigContext == NULL || pZapSigContext->externalTokens != ZapSig::NormalTokens);

            }
#endif // #ifndef DACCESS_COMPILE

            thRet = loadedType;
            break;
        }

        case ELEMENT_TYPE_ARRAY:
        case ELEMENT_TYPE_SZARRAY:
        {
1661 1662 1663
            TypeHandle elemType = psig.GetTypeHandleThrowing(pModule,
                                                             pTypeContext,
                                                             fLoadTypes,
1664 1665
                                                             level,
                                                             dropGenericArgumentLevel,
1666
                                                             pSubst,
1667 1668 1669
                                                             pZapSigContext);
            if (elemType.IsNull())
            {
1670 1671
                thRet = elemType;
                break;
1672 1673
            }

1674
            uint32_t rank = 0;
1675 1676 1677 1678 1679 1680 1681
            if (typ == ELEMENT_TYPE_ARRAY) {
                IfFailThrowBF(psig.SkipExactlyOne(), BFA_BAD_SIGNATURE, pOrigModule);
                IfFailThrowBF(psig.GetData(&rank), BFA_BAD_SIGNATURE, pOrigModule);

                _ASSERTE(0 < rank);
            }
            thRet = ClassLoader::LoadArrayTypeThrowing(elemType, typ, rank, fLoadTypes, level);
1682
            break;
1683 1684 1685 1686
        }

        case ELEMENT_TYPE_PINNED:
            // Return what follows
1687 1688 1689
            thRet = psig.GetTypeHandleThrowing(pModule,
                                               pTypeContext,
                                               fLoadTypes,
1690 1691
                                               level,
                                               dropGenericArgumentLevel,
1692
                                               pSubst,
1693
                                               pZapSigContext);
1694
            break;
1695 1696 1697 1698

        case ELEMENT_TYPE_BYREF:
        case ELEMENT_TYPE_PTR:
        {
1699 1700 1701
            TypeHandle baseType = psig.GetTypeHandleThrowing(pModule,
                                                             pTypeContext,
                                                             fLoadTypes,
1702 1703
                                                             level,
                                                             dropGenericArgumentLevel,
1704 1705
                                                             pSubst,
                                                             pZapSigContext);
1706 1707 1708 1709 1710 1711
            if (baseType.IsNull())
            {
                thRet = baseType;
            }
            else
            {
1712
                thRet = ClassLoader::LoadPointerOrByrefTypeThrowing(typ, baseType, fLoadTypes, level);
1713
            }
1714
            break;
1715 1716 1717
        }

        case ELEMENT_TYPE_FNPTR:
1718
        {
1719
#ifndef DACCESS_COMPILE
1720 1721
            uint32_t uCallConv = 0;
            IfFailThrowBF(psig.GetData(&uCallConv), BFA_BAD_SIGNATURE, pOrigModule);
1722

1723 1724
            if ((uCallConv & IMAGE_CEE_CS_CALLCONV_MASK) == IMAGE_CEE_CS_CALLCONV_FIELD)
                THROW_BAD_FORMAT(BFA_FNPTR_CANNOT_BE_A_FIELD, pOrigModule);
1725

1726 1727
            if ((uCallConv & IMAGE_CEE_CS_CALLCONV_GENERIC) > 0)
                THROW_BAD_FORMAT(BFA_FNPTR_CANNOT_BE_GENERIC, pOrigModule);
1728

1729 1730 1731
            // Get the arg count.
            uint32_t cArgs = 0;
            IfFailThrowBF(psig.GetData(&cArgs), BFA_BAD_SIGNATURE, pOrigModule);
1732

1733 1734 1735 1736 1737 1738
            uint32_t cAllocaSize;
            if (!ClrSafeInt<uint32_t>::addition(cArgs, 1, cAllocaSize) ||
                !ClrSafeInt<uint32_t>::multiply(cAllocaSize, sizeof(TypeHandle), cAllocaSize))
            {
                ThrowHR(COR_E_OVERFLOW);
            }
1739

1740 1741
            TypeHandle *retAndArgTypes = (TypeHandle*) _alloca(cAllocaSize);
            bool fReturnTypeOrParameterNotLoaded = false;
1742

1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754
            for (unsigned i = 0; i <= cArgs; i++)
            {
                // Lookup type handle.
                retAndArgTypes[i] = psig.GetTypeHandleThrowing(pOrigModule,
                                                               pTypeContext,
                                                               fLoadTypes,
                                                               level,
                                                               dropGenericArgumentLevel,
                                                               pSubst,
                                                               pZapSigContext);

                if (retAndArgTypes[i].IsNull())
1755
                {
1756 1757
                    thRet = TypeHandle();
                    fReturnTypeOrParameterNotLoaded = true;
1758 1759 1760
                    break;
                }

1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783
                IfFailThrowBF(psig.SkipExactlyOne(), BFA_BAD_SIGNATURE, pOrigModule);
            }

            if (fReturnTypeOrParameterNotLoaded)
            {
                break;
            }

            // Only have an unmanaged\managed status, and not the unmanaged CALLCONV_ value.
            switch (uCallConv & IMAGE_CEE_CS_CALLCONV_MASK)
            {
                case IMAGE_CEE_CS_CALLCONV_C:
                case IMAGE_CEE_CS_CALLCONV_STDCALL:
                case IMAGE_CEE_CS_CALLCONV_THISCALL:
                case IMAGE_CEE_CS_CALLCONV_FASTCALL:
                    // Strip the calling convention.
                    uCallConv &= ~IMAGE_CEE_CS_CALLCONV_MASK;
                    // Normalize to unmanaged.
                    uCallConv |= IMAGE_CEE_CS_CALLCONV_UNMANAGED;
            }

            // Find an existing function pointer or make a new one
            thRet = ClassLoader::LoadFnptrTypeThrowing((BYTE) uCallConv, cArgs, retAndArgTypes, fLoadTypes, level);                
1784
#else
1785 1786
            // Function pointers are interpreted as IntPtr to the debugger.
            thRet = TypeHandle(CoreLibBinder::GetElementType(ELEMENT_TYPE_I));
1787 1788
#endif
            break;
1789
        }
1790 1791 1792 1793 1794 1795 1796 1797

        case ELEMENT_TYPE_INTERNAL :
            {
                TypeHandle hType;
                // this check is not functional in DAC and provides no security against a malicious dump
                // the DAC is prepared to receive an invalid type handle
#ifndef DACCESS_COMPILE
                if (pModule->IsSigInIL(m_ptr))
1798
                    THROW_BAD_FORMAT(BFA_BAD_SIGNATURE, pModule);
1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811
#endif
                CorSigUncompressPointer(psig.GetPtr(), (void**)&hType);
                thRet = hType;
                break;
            }

        case ELEMENT_TYPE_SENTINEL:
            {
#ifndef DACCESS_COMPILE

                mdToken token = 0;

                IfFailThrowBF(psig.GetToken(&token), BFA_BAD_SIGNATURE, pOrigModule);
1812

1813 1814 1815
                pOrigModule->ThrowTypeLoadException(pModule->GetMDImport(),
                                                    token,
                                                    IDS_CLASSLOAD_GENERAL);
1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829
#else
                DacNotImpl();
                break;
#endif // #ifndef DACCESS_COMPILE
            }

            default:
#ifdef _DEBUG_IMPL
                _ASSERTE(!FORBIDGC_LOADER_USE_ENABLED());
#endif
                THROW_BAD_FORMAT(BFA_BAD_COMPLUS_SIG, pOrigModule);
    }

    }
1830

1831 1832 1833 1834 1835 1836
    RETURN thRet;
}
#ifdef _PREFAST_
#pragma warning(pop)
#endif

1837
TypeHandle SigPointer::GetGenericInstType(ModuleBase *        pModule,
1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853
                                    ClassLoader::LoadTypesFlag  fLoadTypes/*=LoadTypes*/,
                                    ClassLoadLevel              level/*=CLASS_LOADED*/,
                                    const ZapSig::Context *     pZapSigContext)
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        if (FORBIDGC_LOADER_USE_ENABLED()) NOTHROW; else THROWS;
        MODE_ANY;
        if (FORBIDGC_LOADER_USE_ENABLED()) GC_NOTRIGGER; else GC_TRIGGERS;
        if (FORBIDGC_LOADER_USE_ENABLED()) FORBID_FAULT; else { INJECT_FAULT(return TypeHandle();); }
        if (FORBIDGC_LOADER_USE_ENABLED() || fLoadTypes != ClassLoader::LoadTypes) { LOADS_TYPE(CLASS_LOAD_BEGIN); } else { LOADS_TYPE(level); }
        SUPPORTS_DAC;
    }
    CONTRACTL_END

1854
    ModuleBase * pOrigModule   = (pZapSigContext != NULL) ? pZapSigContext->pInfoModule : pModule;
1855 1856 1857 1858 1859

    CorElementType typ = ELEMENT_TYPE_END;
    IfFailThrowBF(GetElemType(&typ), BFA_BAD_SIGNATURE, pOrigModule);

    TypeHandle genericType;
1860 1861

    if (typ == ELEMENT_TYPE_INTERNAL)
1862 1863 1864 1865 1866
    {
        // this check is not functional in DAC and provides no security against a malicious dump
        // the DAC is prepared to receive an invalid type handle
#ifndef DACCESS_COMPILE
        if (pModule->IsSigInIL(m_ptr))
1867
            THROW_BAD_FORMAT(BFA_BAD_SIGNATURE, pModule);
1868 1869 1870 1871
#endif

        IfFailThrow(GetPointer((void**)&genericType));
    }
1872
    else
1873 1874 1875 1876 1877 1878
    {
        mdToken typeToken = mdTypeRefNil;
        IfFailThrowBF(GetToken(&typeToken), BFA_BAD_SIGNATURE, pOrigModule);

        if ((TypeFromToken(typeToken) != mdtTypeRef) && (TypeFromToken(typeToken) != mdtTypeDef))
            THROW_BAD_FORMAT(BFA_UNEXPECTED_TOKEN_AFTER_GENINST, pOrigModule);
1879

1880 1881
        if (IsNilToken(typeToken))
            THROW_BAD_FORMAT(BFA_UNEXPECTED_TOKEN_AFTER_GENINST, pOrigModule);
1882

1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897
        ClassLoader::NotFoundAction  notFoundAction;
        CorInternalStates            tdTypes;

        if (fLoadTypes == ClassLoader::LoadTypes)
        {
            notFoundAction = ClassLoader::ThrowIfNotFound;
            tdTypes = tdNoTypes;
        }
        else
        {
            notFoundAction = ClassLoader::ReturnNullIfNotFound;
            tdTypes = tdAllTypes;
        }

        genericType = ClassLoader::LoadTypeDefOrRefThrowing(pModule,
1898
                                                            typeToken,
1899 1900 1901 1902 1903
                                                            notFoundAction,
                                                            ClassLoader::PermitUninstDefOrRef,
                                                            tdTypes,
                                                            level);

1904
        if (genericType.IsNull())
1905 1906 1907 1908 1909
        {
            return genericType;
        }

#ifndef DACCESS_COMPILE
J
Jan Vorlicek 已提交
1910
        if (fLoadTypes == ClassLoader::LoadTypes)
1911
        {
1912
            // Skip this check when using zap sigs; it should have been correctly computed at NGen time
1913 1914 1915 1916 1917
            // and a change from one to the other would have invalidated the image.  Leave in the code for debug so we can assert below.
            if (pZapSigContext == NULL || pZapSigContext->externalTokens != ZapSig::NormalTokens)
            {
                bool typFromSigIsClass = (typ == ELEMENT_TYPE_CLASS);
                bool typLoadedIsClass  = (genericType.GetSignatureCorElementType() == ELEMENT_TYPE_CLASS);
1918

1919
                if (typFromSigIsClass != typLoadedIsClass)
1920
                {
1921 1922 1923
                    pOrigModule->ThrowTypeLoadException(pModule->GetMDImport(),
                                                        typeToken,
                                                        BFA_CLASSLOAD_VALUETYPEMISMATCH);
1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937
                }
            }

            // Assert that our reasoning above was valid (that there is never a zapsig that gets this wrong)
            _ASSERTE(((typ == ELEMENT_TYPE_CLASS) == (genericType.GetSignatureCorElementType() == ELEMENT_TYPE_CLASS)) ||
                      pZapSigContext == NULL || pZapSigContext->externalTokens != ZapSig::NormalTokens);
        }
#endif // #ifndef DACCESS_COMPILE
    }

    return genericType;
}

// SigPointer should be just after E_T_VAR or E_T_MVAR
1938
TypeHandle SigPointer::GetTypeVariableThrowing(ModuleBase *pModule, // unused - may be used later for better error reporting
1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985
                                               CorElementType et,
                                               ClassLoader::LoadTypesFlag fLoadTypes/*=LoadTypes*/,
                                               const SigTypeContext *pTypeContext)
{
    CONTRACT(TypeHandle)
    {
        INSTANCE_CHECK;
        PRECONDITION(CorTypeInfo::IsGenericVariable_NoThrow(et));
        if (FORBIDGC_LOADER_USE_ENABLED()) NOTHROW; else THROWS;
        MODE_ANY;
        if (FORBIDGC_LOADER_USE_ENABLED()) GC_NOTRIGGER; else GC_TRIGGERS;
        if (FORBIDGC_LOADER_USE_ENABLED()) FORBID_FAULT; else { INJECT_FAULT(COMPlusThrowOM()); }
        POSTCONDITION(CheckPointer(RETVAL, ((fLoadTypes == ClassLoader::LoadTypes) ? NULL_NOT_OK : NULL_OK)));
        SUPPORTS_DAC;
    }
    CONTRACT_END

    TypeHandle res = GetTypeVariable(et, pTypeContext);
#ifndef DACCESS_COMPILE
    if (res.IsNull() && (fLoadTypes == ClassLoader::LoadTypes))
    {
       COMPlusThrowHR(COR_E_BADIMAGEFORMAT);
    }
#endif
    RETURN(res);
}

// SigPointer should be just after E_T_VAR or E_T_MVAR
TypeHandle SigPointer::GetTypeVariable(CorElementType et,
                                       const SigTypeContext *pTypeContext)
{

    CONTRACT(TypeHandle)
    {
        INSTANCE_CHECK;
        PRECONDITION(CorTypeInfo::IsGenericVariable_NoThrow(et));
        NOTHROW;
        GC_NOTRIGGER;
        POSTCONDITION(CheckPointer(RETVAL, NULL_OK)); // will return TypeHandle() if index is out of range
        SUPPORTS_DAC;
#ifndef DACCESS_COMPILE
        //        POSTCONDITION(RETVAL.IsNull() || RETVAL.IsRestored() || RETVAL.GetMethodTable()->IsRestoring());
#endif
        MODE_ANY;
    }
    CONTRACT_END

1986
    uint32_t index;
1987 1988 1989 1990 1991 1992
    if (FAILED(GetData(&index)))
    {
        TypeHandle thNull;
        RETURN(thNull);
    }

1993
    if (!pTypeContext
1994
        ||
1995
        (et == ELEMENT_TYPE_VAR &&
1996 1997
         (index >= pTypeContext->m_classInst.GetNumArgs()))
        ||
1998
        (et == ELEMENT_TYPE_MVAR &&
1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048
         (index >= pTypeContext->m_methodInst.GetNumArgs())))
    {
        LOG((LF_ALWAYS, LL_INFO1000, "GENERICS: Error: GetTypeVariable on out-of-range type variable\n"));
        BAD_FORMAT_NOTHROW_ASSERT(!"Invalid type context: either this is an ill-formed signature (e.g. an invalid type variable number) or you have not provided a non-empty SigTypeContext where one is required.  Check back on the callstack for where the value of pTypeContext is first provided, and see if it is acquired from the correct place.  For calls originating from a JIT it should be acquired from the context parameter, which indicates the method being compiled.  For calls from other locations it should be acquired from the MethodTable, EEClass, TypeHandle, FieldDesc or MethodDesc being analyzed.");
        TypeHandle thNull;
        RETURN(thNull);
    }
    if (et == ELEMENT_TYPE_VAR)
    {
        RETURN(pTypeContext->m_classInst[index]);
    }
    else
    {
        RETURN(pTypeContext->m_methodInst[index]);
    }
}


#ifndef DACCESS_COMPILE

BOOL SigPointer::IsStringType(Module* pModule, const SigTypeContext *pTypeContext) const
{
    WRAPPER_NO_CONTRACT;

    return IsStringTypeHelper(pModule, pTypeContext, FALSE);
}


BOOL SigPointer::IsStringTypeThrowing(Module* pModule, const SigTypeContext *pTypeContext) const
{
    WRAPPER_NO_CONTRACT;

    return IsStringTypeHelper(pModule, pTypeContext, TRUE);
}

BOOL SigPointer::IsStringTypeHelper(Module* pModule, const SigTypeContext* pTypeContext, BOOL fThrow) const
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        if (fThrow)
        {
            THROWS;
            GC_TRIGGERS;
        }
        else
        {
            NOTHROW;
            GC_NOTRIGGER;
        }
2049

2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068
        MODE_ANY;
        PRECONDITION(CheckPointer(pModule));
    }
    CONTRACTL_END

    IMDInternalImport *pInternalImport = pModule->GetMDImport();
    SigPointer psig = *this;
    CorElementType typ;
    if (FAILED(psig.GetElemType(&typ)))
    {
        if (fThrow)
        {
            ThrowHR(META_E_BAD_SIGNATURE);
        }
        else
        {
            return FALSE;
        }
    }
2069

2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091
    switch (typ)
    {
        case ELEMENT_TYPE_STRING :
            return TRUE;

        case ELEMENT_TYPE_CLASS :
        {
            LPCUTF8 pclsname;
            LPCUTF8 pszNamespace;
            mdToken token;

            if (FAILED( psig.GetToken(&token)))
            {
                if (fThrow)
                {
                    ThrowHR(META_E_BAD_SIGNATURE);
                }
                else
                {
                    return FALSE;
                }
            }
2092

2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121
            if (TypeFromToken(token) == mdtTypeDef)
            {
                if (FAILED(pInternalImport->GetNameOfTypeDef(token, &pclsname, &pszNamespace)))
                {
                    if (fThrow)
                    {
                        ThrowHR(COR_E_BADIMAGEFORMAT);
                    }
                    else
                    {
                        return FALSE;
                    }
                }
            }
            else
            {
                BAD_FORMAT_NOTHROW_ASSERT(TypeFromToken(token) == mdtTypeRef);
                if (FAILED(pInternalImport->GetNameOfTypeRef(token, &pszNamespace, &pclsname)))
                {
                    if (fThrow)
                    {
                        ThrowHR(COR_E_BADIMAGEFORMAT);
                    }
                    else
                    {
                        return FALSE;
                    }
                }
            }
2122

2123 2124
            if (strcmp(pclsname, g_StringName) != 0)
                return FALSE;
2125

2126 2127
            if (pszNamespace == NULL)
                return FALSE;
2128

2129 2130
            return (strcmp(pszNamespace, g_SystemNS) == 0);
        }
2131

2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144
        case ELEMENT_TYPE_VAR :
        case ELEMENT_TYPE_MVAR :
        {
            TypeHandle ty;

            if (fThrow)
            {
                ty = psig.GetTypeVariableThrowing(pModule, typ, ClassLoader::LoadTypes, pTypeContext);
            }
            else
            {
                ty = psig.GetTypeVariable(typ, pTypeContext);
            }
2145

2146 2147 2148
            TypeHandle th(g_pStringClass);
            return (ty == th);
        }
2149

2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182
        default:
            break;
    }
    return FALSE;
}


//------------------------------------------------------------------------
// Tests if the element class name is szClassName.
//------------------------------------------------------------------------
BOOL SigPointer::IsClass(Module* pModule, LPCUTF8 szClassName, const SigTypeContext *pTypeContext) const
{
    WRAPPER_NO_CONTRACT;

    return IsClassHelper(pModule, szClassName, pTypeContext, FALSE);
}


//------------------------------------------------------------------------
// Tests if the element class name is szClassName.
//------------------------------------------------------------------------
BOOL SigPointer::IsClassThrowing(Module* pModule, LPCUTF8 szClassName, const SigTypeContext *pTypeContext) const
{
    WRAPPER_NO_CONTRACT;

    return IsClassHelper(pModule, szClassName, pTypeContext, TRUE);
}

BOOL SigPointer::IsClassHelper(Module* pModule, LPCUTF8 szClassName, const SigTypeContext* pTypeContext, BOOL fThrow) const
{
    CONTRACTL
    {
        INSTANCE_CHECK;
2183

2184 2185 2186 2187 2188 2189 2190 2191 2192 2193
        if (fThrow)
        {
            THROWS;
            GC_TRIGGERS;
        }
        else
        {
            NOTHROW;
            GC_NOTRIGGER;
        }
2194

2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224
        MODE_ANY;
        PRECONDITION(CheckPointer(pModule));
        PRECONDITION(CheckPointer(szClassName));
    }
    CONTRACTL_END

    SigPointer psig = *this;
    CorElementType typ;
    if (FAILED(psig.GetElemType(&typ)))
    {
        if (fThrow)
            ThrowHR(META_E_BAD_SIGNATURE);
        else
            return FALSE;
    }

    BAD_FORMAT_NOTHROW_ASSERT((typ == ELEMENT_TYPE_VAR)      || (typ == ELEMENT_TYPE_MVAR)      ||
                              (typ == ELEMENT_TYPE_CLASS)    || (typ == ELEMENT_TYPE_VALUETYPE) ||
                              (typ == ELEMENT_TYPE_OBJECT)   || (typ == ELEMENT_TYPE_STRING)    ||
                              (typ == ELEMENT_TYPE_INTERNAL) || (typ == ELEMENT_TYPE_GENERICINST));


    if (typ == ELEMENT_TYPE_VAR || typ == ELEMENT_TYPE_MVAR)
    {
        TypeHandle ty;

        if (fThrow)
            ty = psig.GetTypeVariableThrowing(pModule, typ, ClassLoader::LoadTypes, pTypeContext);
        else
            ty = psig.GetTypeVariable(typ, pTypeContext);
2225

2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248
        return(!ty.IsNull() && IsTypeRefOrDef(szClassName, ty.GetModule(), ty.GetCl()));
    }
    else if ((typ == ELEMENT_TYPE_CLASS) || (typ == ELEMENT_TYPE_VALUETYPE))
    {
        mdTypeRef typeref;
        if (FAILED(psig.GetToken(&typeref)))
        {
            if (fThrow)
                ThrowHR(META_E_BAD_SIGNATURE);
            else
                return FALSE;
        }

        return( IsTypeRefOrDef(szClassName, pModule, typeref) );
    }
    else if (typ == ELEMENT_TYPE_OBJECT)
    {
        return( !strcmp(szClassName, g_ObjectClassName) );
    }
    else if (typ == ELEMENT_TYPE_STRING)
    {
        return( !strcmp(szClassName, g_StringClassName) );
    }
2249
    else if (typ == ELEMENT_TYPE_INTERNAL)
2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302
    {
        TypeHandle th;

        // this check is not functional in DAC and provides no security against a malicious dump
        // the DAC is prepared to receive an invalid type handle
#ifndef DACCESS_COMPILE
        if (pModule->IsSigInIL(m_ptr))
        {
            if (fThrow)
                ThrowHR(META_E_BAD_SIGNATURE);
            else
                return FALSE;
        }
#endif

        CorSigUncompressPointer(psig.GetPtr(), (void**)&th);
        _ASSERTE(!th.IsNull());
        return(IsTypeRefOrDef(szClassName, th.GetModule(), th.GetCl()));
    }

    return( false );
}

//------------------------------------------------------------------------
// Tests for the existence of a custom modifier
//------------------------------------------------------------------------
BOOL SigPointer::HasCustomModifier(Module *pModule, LPCSTR szModName, CorElementType cmodtype) const
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        NOTHROW;
        GC_NOTRIGGER;
        FORBID_FAULT;
        MODE_ANY;
    }
    CONTRACTL_END


    BAD_FORMAT_NOTHROW_ASSERT(cmodtype == ELEMENT_TYPE_CMOD_OPT || cmodtype == ELEMENT_TYPE_CMOD_REQD);

    SigPointer sp = *this;
    CorElementType etyp;
    if (sp.AtSentinel())
        sp.m_ptr++;

    BYTE data;

    if (FAILED(sp.GetByte(&data)))
        return FALSE;

    etyp = (CorElementType)data;

2303

2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393
    while (etyp == ELEMENT_TYPE_CMOD_OPT || etyp == ELEMENT_TYPE_CMOD_REQD) {

        mdToken tk;
        if (FAILED(sp.GetToken(&tk)))
            return FALSE;

        if (etyp == cmodtype && IsTypeRefOrDef(szModName, pModule, tk))
        {
            return(TRUE);
        }

        if (FAILED(sp.GetByte(&data)))
            return FALSE;

        etyp = (CorElementType)data;


    }
    return(FALSE);
}

#endif // #ifndef DACCESS_COMPILE

//------------------------------------------------------------------------
// Tests for ELEMENT_TYPE_CLASS or ELEMENT_TYPE_VALUETYPE followed by a TypeDef,
// and returns the TypeDef
//------------------------------------------------------------------------
BOOL SigPointer::IsTypeDef(mdTypeDef* pTypeDef) const
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        NOTHROW;
        GC_NOTRIGGER;
        FORBID_FAULT;
        MODE_ANY;
    }
    CONTRACTL_END;

    SigPointer sigTemp(*this);

    CorElementType etype = ELEMENT_TYPE_END;
    HRESULT hr = sigTemp.GetElemType(&etype);
    if (FAILED(hr))
        return FALSE;

    if (etype != ELEMENT_TYPE_CLASS && etype != ELEMENT_TYPE_VALUETYPE)
        return FALSE;

    mdToken token = mdTypeRefNil;
    hr = sigTemp.GetToken(&token);
    if (FAILED(hr))
        return FALSE;

    if (TypeFromToken(token) != mdtTypeDef)
        return FALSE;

    if (pTypeDef)
        *pTypeDef = (mdTypeDef)token;

    return TRUE;
}

CorElementType SigPointer::PeekElemTypeNormalized(Module* pModule, const SigTypeContext *pTypeContext, TypeHandle * pthValueType) const
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        if (FORBIDGC_LOADER_USE_ENABLED()) NOTHROW; else THROWS;
        if (FORBIDGC_LOADER_USE_ENABLED()) GC_NOTRIGGER; else GC_TRIGGERS;
        if (FORBIDGC_LOADER_USE_ENABLED()) FORBID_FAULT; else { INJECT_FAULT(COMPlusThrowOM()); }
        MODE_ANY;
        SUPPORTS_DAC;
    }
    CONTRACTL_END

    CorElementType type = PeekElemTypeClosed(pModule, pTypeContext);
    _ASSERTE(type != ELEMENT_TYPE_INTERNAL);

    if (type == ELEMENT_TYPE_VALUETYPE)
    {
        {
            // Everett C++ compiler can generate a TypeRef with RS=0
            // without respective TypeDef for unmanaged valuetypes,
            // referenced only by pointers to them.
            // In such case, GetTypeHandleThrowing returns null handle,
            // and we return E_T_VOID
            TypeHandle th = GetTypeHandleThrowing(pModule, pTypeContext, ClassLoader::LoadTypes, CLASS_LOAD_APPROXPARENTS, TRUE);
            if(th.IsNull())
            {
2394
                th = TypeHandle(CoreLibBinder::GetElementType(ELEMENT_TYPE_VOID));
2395 2396 2397 2398 2399 2400 2401
            }

            type = th.GetInternalCorElementType();
            if (pthValueType != NULL)
                *pthValueType = th;
        }
    }
2402 2403 2404 2405 2406
    else if (type == ELEMENT_TYPE_TYPEDBYREF)
    {
        if (pthValueType != NULL)
            *pthValueType = TypeHandle(g_TypedReferenceMT);
    }
2407 2408 2409 2410 2411

    return(type);
}

//---------------------------------------------------------------------------------------
2412 2413
//
CorElementType
2414
SigPointer::PeekElemTypeClosed(
2415
    Module *               pModule,
2416 2417 2418 2419 2420
    const SigTypeContext * pTypeContext) const
{
    CONTRACTL
    {
        INSTANCE_CHECK;
2421
        NOTHROW;
2422 2423 2424 2425 2426 2427 2428
        GC_NOTRIGGER;
        FORBID_FAULT;
        MODE_ANY;
        SUPPORTS_DAC;
    }
    CONTRACTL_END

2429

2430 2431 2432 2433 2434
    CorElementType type;

    if (FAILED(PeekElemType(&type)))
        return ELEMENT_TYPE_END;

2435 2436 2437
    if ((type == ELEMENT_TYPE_GENERICINST) ||
        (type == ELEMENT_TYPE_VAR) ||
        (type == ELEMENT_TYPE_MVAR) ||
2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454
        (type == ELEMENT_TYPE_INTERNAL))
    {
        SigPointer sp(*this);
        if (FAILED(sp.GetElemType(NULL))) // skip over E_T_XXX
            return ELEMENT_TYPE_END;

        switch (type)
        {
            case ELEMENT_TYPE_GENERICINST:
            {
                if (FAILED(sp.GetElemType(&type)))
                    return ELEMENT_TYPE_END;

                if (type != ELEMENT_TYPE_INTERNAL)
                    return type;
            }

2455 2456
            FALLTHROUGH;

2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479
            case ELEMENT_TYPE_INTERNAL:
            {
                TypeHandle th;

                // this check is not functional in DAC and provides no security against a malicious dump
                // the DAC is prepared to receive an invalid type handle
#ifndef DACCESS_COMPILE
                if ((pModule != NULL) && pModule->IsSigInIL(m_ptr))
                {
                    return ELEMENT_TYPE_END;
                }
#endif

                if (FAILED(sp.GetPointer((void **)&th)))
                {
                    return ELEMENT_TYPE_END;
                }
                _ASSERTE(!th.IsNull());

                return th.GetSignatureCorElementType();
            }
            case ELEMENT_TYPE_VAR :
            case ELEMENT_TYPE_MVAR :
2480
            {
2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499
                TypeHandle th = sp.GetTypeVariable(type, pTypeContext);
                if (th.IsNull())
                {
                    BAD_FORMAT_NOTHROW_ASSERT(!"You either have bad signature or caller forget to pass valid type context");
                    return ELEMENT_TYPE_END;
                }

                return th.GetSignatureCorElementType();
            }
            default:
                UNREACHABLE();
        }
    }

    return type;
} // SigPointer::PeekElemTypeClosed


//---------------------------------------------------------------------------------------
2500
//
2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529
mdTypeRef SigPointer::PeekValueTypeTokenClosed(Module *pModule, const SigTypeContext *pTypeContext, Module **ppModuleOfToken) const
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        NOTHROW;
        GC_NOTRIGGER;
        PRECONDITION(PeekElemTypeClosed(NULL, pTypeContext) == ELEMENT_TYPE_VALUETYPE);
        FORBID_FAULT;
        MODE_ANY;
    }
    CONTRACTL_END


    mdToken token;
    CorElementType type;

    *ppModuleOfToken = pModule;

    if (FAILED(PeekElemType(&type)))
        return mdTokenNil;

    switch (type)
    {
    case ELEMENT_TYPE_GENERICINST:
        {
            SigPointer sp(*this);
            if (FAILED(sp.GetElemType(NULL)))
                return mdTokenNil;
2530

2531 2532 2533 2534
            CorElementType subtype;
            if (FAILED(sp.GetElemType(&subtype)))
                return mdTokenNil;
            if (subtype == ELEMENT_TYPE_INTERNAL)
2535
                return mdTokenNil;
2536
            _ASSERTE(subtype == ELEMENT_TYPE_VALUETYPE);
2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559

            if (FAILED(sp.GetToken(&token)))
                return mdTokenNil;

            return token;
        }
    case ELEMENT_TYPE_VAR :
    case ELEMENT_TYPE_MVAR :
        {
            SigPointer sp(*this);

            if (FAILED(sp.GetElemType(NULL)))
                return mdTokenNil;

            TypeHandle th = sp.GetTypeVariable(type, pTypeContext);
            *ppModuleOfToken = th.GetModule();
            _ASSERTE(!th.IsNull());
            return(th.GetCl());
        }
    case ELEMENT_TYPE_INTERNAL:
        // we have no way to give back a token for the E_T_INTERNAL so we return  a null one
        // and make the caller deal with it
        return mdTokenNil;
2560

2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577
    default:
        {
            _ASSERTE(type == ELEMENT_TYPE_VALUETYPE);
            SigPointer sp(*this);

            if (FAILED(sp.GetElemType(NULL)))
                return mdTokenNil;

            if (FAILED(sp.GetToken(&token)))
                return mdTokenNil;

            return token;
        }
    }
}

//---------------------------------------------------------------------------------------
2578
//
2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590
UINT MetaSig::GetElemSize(CorElementType etype, TypeHandle thValueType)
{
    CONTRACTL
    {
        if (FORBIDGC_LOADER_USE_ENABLED()) NOTHROW; else THROWS;
        if (FORBIDGC_LOADER_USE_ENABLED()) GC_NOTRIGGER; else GC_TRIGGERS;
        if (FORBIDGC_LOADER_USE_ENABLED()) FORBID_FAULT; else { INJECT_FAULT(COMPlusThrowOM()); }
        MODE_ANY;
        SUPPORTS_DAC;
    }
    CONTRACTL_END

2591
    if ((UINT)etype >= ARRAY_SIZE(gElementTypeInfo))
2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610
        ThrowHR(COR_E_BADIMAGEFORMAT, BFA_BAD_COMPLUS_SIG);

    int cbsize = gElementTypeInfo[(UINT)etype].m_cbSize;
    if (cbsize != -1)
        return(cbsize);

    if (!thValueType.IsNull())
        return thValueType.GetSize();

    if (etype == ELEMENT_TYPE_VAR || etype == ELEMENT_TYPE_MVAR)
    {
        LOG((LF_ALWAYS, LL_INFO1000, "GENERICS: Warning: SizeOf on VAR without instantiation\n"));
        return(sizeof(LPVOID));
    }

    ThrowHR(COR_E_BADIMAGEFORMAT, BFA_BAD_ELEM_IN_SIZEOF);
}

//---------------------------------------------------------------------------------------
2611
//
2612 2613 2614
// Assumes that the SigPointer points to the start of an element type.
// Returns size of that element in bytes. This is the minimum size that a
// field of this type would occupy inside an object.
2615
//
2616
UINT SigPointer::SizeOf(Module* pModule, const SigTypeContext *pTypeContext, TypeHandle* pTypeHandle) const
2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        if (FORBIDGC_LOADER_USE_ENABLED()) NOTHROW; else THROWS;
        if (FORBIDGC_LOADER_USE_ENABLED()) GC_NOTRIGGER; else GC_TRIGGERS;
        if (FORBIDGC_LOADER_USE_ENABLED()) FORBID_FAULT; else { INJECT_FAULT(COMPlusThrowOM()); }
        MODE_ANY;
        UNCHECKED(PRECONDITION(CheckPointer(pModule)));
        UNCHECKED(PRECONDITION(CheckPointer(pTypeContext, NULL_OK)));
        SUPPORTS_DAC;
    }
    CONTRACTL_END

2631 2632
    CorElementType etype = PeekElemTypeNormalized(pModule, pTypeContext, pTypeHandle);
    return MetaSig::GetElemSize(etype, *pTypeHandle);
2633 2634 2635 2636 2637
}

#ifndef DACCESS_COMPILE

//---------------------------------------------------------------------------------------
2638
//
2639 2640
// Determines if the current argument is System.String.
// Caller must determine first that the argument type is ELEMENT_TYPE_CLASS.
2641
//
2642 2643 2644 2645 2646 2647 2648 2649
BOOL MetaSig::IsStringType() const
{
    WRAPPER_NO_CONTRACT

    return m_pLastType.IsStringType(m_pModule, &m_typeContext);
}

//---------------------------------------------------------------------------------------
2650
//
2651 2652
// Determines if the current argument is a particular class.
// Caller must determine first that the argument type is ELEMENT_TYPE_CLASS.
2653
//
2654 2655 2656 2657 2658 2659 2660 2661
BOOL MetaSig::IsClass(LPCUTF8 szClassName) const
{
    WRAPPER_NO_CONTRACT

    return m_pLastType.IsClass(m_pModule, szClassName, &m_typeContext);
}

//---------------------------------------------------------------------------------------
2662
//
2663 2664 2665
// Return the type of an reference if the array is the param type
//  The arg type must be an ELEMENT_TYPE_BYREF
//  ref to array needs additional arg
2666
//
2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698
CorElementType MetaSig::GetByRefType(TypeHandle *pTy) const
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        THROWS;
        GC_TRIGGERS;
        INJECT_FAULT(COMPlusThrowOM());
        MODE_ANY;
    }
    CONTRACTL_END

    SigPointer sigptr(m_pLastType);

    CorElementType typ = ELEMENT_TYPE_END;
    IfFailThrowBF(sigptr.GetElemType(&typ), BFA_BAD_SIGNATURE, GetModule());

    _ASSERTE(typ == ELEMENT_TYPE_BYREF);
    typ = (CorElementType)sigptr.PeekElemTypeClosed(GetModule(), &m_typeContext);

    if (!CorIsPrimitiveType(typ))
    {
        if (typ == ELEMENT_TYPE_TYPEDBYREF)
            THROW_BAD_FORMAT(BFA_TYPEDBYREFCANNOTHAVEBYREF, GetModule());
        TypeHandle th = sigptr.GetTypeHandleThrowing(m_pModule, &m_typeContext);
        *pTy = th;
        return(th.GetSignatureCorElementType());
    }
    return(typ);
}

//---------------------------------------------------------------------------------------
2699
//
2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718
HRESULT CompareTypeTokensNT(mdToken tk1, mdToken tk2, Module *pModule1, Module *pModule2)
{
    STATIC_CONTRACT_NOTHROW;

    HRESULT hr = S_OK;
    EX_TRY
    {
        if (CompareTypeTokens(tk1, tk2, pModule1, pModule2))
            hr = S_OK;
        else
            hr = S_FALSE;
    }
    EX_CATCH_HRESULT_NO_ERRORINFO(hr);
    return hr;
}

#ifdef FEATURE_TYPEEQUIVALENCE

//---------------------------------------------------------------------------------------
2719
//
2720
// Returns S_FALSE if the type is not decorated with TypeIdentifierAttribute.
2721
//
2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748
HRESULT TypeIdentifierData::Init(Module *pModule, mdToken tk)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
        PRECONDITION(CheckPointer(pModule));
        PRECONDITION(TypeFromToken(tk) == mdtTypeDef);
    }
    CONTRACTL_END

    IMDInternalImport *pInternalImport = pModule->GetMDImport();
    HRESULT hr = S_OK;

    DWORD dwAttrType;
    IfFailRet(pInternalImport->GetTypeDefProps(tk, &dwAttrType, NULL));

    if (IsTdWindowsRuntime(dwAttrType))
    {
        // no type equivalence support for WinRT types
        return S_FALSE;
    }

    ULONG cbData;
    const BYTE *pData;

2749
    IfFailRet(pModule->GetCustomAttribute(
2750
        tk,
2751
        WellKnownAttribute::TypeIdentifier,
2752
        (const void **)&pData,
2753
        &cbData));
2754

2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765
    if (hr == S_OK)
    {
        CustomAttributeParser caType(pData, cbData);

        if (cbData > 4)
        {
            // parameterless blob is 01 00 00 00 which means that the two arguments must follow now
            CaArg args[2];

            args[0].Init(SERIALIZATION_TYPE_STRING, 0);
            args[1].Init(SERIALIZATION_TYPE_STRING, 0);
2766
            IfFailRet(ParseKnownCaArgs(caType, args, ARRAY_SIZE(args)));
2767

2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781
            m_cbScope = args[0].val.str.cbStr;
            m_pchScope = args[0].val.str.pStr;
            m_cbIdentifierName = args[1].val.str.cbStr;
            m_pchIdentifierName = args[1].val.str.pStr;
        }
        else
        {
            // no arguments follow but we should still verify the blob
            IfFailRet(caType.ValidateProlog());
        }
    }
    else
    {
        // no TypeIdentifierAttribute -> the assembly must be a type library
2782 2783 2784 2785 2786
        bool has_eq = !pModule->GetAssembly()->IsDynamic();

#ifdef FEATURE_COMINTEROP
        has_eq = has_eq && pModule->GetAssembly()->IsPIAOrImportedFromTypeLib();
#endif // FEATURE_COMINTEROP
2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800

        if (!has_eq)
        {
            // this type is not opted into type equivalence
            return S_FALSE;
        }
    }

    if (m_pchIdentifierName == NULL)
    {
        // we have got no data from the TypeIdentifier attribute -> we have to get it elsewhere
        if (IsTdInterface(dwAttrType) && IsTdImport(dwAttrType))
        {
            // ComImport interfaces get scope from their GUID
2801
            hr = pModule->GetCustomAttribute(tk, WellKnownAttribute::Guid, (const void **)&pData, &cbData);
2802 2803 2804 2805
        }
        else
        {
            // other equivalent types get it from the declaring assembly
2806
            hr = pModule->GetCustomAttribute(TokenFromRid(1, mdtAssembly), WellKnownAttribute::Guid, (const void **)&pData, &cbData);
2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836
        }

        if (hr != S_OK)
        {
            // no GUID is available
            return hr;
        }

        CustomAttributeParser caType(pData, cbData);
        CaArg guidarg;

        guidarg.Init(SERIALIZATION_TYPE_STRING, 0);
        IfFailRet(ParseKnownCaArgs(caType, &guidarg, 1));

        m_cbScope = guidarg.val.str.cbStr;
        m_pchScope = guidarg.val.str.pStr;

        // all types get their identifier from their namespace and name
        LPCUTF8 pszName;
        LPCUTF8 pszNamespace;
        IfFailRet(pInternalImport->GetNameOfTypeDef(tk, &pszName, &pszNamespace));

        m_cbIdentifierNamespace = (pszNamespace != NULL ? strlen(pszNamespace) : 0);
        m_pchIdentifierNamespace = pszNamespace;

        m_cbIdentifierName = strlen(pszName);
        m_pchIdentifierName = pszName;

        hr = S_OK;
    }
2837

2838 2839 2840 2841
    return hr;
}

//---------------------------------------------------------------------------------------
2842
//
2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879
BOOL TypeIdentifierData::IsEqual(const TypeIdentifierData & data) const
{
    LIMITED_METHOD_CONTRACT;

    // scope needs to be the same
    if (m_cbScope != data.m_cbScope || _strnicmp(m_pchScope, data.m_pchScope, m_cbScope) != 0)
        return FALSE;

    // identifier needs to be the same
    if (m_cbIdentifierNamespace == 0 && data.m_cbIdentifierNamespace == 0)
    {
        // we are comparing only m_pchIdentifierName
        return (m_cbIdentifierName == data.m_cbIdentifierName) &&
               (memcmp(m_pchIdentifierName, data.m_pchIdentifierName, m_cbIdentifierName) == 0);
    }

    if (m_cbIdentifierNamespace != 0 && data.m_cbIdentifierNamespace != 0)
    {
        // we are comparing both m_pchIdentifierNamespace and m_pchIdentifierName
        return (m_cbIdentifierName == data.m_cbIdentifierName) &&
               (m_cbIdentifierNamespace == data.m_cbIdentifierNamespace) &&
               (memcmp(m_pchIdentifierName, data.m_pchIdentifierName, m_cbIdentifierName) == 0) &&
               (memcmp(m_pchIdentifierNamespace, data.m_pchIdentifierNamespace, m_cbIdentifierNamespace) == 0);
    }

    if (m_cbIdentifierNamespace == 0 && data.m_cbIdentifierNamespace != 0)
    {
        // we are comparing m_cbIdentifierName with (data.m_pchIdentifierNamespace + '.' + data.m_pchIdentifierName)
        if (m_cbIdentifierName != data.m_cbIdentifierNamespace + 1 + data.m_cbIdentifierName)
            return FALSE;

        return (memcmp(m_pchIdentifierName, data.m_pchIdentifierNamespace, data.m_cbIdentifierNamespace) == 0) &&
               (m_pchIdentifierName[data.m_cbIdentifierNamespace] == NAMESPACE_SEPARATOR_CHAR) &&
               (memcmp(m_pchIdentifierName + data.m_cbIdentifierNamespace + 1, data.m_pchIdentifierName, data.m_cbIdentifierName) == 0);
    }

    _ASSERTE(m_cbIdentifierNamespace != 0 && data.m_cbIdentifierNamespace == 0);
2880

2881 2882 2883 2884 2885 2886 2887 2888 2889 2890
    // we are comparing (m_pchIdentifierNamespace + '.' + m_pchIdentifierName) with data.m_cbIdentifierName
    if (m_cbIdentifierNamespace + 1 + m_cbIdentifierName != data.m_cbIdentifierName)
        return FALSE;

    return (memcmp(m_pchIdentifierNamespace, data.m_pchIdentifierName, m_cbIdentifierNamespace) == 0) &&
           (data.m_pchIdentifierName[m_cbIdentifierNamespace] == NAMESPACE_SEPARATOR_CHAR) &&
           (memcmp(m_pchIdentifierName, data.m_pchIdentifierName + m_cbIdentifierNamespace + 1, m_cbIdentifierName) == 0);
}

//---------------------------------------------------------------------------------------
2891
//
2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931
static BOOL CompareStructuresForEquivalence(mdToken tk1, mdToken tk2, Module *pModule1, Module *pModule2, BOOL fEnumMode, TokenPairList *pVisited)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END

    // make sure the types don't declare any methods
    IMDInternalImport *pInternalImport1 = pModule1->GetMDImport();
    IMDInternalImport *pInternalImport2 = pModule2->GetMDImport();

    HENUMInternalHolder hMethodEnum1(pInternalImport1);
    HENUMInternalHolder hMethodEnum2(pInternalImport2);

    hMethodEnum1.EnumInit(mdtMethodDef, tk1);
    hMethodEnum2.EnumInit(mdtMethodDef, tk2);

    if (hMethodEnum1.EnumGetCount() != 0 || hMethodEnum2.EnumGetCount() != 0)
        return FALSE;

    // compare field types for equivalence
    HENUMInternalHolder hFieldEnum1(pInternalImport1);
    HENUMInternalHolder hFieldEnum2(pInternalImport2);

    hFieldEnum1.EnumInit(mdtFieldDef, tk1);
    hFieldEnum2.EnumInit(mdtFieldDef, tk2);

    while (true)
    {
        mdToken tkField1, tkField2;

        DWORD dwAttrField1, dwAttrField2;
        bool res1, res2;

        while ((res1 = hFieldEnum1.EnumNext(&tkField1)) == true)
        {
            IfFailThrow(pInternalImport1->GetFieldDefProps(tkField1, &dwAttrField1));
2932

2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965
            if (IsFdPublic(dwAttrField1) && !IsFdStatic(dwAttrField1))
                break;

            if (!fEnumMode || !IsFdLiteral(dwAttrField1)) // ignore literals in enums
                return FALSE;
        }

        while ((res2 = hFieldEnum2.EnumNext(&tkField2)) == true)
        {
            IfFailThrow(pInternalImport2->GetFieldDefProps(tkField2, &dwAttrField2));

            if (IsFdPublic(dwAttrField2) && !IsFdStatic(dwAttrField2))
                break;

            if (!fEnumMode || !IsFdLiteral(dwAttrField2)) // ignore literals in enums
                return FALSE;
        }

        if (!res1 && !res2)
        {
            // we ran out of fields in both types
            break;
        }

        if (res1 != res2)
        {
            // we ran out of fields in one type
            return FALSE;
        }

        // now we have tokens of two instance fields that need to be compared for equivalence
        PCCOR_SIGNATURE pSig1, pSig2;
        DWORD cbSig1, cbSig2;
2966

2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984
        IfFailThrow(pInternalImport1->GetSigOfFieldDef(tkField1, &cbSig1, &pSig1));
        IfFailThrow(pInternalImport2->GetSigOfFieldDef(tkField2, &cbSig2, &pSig2));

        if (!MetaSig::CompareFieldSigs(pSig1, cbSig1, pModule1, pSig2, cbSig2, pModule2, pVisited))
            return FALSE;
    }

    if (!fEnumMode)
    {
        // compare layout (layout kind, charset, packing, size, offsets, marshaling)
        if (!CompareTypeLayout(tk1, tk2, pModule1, pModule2))
            return FALSE;
    }

    return TRUE;
}

//---------------------------------------------------------------------------------------
2985
//
2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032
static void GetDelegateInvokeMethodSignature(mdToken tkDelegate, Module *pModule, DWORD *pcbSig, PCCOR_SIGNATURE *ppSig)
{
    CONTRACTL
    {
        THROWS;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END

    IMDInternalImport *pInternalImport = pModule->GetMDImport();

    HENUMInternalHolder hEnum(pInternalImport);
    hEnum.EnumInit(mdtMethodDef, tkDelegate);

    mdToken tkMethod;
    while (hEnum.EnumNext(&tkMethod))
    {
        LPCUTF8 pszName;
        IfFailThrow(pInternalImport->GetNameAndSigOfMethodDef(tkMethod, ppSig, pcbSig, &pszName));

        if (strcmp(pszName, "Invoke") == 0)
            return;
    }

    ThrowHR(COR_E_BADIMAGEFORMAT);
}

static BOOL CompareDelegatesForEquivalence(mdToken tk1, mdToken tk2, Module *pModule1, Module *pModule2, TokenPairList *pVisited)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END

    PCCOR_SIGNATURE pSig1;
    PCCOR_SIGNATURE pSig2;
    DWORD cbSig1;
    DWORD cbSig2;

    // find the Invoke methods
    GetDelegateInvokeMethodSignature(tk1, pModule1, &cbSig1, &pSig1);
    GetDelegateInvokeMethodSignature(tk2, pModule2, &cbSig2, &pSig2);

3033
    return MetaSig::CompareMethodSigs(pSig1, cbSig1, pModule1, NULL, pSig2, cbSig2, pModule2, NULL, FALSE, pVisited);
3034 3035
}

3036
#endif // FEATURE_TYPEEQUIVALENCE
3037 3038 3039 3040
#endif // #ifndef DACCESS_COMPILE

#ifndef DACCESS_COMPILE
//---------------------------------------------------------------------------------------
3041
//
3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133
BOOL IsTypeDefExternallyVisible(mdToken tk, Module *pModule, DWORD dwAttrClass)
{
    CONTRACTL
    {
        NOTHROW;
        MODE_ANY;
        GC_NOTRIGGER;
    }
    CONTRACTL_END;

    BOOL bIsVisible = TRUE;

    if (!IsTdPublic(dwAttrClass))
    {
        if (!IsTdNestedPublic(dwAttrClass))
            return FALSE;

        IMDInternalImport *pInternalImport = pModule->GetMDImport();

        DWORD dwAttrEnclosing;

        mdTypeDef tdCurrent = tk;
        do
        {
            mdTypeDef tdEnclosing = mdTypeDefNil;

            if (FAILED(pInternalImport->GetNestedClassProps(tdCurrent, &tdEnclosing)))
                return FALSE;

            tdCurrent = tdEnclosing;

            // We stop searching as soon as we hit the first non NestedPublic type.
            // So logically, we can't possibly fall off the top of the hierarchy.
            _ASSERTE(tdEnclosing != mdTypeDefNil);

            mdToken tkJunk = mdTokenNil;

            if (FAILED(pInternalImport->GetTypeDefProps(tdEnclosing, &dwAttrEnclosing, &tkJunk)))
            {
                return FALSE;
            }
        }
        while (IsTdNestedPublic(dwAttrEnclosing));

        bIsVisible = IsTdPublic(dwAttrEnclosing);
    }

    return bIsVisible;
}
#endif

#ifndef FEATURE_TYPEEQUIVALENCE
#ifndef DACCESS_COMPILE
BOOL IsTypeDefEquivalent(mdToken tk, Module *pModule)
{
    LIMITED_METHOD_CONTRACT;
    return FALSE;
}
#endif
#endif

#ifdef FEATURE_TYPEEQUIVALENCE
#ifndef DACCESS_COMPILE
BOOL IsTypeDefEquivalent(mdToken tk, Module *pModule)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        INJECT_FAULT(COMPlusThrowOM());
        MODE_ANY;
    }
    CONTRACTL_END;


    IMDInternalImport *pInternalImport = pModule->GetMDImport();

    if (tk == mdTypeDefNil)
        return FALSE;

    DWORD dwAttrType;
    mdToken tkExtends;

    IfFailThrow(pInternalImport->GetTypeDefProps(tk, &dwAttrType, &tkExtends));

    if (IsTdWindowsRuntime(dwAttrType))
    {
        // no type equivalence support for WinRT types
        return FALSE;
    }

    // Check for the TypeIdentifierAttribute and auto opt-in
3134
    HRESULT hr = pModule->GetCustomAttribute(tk, WellKnownAttribute::TypeIdentifier, NULL, NULL);
3135 3136 3137 3138 3139
    IfFailThrow(hr);

    // 1. Type is within assembly marked with ImportedFromTypeLibAttribute or PrimaryInteropAssemblyAttribute
    if (hr != S_OK)
    {
3140 3141 3142 3143 3144 3145
        // no TypeIdentifierAttribute -> the assembly must be a type library
        bool has_eq = !pModule->GetAssembly()->IsDynamic();

#ifdef FEATURE_COMINTEROP
        has_eq = has_eq && pModule->GetAssembly()->IsPIAOrImportedFromTypeLib();
#endif // FEATURE_COMINTEROP
3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174

        if (!has_eq)
            return FALSE;
    }
    else if (hr == S_OK)
    {
        // Type has TypeIdentifierAttribute. It is marked as type equivalent.
        return TRUE;
    }

    mdToken tdEnum = g_pEnumClass->GetCl();
    Module *pSystemModule = g_pEnumClass->GetModule();
    mdToken tdValueType = g_pValueTypeClass->GetCl();
    _ASSERTE(pSystemModule == g_pValueTypeClass->GetModule());
    mdToken tdMCDelegate = g_pMulticastDelegateClass->GetCl();
    _ASSERTE(pSystemModule == g_pMulticastDelegateClass->GetModule());

    // 2. Type is a COMImport/COMEvent interface, enum, struct, or delegate
    BOOL fIsCOMInterface = FALSE;
    if (IsTdInterface(dwAttrType))
    {
        if (IsTdImport(dwAttrType))
        {
            // COMImport
            fIsCOMInterface = TRUE;
        }
        else
        {
            // COMEvent
3175
            hr = pModule->GetCustomAttribute(tk, WellKnownAttribute::ComEventInterface, NULL, NULL);
3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238
            IfFailThrow(hr);

            if (hr == S_OK)
                fIsCOMInterface = TRUE;
        }
    }

    if (fIsCOMInterface ||
        (!IsTdInterface(dwAttrType) && (tkExtends != mdTypeDefNil) &&
        ((CompareTypeTokens(tkExtends, tdEnum, pModule, pSystemModule)) ||
         (CompareTypeTokens(tkExtends, tdValueType, pModule, pSystemModule) && (tk != tdEnum || pModule != pSystemModule)) ||
         (CompareTypeTokens(tkExtends, tdMCDelegate, pModule, pSystemModule)))))
    {
        HENUMInternal   hEnumGenericPars;
        IfFailThrow(pInternalImport->EnumInit(mdtGenericParam, tk, &hEnumGenericPars));
        DWORD numGenericArgs = pInternalImport->EnumGetCount(&hEnumGenericPars);

        // 3. Type is not generic
        if (numGenericArgs > 0)
            return FALSE;

        // 4. Type is externally visible (i.e. public)
        if (!IsTypeDefExternallyVisible(tk, pModule, dwAttrType))
            return FALSE;

        // since the token has not been loaded yet,
        // its module might be not fully initialized in this domain
        // take care of that possibility
        pModule->EnsureAllocated();

        // 6. If type is nested, nesting type must be equivalent.
        if (IsTdNested(dwAttrType))
        {
            mdTypeDef tdEnclosing = mdTypeDefNil;

            IfFailThrow(pInternalImport->GetNestedClassProps(tk, &tdEnclosing));

            if (!IsTypeDefEquivalent(tdEnclosing, pModule))
                return FALSE;
        }

        // Type meets all of the requirements laid down above. Type is considered to be marked as equivalent.
        return TRUE;
    }
    else
    {
        return FALSE;
    }
}
#endif
#endif // FEATURE_TYPEEQUIVALENCE

BOOL CompareTypeDefsForEquivalence(mdToken tk1, mdToken tk2, Module *pModule1, Module *pModule2, TokenPairList *pVisited)
{
#if !defined(DACCESS_COMPILE) && defined(FEATURE_TYPEEQUIVALENCE)
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        INJECT_FAULT(COMPlusThrowOM());
        MODE_ANY;
    }
    CONTRACTL_END;
3239

3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286
    if (TokenPairList::InTypeEquivalenceForbiddenScope(pVisited))
    {
        // we limit variance on generics only to interfaces
        return FALSE;
    }
    if (TokenPairList::Exists(pVisited, tk1, pModule1, tk2, pModule2))
    {
        // we are in the process of comparing these tokens already
        return TRUE;
    }
    TokenPairList newVisited(tk1, pModule1, tk2, pModule2, pVisited);

    DWORD dwAttrType1;
    DWORD dwAttrType2;
    mdToken tkExtends1;
    mdToken tkExtends2;
    IMDInternalImport *pInternalImport1 = pModule1->GetMDImport();
    IMDInternalImport *pInternalImport2 = pModule2->GetMDImport();

    // *************************************************************************
    // 1. both types must opt into type equivalence and be able to acquire their equivalence set
    // *************************************************************************
    TypeIdentifierData data1;
    TypeIdentifierData data2;
    HRESULT hr;

    IfFailThrow(hr = data1.Init(pModule1, tk1));
    BOOL has_eq1 = (hr == S_OK);

    IfFailThrow(hr = data2.Init(pModule2, tk2));
    BOOL has_eq2 = (hr == S_OK);

    if (!has_eq1 || !has_eq2)
        return FALSE;

    // Check to ensure that the types are actually opted into equivalence.
    if (!IsTypeDefEquivalent(tk1, pModule1) || !IsTypeDefEquivalent(tk2, pModule2))
        return FALSE;

    // *************************************************************************
    // 2. the two types have the same type identity
    // *************************************************************************
    if (!data1.IsEqual(data2))
        return FALSE;

    IfFailThrow(pInternalImport1->GetTypeDefProps(tk1, &dwAttrType1, &tkExtends1));
    IfFailThrow(pInternalImport2->GetTypeDefProps(tk2, &dwAttrType2, &tkExtends2));
3287

3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318
    // *************************************************************************
    // 2a. the two types have the same name and namespace
    // *************************************************************************
    {
        LPCUTF8 pszName1;
        LPCUTF8 pszNamespace1;
        LPCUTF8 pszName2;
        LPCUTF8 pszNamespace2;

        IfFailThrow(pInternalImport1->GetNameOfTypeDef(tk1, &pszName1, &pszNamespace1));
        IfFailThrow(pInternalImport2->GetNameOfTypeDef(tk2, &pszName2, &pszNamespace2));

        if (strcmp(pszName1, pszName2) != 0 || strcmp(pszNamespace1, pszNamespace2) != 0)
        {
            return FALSE;
        }
    }

    // *************************************************************************
    // 2b. the two types must not be nested... or they must have an equivalent enclosing type
    // *************************************************************************
    {
        if (!!IsTdNested(dwAttrType1) != !!IsTdNested(dwAttrType2))
        {
            return FALSE;
        }

        if (IsTdNested(dwAttrType1))
        {
            mdToken tkEnclosing1;
            mdToken tkEnclosing2;
3319

3320 3321
            IfFailThrow(pInternalImport1->GetNestedClassProps(tk1, &tkEnclosing1));
            IfFailThrow(pInternalImport2->GetNestedClassProps(tk2, &tkEnclosing2));
3322

3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364
            if (!CompareTypeDefsForEquivalence(tkEnclosing1, tkEnclosing2, pModule1, pModule2, pVisited))
            {
                return FALSE;
            }
        }
    }

    // *************************************************************************
    // 3. type is an interface, struct, enum, or delegate
    // *************************************************************************
    if (IsTdInterface(dwAttrType1))
    {
        // interface
        if (!IsTdInterface(dwAttrType2))
            return FALSE;
    }
    else
    {
        mdToken tdEnum = g_pEnumClass->GetCl();
        Module *pSystemModule = g_pEnumClass->GetModule();

        if (CompareTypeTokens(tkExtends1, tdEnum, pModule1, pSystemModule, &newVisited))
        {
            // enum (extends System.Enum)
            if (!CompareTypeTokens(tkExtends2, tdEnum, pModule2, pSystemModule, &newVisited))
                return FALSE;

            if (!CompareStructuresForEquivalence(tk1, tk2, pModule1, pModule2, TRUE, &newVisited))
                return FALSE;
        }
        else
        {
            mdToken tdValueType = g_pValueTypeClass->GetCl();
            _ASSERTE(pSystemModule == g_pValueTypeClass->GetModule());

            if (CompareTypeTokens(tkExtends1, tdValueType, pModule1, pSystemModule, &newVisited) &&
                (tk1 != tdEnum || pModule1 != pSystemModule))
            {
                // struct (extends System.ValueType but is not System.Enum)
                if (!CompareTypeTokens(tkExtends2, tdValueType, pModule2, pSystemModule, &newVisited) ||
                    (tk2 == tdEnum && pModule2 == pSystemModule))
                    return FALSE;
3365

3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392
                if  (!CompareStructuresForEquivalence(tk1, tk2, pModule1, pModule2, FALSE, &newVisited))
                    return FALSE;
            }
            else
            {
                mdToken tdMCDelegate = g_pMulticastDelegateClass->GetCl();
                _ASSERTE(pSystemModule == g_pMulticastDelegateClass->GetModule());

                if (CompareTypeTokens(tkExtends1, tdMCDelegate, pModule1, pSystemModule, &newVisited))
                {
                    // delegate (extends System.MulticastDelegate)
                    if (!CompareTypeTokens(tkExtends2, tdMCDelegate, pModule2, pSystemModule, &newVisited))
                        return FALSE;

                    if (!CompareDelegatesForEquivalence(tk1, tk2, pModule1, pModule2, &newVisited))
                        return FALSE;
                }
                else
                {
                    // the type is neither interface, struct, enum, nor delegate
                    return FALSE;
                }
            }
        }
    }
    return TRUE;

3393
#else //!defined(DACCESS_COMPILE) && defined(FEATURE_TYPEEQUIVALENCE)
3394 3395 3396 3397 3398 3399 3400 3401 3402 3403

#ifdef DACCESS_COMPILE
    // We shouldn't execute this code in dac builds.
    _ASSERTE(FALSE);
#endif
    return (tk1 == tk2) && (pModule1 == pModule2);
#endif //!defined(DACCESS_COMPILE) && defined(FEATURE_COMINTEROP)
}


3404
BOOL CompareTypeTokens(mdToken tk1, mdToken tk2, ModuleBase *pModule1, ModuleBase *pModule2, TokenPairList *pVisited /*= NULL*/)
3405 3406 3407 3408 3409 3410 3411 3412 3413
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        INJECT_FAULT(COMPlusThrowOM());
        MODE_ANY;
    }
    CONTRACTL_END
3414

3415 3416 3417 3418 3419 3420 3421 3422 3423
    HRESULT hr;
    IMDInternalImport *pInternalImport1;
    IMDInternalImport *pInternalImport2;
    LPCUTF8 pszName1;
    LPCUTF8 pszNamespace1;
    LPCUTF8 pszName2;
    LPCUTF8 pszNamespace2;
    mdToken enclosingTypeTk1;
    mdToken enclosingTypeTk2;
3424

3425 3426 3427 3428 3429
    if (dac_cast<TADDR>(pModule1) == dac_cast<TADDR>(pModule2) &&
        tk1 == tk2)
    {
        return TRUE;
    }
3430

3431 3432 3433 3434 3435 3436
    pInternalImport1 = pModule1->GetMDImport();
    if (!pInternalImport1->IsValidToken(tk1))
    {
        BAD_FORMAT_NOTHROW_ASSERT(!"Invalid token");
        IfFailGo(COR_E_BADIMAGEFORMAT);
    }
3437

3438 3439 3440 3441 3442 3443
    pInternalImport2 = pModule2->GetMDImport();
    if (!pInternalImport2->IsValidToken(tk2))
    {
        BAD_FORMAT_NOTHROW_ASSERT(!"Invalid token");
        IfFailGo(COR_E_BADIMAGEFORMAT);
    }
3444

3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457
    pszName1 = NULL;
    pszNamespace1 = NULL;
    if (TypeFromToken(tk1) == mdtTypeRef)
    {
        IfFailGo(pInternalImport1->GetNameOfTypeRef(tk1, &pszNamespace1, &pszName1));
    }
    else if (TypeFromToken(tk1) == mdtTypeDef)
    {
        if (TypeFromToken(tk2) == mdtTypeDef)
        {
#ifdef FEATURE_TYPEEQUIVALENCE
            // two type defs can't be the same unless they are identical or resolve to
            // equivalent types (equivalence based on GUID and TypeIdentifierAttribute)
3458 3459 3460
            _ASSERTE(pModule1->IsFullModule());
            _ASSERTE(pModule2->IsFullModule());
            return CompareTypeDefsForEquivalence(tk1, tk2, static_cast<Module*>(pModule1), static_cast<Module*>(pModule2), pVisited);
3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471
#else // FEATURE_TYPEEQUIVALENCE
            // two type defs can't be the same unless they are identical
            return FALSE;
#endif // FEATURE_TYPEEQUIVALENCE
        }
        IfFailGo(pInternalImport1->GetNameOfTypeDef(tk1, &pszName1, &pszNamespace1));
    }
    else
    {
        return FALSE;  // comparing a type against a module or assemblyref, no match
    }
3472

3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486
    pszName2 = NULL;
    pszNamespace2 = NULL;
    if (TypeFromToken(tk2) == mdtTypeRef)
    {
        IfFailGo(pInternalImport2->GetNameOfTypeRef(tk2, &pszNamespace2, &pszName2));
    }
    else if (TypeFromToken(tk2) == mdtTypeDef)
    {
        IfFailGo(pInternalImport2->GetNameOfTypeDef(tk2, &pszName2, &pszNamespace2));
    }
    else
    {
        return FALSE;       // comparing a type against a module or assemblyref, no match
    }
3487

3488 3489 3490 3491 3492
    _ASSERTE((pszNamespace1 != NULL) && (pszNamespace2 != NULL));
    if (strcmp(pszName1, pszName2) != 0 || strcmp(pszNamespace1, pszNamespace2) != 0)
    {
        return FALSE;
    }
3493

3494 3495
    //////////////////////////////////////////////////////////////////////
    // OK names pass, see if it is nested, and if so that the nested classes are the same
3496

3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516
    enclosingTypeTk1 = mdTokenNil;
    if (TypeFromToken(tk1) == mdtTypeRef)
    {
        IfFailGo(pInternalImport1->GetResolutionScopeOfTypeRef(tk1, &enclosingTypeTk1));
        if (enclosingTypeTk1 == mdTypeRefNil)
        {
            enclosingTypeTk1 = mdTokenNil;
        }
    }
    else
    {
        if (FAILED(hr = pInternalImport1->GetNestedClassProps(tk1, &enclosingTypeTk1)))
        {
            if (hr != CLDB_E_RECORD_NOTFOUND)
            {
                IfFailGo(hr);
            }
            enclosingTypeTk1 = mdTokenNil;
        }
    }
3517

3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537
    enclosingTypeTk2 = mdTokenNil;
    if (TypeFromToken(tk2) == mdtTypeRef)
    {
        IfFailGo(pInternalImport2->GetResolutionScopeOfTypeRef(tk2, &enclosingTypeTk2));
        if (enclosingTypeTk2 == mdTypeRefNil)
        {
            enclosingTypeTk2 = mdTokenNil;
        }
    }
    else
    {
        if (FAILED(hr = pInternalImport2->GetNestedClassProps(tk2, &enclosingTypeTk2)))
        {
            if (hr != CLDB_E_RECORD_NOTFOUND)
            {
                IfFailGo(hr);
            }
            enclosingTypeTk2 = mdTokenNil;
        }
    }
3538

3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551
    if (TypeFromToken(enclosingTypeTk1) == mdtTypeRef || TypeFromToken(enclosingTypeTk1) == mdtTypeDef)
    {
        if (!CompareTypeTokens(enclosingTypeTk1, enclosingTypeTk2, pModule1, pModule2, pVisited))
            return FALSE;

        // TODO: We could return TRUE if we knew that type equivalence was not exercised during the previous call.
    }
    else
    {
        // Check if tk1 is non-nested, but tk2 is nested
        if (TypeFromToken(enclosingTypeTk2) == mdtTypeRef || TypeFromToken(enclosingTypeTk2) == mdtTypeDef)
            return FALSE;
    }
3552

3553
    //////////////////////////////////////////////////////////////////////
A
Adeel Mujahid 已提交
3554
    // OK, we have non-nested types or the enclosing types are equivalent
3555

3556

3557 3558
    // Do not load the type! (Or else you may run into circular dependency loading problems.)
    Module* pFoundModule1;
3559
    mdToken foundTypeDefToken1;
3560 3561 3562 3563 3564 3565 3566 3567
    if (!ClassLoader::ResolveTokenToTypeDefThrowing(pModule1,
                                                    tk1,
                                                    &pFoundModule1,
                                                    &foundTypeDefToken1))
    {
        return FALSE;
    }
    _ASSERTE(TypeFromToken(foundTypeDefToken1) == mdtTypeDef);
3568

3569 3570 3571 3572 3573 3574 3575 3576 3577 3578
    Module* pFoundModule2;
    mdToken foundTypeDefToken2;
    if (!ClassLoader::ResolveTokenToTypeDefThrowing(pModule2,
                                                    tk2,
                                                    &pFoundModule2,
                                                    &foundTypeDefToken2))
    {
        return FALSE;
    }
    _ASSERTE(TypeFromToken(foundTypeDefToken2) == mdtTypeDef);
3579

3580 3581
    _ASSERTE(TypeFromToken(foundTypeDefToken1) == mdtTypeDef && TypeFromToken(foundTypeDefToken2) == mdtTypeDef);
    return CompareTypeTokens(foundTypeDefToken1, foundTypeDefToken2, pFoundModule1, pFoundModule2, pVisited);
3582

3583 3584 3585 3586
ErrExit:
#ifdef DACCESS_COMPILE
    ThrowHR(hr);
#else
3587 3588 3589 3590 3591 3592 3593 3594
    if (pModule2->IsFullModule())
    {
        EEFileLoadException::Throw(static_cast<Module*>(pModule2)->GetPEAssembly(), hr);
    }
    else
    {
        ThrowHR(hr);
    }
3595 3596 3597 3598 3599 3600 3601
#endif //!DACCESS_COMPILE
} // CompareTypeTokens

#ifdef _PREFAST_
#pragma warning(push)
#pragma warning(disable:21000) // Suppress PREFast warning about overly large function
#endif
3602

3603
//---------------------------------------------------------------------------------------
3604
//
3605
// Compare the next elements in two sigs.
3606
//
3607
// static
3608
BOOL
3609
MetaSig::CompareElementType(
3610 3611 3612 3613
    PCCOR_SIGNATURE &    pSig1,
    PCCOR_SIGNATURE &    pSig2,
    PCCOR_SIGNATURE      pEndSig1,
    PCCOR_SIGNATURE      pEndSig2,
3614 3615
    ModuleBase *         pModule1,
    ModuleBase *         pModule2,
3616 3617
    const Substitution * pSubst1,
    const Substitution * pSubst2,
3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643
    TokenPairList *      pVisited) // = NULL
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        INJECT_FAULT(COMPlusThrowOM());
        MODE_ANY;
    }
    CONTRACTL_END

 redo:
    // We jump here if the Type was a ET_CMOD prefix.
    // The caller expects us to handle CMOD's but not present them as types on their own.

    if ((pSig1 >= pEndSig1) || (pSig2 >= pEndSig2))
    {   // End of sig encountered prematurely
        return FALSE;
    }

    if ((*pSig2 == ELEMENT_TYPE_VAR) && (pSubst2 != NULL) && !pSubst2->GetInst().IsNull())
    {
        SigPointer inst = pSubst2->GetInst();
        pSig2++;
        DWORD index;
        IfFailThrow(CorSigUncompressData_EndPtr(pSig2, pEndSig2, &index));
3644

3645 3646 3647 3648 3649 3650 3651
        for (DWORD i = 0; i < index; i++)
        {
            IfFailThrow(inst.SkipExactlyOne());
        }
        PCCOR_SIGNATURE pSig3 = inst.GetPtr();
        IfFailThrow(inst.SkipExactlyOne());
        PCCOR_SIGNATURE pEndSig3 = inst.GetPtr();
3652

3653
        return CompareElementType(
3654 3655 3656 3657 3658 3659 3660 3661
            pSig1,
            pSig3,
            pEndSig1,
            pEndSig3,
            pModule1,
            pSubst2->GetModule(),
            pSubst1,
            pSubst2->GetNext(),
3662 3663 3664 3665 3666 3667 3668 3669 3670
            pVisited);
    }

    if ((*pSig1 == ELEMENT_TYPE_VAR) && (pSubst1 != NULL) && !pSubst1->GetInst().IsNull())
    {
        SigPointer inst = pSubst1->GetInst();
        pSig1++;
        DWORD index;
        IfFailThrow(CorSigUncompressData_EndPtr(pSig1, pEndSig1, &index));
3671

3672 3673 3674 3675 3676 3677 3678
        for (DWORD i = 0; i < index; i++)
        {
            IfFailThrow(inst.SkipExactlyOne());
        }
        PCCOR_SIGNATURE pSig3 = inst.GetPtr();
        IfFailThrow(inst.SkipExactlyOne());
        PCCOR_SIGNATURE pEndSig3 = inst.GetPtr();
3679

3680
        return CompareElementType(
3681 3682 3683 3684 3685 3686 3687 3688
            pSig3,
            pSig2,
            pEndSig3,
            pEndSig2,
            pSubst1->GetModule(),
            pModule2,
            pSubst1->GetNext(),
            pSubst2,
3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704
            pVisited);
    }

    CorElementType Type1 = ELEMENT_TYPE_MAX; // initialize to illegal
    CorElementType Type2 = ELEMENT_TYPE_MAX; // initialize to illegal

    IfFailThrow(CorSigUncompressElementType_EndPtr(pSig1, pEndSig1, &Type1));
    IfFailThrow(CorSigUncompressElementType_EndPtr(pSig2, pEndSig2, &Type2));

    if (Type1 == ELEMENT_TYPE_INTERNAL)
    {
        // this check is not functional in DAC and provides no security against a malicious dump
        // the DAC is prepared to receive an invalid type handle
#ifndef DACCESS_COMPILE
        if (pModule1->IsSigInIL(pSig1))
        {
3705
            THROW_BAD_FORMAT(BFA_BAD_SIGNATURE, pModule1);
3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717
        }
#endif

    }

    if (Type2 == ELEMENT_TYPE_INTERNAL)
    {
        // this check is not functional in DAC and provides no security against a malicious dump
        // the DAC is prepared to receive an invalid type handle
#ifndef DACCESS_COMPILE
        if (pModule2->IsSigInIL(pSig2))
        {
3718
            THROW_BAD_FORMAT(BFA_BAD_SIGNATURE, pModule2);
3719 3720 3721 3722 3723 3724 3725 3726 3727 3728
        }
#endif
    }

    if (Type1 != Type2)
    {
        if ((Type1 == ELEMENT_TYPE_INTERNAL) || (Type2 == ELEMENT_TYPE_INTERNAL))
        {
            TypeHandle     hInternal;
            CorElementType eOtherType;
3729
            ModuleBase *   pOtherModule;
3730 3731 3732 3733

            // One type is already loaded, collect all the necessary information to identify the other type.
            if (Type1 == ELEMENT_TYPE_INTERNAL)
            {
3734
                IfFailThrow(CorSigUncompressPointer_EndPtr(pSig1, pEndSig1, (void**)&hInternal));
3735

3736 3737 3738 3739 3740 3741
                eOtherType = Type2;
                pOtherModule = pModule2;
            }
            else
            {
                IfFailThrow(CorSigUncompressPointer_EndPtr(pSig2, pEndSig2, (void **)&hInternal));
3742

3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761
                eOtherType = Type1;
                pOtherModule = pModule1;
            }

            // Internal types can only correspond to types or value types.
            switch (eOtherType)
            {
                case ELEMENT_TYPE_OBJECT:
                {
                    return (hInternal.AsMethodTable() == g_pObjectClass);
                }
                case ELEMENT_TYPE_STRING:
                {
                    return (hInternal.AsMethodTable() == g_pStringClass);
                }
                case ELEMENT_TYPE_VALUETYPE:
                case ELEMENT_TYPE_CLASS:
                {
                    mdToken tkOther;
3762
                    if (Type1 == ELEMENT_TYPE_INTERNAL)
3763 3764 3765 3766 3767 3768 3769 3770
                    {
                        IfFailThrow(CorSigUncompressToken_EndPtr(pSig2, pEndSig2, &tkOther));
                    }
                    else
                    {
                        IfFailThrow(CorSigUncompressToken_EndPtr(pSig1, pEndSig1, &tkOther));
                    }

3771
                    TypeHandle hOtherType = ClassLoader::LoadTypeDefOrRefThrowing(
3772 3773 3774
                        pOtherModule,
                        tkOther,
                        ClassLoader::ReturnNullIfNotFound,
3775
                        ClassLoader::FailIfUninstDefOrRef);
3776

3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827
                    return (hInternal == hOtherType);
                }
                default:
                {
                    return FALSE;
                }
            }
        }
        else
        {
            return FALSE; // types must be the same
        }
    }

    switch (Type1)
    {
        default:
        {
            // Unknown type!
            THROW_BAD_FORMAT(BFA_BAD_COMPLUS_SIG, pModule1);
        }

        case ELEMENT_TYPE_U:
        case ELEMENT_TYPE_I:
        case ELEMENT_TYPE_VOID:
        case ELEMENT_TYPE_I1:
        case ELEMENT_TYPE_U1:
        case ELEMENT_TYPE_I2:
        case ELEMENT_TYPE_U2:
        case ELEMENT_TYPE_I4:
        case ELEMENT_TYPE_U4:
        case ELEMENT_TYPE_I8:
        case ELEMENT_TYPE_U8:
        case ELEMENT_TYPE_R4:
        case ELEMENT_TYPE_R8:
        case ELEMENT_TYPE_BOOLEAN:
        case ELEMENT_TYPE_CHAR:
        case ELEMENT_TYPE_TYPEDBYREF:
        case ELEMENT_TYPE_STRING:
        case ELEMENT_TYPE_OBJECT:
        {
            return TRUE;
        }

        case ELEMENT_TYPE_VAR:
        case ELEMENT_TYPE_MVAR:
        {
            DWORD varNum1;
            IfFailThrow(CorSigUncompressData_EndPtr(pSig1, pEndSig1, &varNum1));
            DWORD varNum2;
            IfFailThrow(CorSigUncompressData_EndPtr(pSig2, pEndSig2, &varNum2));
3828

3829 3830
            return (varNum1 == varNum2);
        }
3831

3832 3833 3834 3835 3836 3837 3838 3839 3840 3841
        case ELEMENT_TYPE_CMOD_REQD:
        case ELEMENT_TYPE_CMOD_OPT:
        {
            mdToken tk1, tk2;

            IfFailThrow(CorSigUncompressToken_EndPtr(pSig1, pEndSig1, &tk1));
            IfFailThrow(CorSigUncompressToken_EndPtr(pSig2, pEndSig2, &tk2));

#ifndef DACCESS_COMPILE
            if (!CompareTypeDefOrRefOrSpec(
3842 3843 3844 3845 3846 3847
                    pModule1,
                    tk1,
                    pSubst1,
                    pModule2,
                    tk2,
                    pSubst2,
3848 3849 3850 3851 3852
                    pVisited))
            {
                return FALSE;
            }
#endif //!DACCESS_COMPILE
3853

3854 3855 3856 3857 3858 3859 3860 3861 3862
            goto redo;
        }

        // These take an additional argument, which is the element type
        case ELEMENT_TYPE_SZARRAY:
        case ELEMENT_TYPE_PTR:
        case ELEMENT_TYPE_BYREF:
        {
            if (!CompareElementType(
3863 3864 3865 3866 3867 3868 3869 3870
                    pSig1,
                    pSig2,
                    pEndSig1,
                    pEndSig2,
                    pModule1,
                    pModule2,
                    pSubst1,
                    pSubst2,
3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884
                    pVisited))
            {
                return FALSE;
            }
            return TRUE;
        }

        case ELEMENT_TYPE_VALUETYPE:
        case ELEMENT_TYPE_CLASS:
        {
            mdToken tk1, tk2;

            IfFailThrow(CorSigUncompressToken_EndPtr(pSig1, pEndSig1, &tk1));
            IfFailThrow(CorSigUncompressToken_EndPtr(pSig2, pEndSig2, &tk2));
3885

3886 3887
            return CompareTypeTokens(tk1, tk2, pModule1, pModule2, pVisited);
        }
3888

3889 3890 3891
        case ELEMENT_TYPE_FNPTR:
        {
            // Compare calling conventions
3892
            // Note: We used to read them as compressed integers, which is wrong, but works for correct
3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910
            // signatures as the highest bit is always 0 for calling conventions
            CorElementType callingConvention1 = ELEMENT_TYPE_MAX; // initialize to illegal
            IfFailThrow(CorSigUncompressElementType_EndPtr(pSig1, pEndSig1, &callingConvention1));
            CorElementType callingConvention2 = ELEMENT_TYPE_MAX; // initialize to illegal
            IfFailThrow(CorSigUncompressElementType_EndPtr(pSig2, pEndSig2, &callingConvention2));
            if (callingConvention1 != callingConvention2)
            {
                return FALSE;
            }

            DWORD argCnt1;
            IfFailThrow(CorSigUncompressData_EndPtr(pSig1, pEndSig1, &argCnt1));
            DWORD argCnt2;
            IfFailThrow(CorSigUncompressData_EndPtr(pSig2, pEndSig2, &argCnt2));
            if (argCnt1 != argCnt2)
            {
                return FALSE;
            }
3911

3912 3913 3914 3915
            // Compressed integer values can be only 0-0x1FFFFFFF
            _ASSERTE(argCnt1 < MAXDWORD);
            // Add return parameter into the parameter count (it cannot overflow)
            argCnt1++;
3916

3917 3918 3919 3920 3921
            TokenPairList newVisited = TokenPairList::AdjustForTypeEquivalenceForbiddenScope(pVisited);
            // Compare all parameters, incl. return parameter
            while (argCnt1 > 0)
            {
                if (!CompareElementType(
3922 3923 3924 3925 3926 3927 3928 3929
                        pSig1,
                        pSig2,
                        pEndSig1,
                        pEndSig2,
                        pModule1,
                        pModule2,
                        pSubst1,
                        pSubst2,
3930 3931 3932 3933 3934 3935 3936 3937
                        &newVisited))
                {
                    return FALSE;
                }
                --argCnt1;
            }
            return TRUE;
        }
3938

3939 3940 3941
        case ELEMENT_TYPE_GENERICINST:
        {
            TokenPairList newVisited = TokenPairList::AdjustForTypeSpec(
3942 3943 3944
                pVisited,
                pModule1,
                pSig1 - 1,
3945 3946 3947 3948 3949
                (DWORD)(pEndSig1 - pSig1) + 1);
            TokenPairList newVisitedAlwaysForbidden = TokenPairList::AdjustForTypeEquivalenceForbiddenScope(pVisited);

            // Type constructors - The actual type is never permitted to participate in type equivalence.
            if (!CompareElementType(
3950 3951 3952 3953 3954 3955 3956 3957
                    pSig1,
                    pSig2,
                    pEndSig1,
                    pEndSig2,
                    pModule1,
                    pModule2,
                    pSubst1,
                    pSubst2,
3958 3959 3960 3961
                    &newVisitedAlwaysForbidden))
            {
                return FALSE;
            }
3962

3963 3964 3965 3966 3967 3968 3969 3970
            DWORD argCnt1;
            IfFailThrow(CorSigUncompressData_EndPtr(pSig1, pEndSig1, &argCnt1));
            DWORD argCnt2;
            IfFailThrow(CorSigUncompressData_EndPtr(pSig2, pEndSig2, &argCnt2));
            if (argCnt1 != argCnt2)
            {
                return FALSE;
            }
3971

3972 3973 3974
            while (argCnt1 > 0)
            {
                if (!CompareElementType(
3975 3976 3977 3978 3979 3980 3981 3982
                        pSig1,
                        pSig2,
                        pEndSig1,
                        pEndSig2,
                        pModule1,
                        pModule2,
                        pSubst1,
                        pSubst2,
3983 3984 3985 3986 3987 3988 3989 3990
                        &newVisited))
                {
                    return FALSE;
                }
                --argCnt1;
            }
            return TRUE;
        }
3991

3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002
        case ELEMENT_TYPE_ARRAY:
        {
            // syntax: ARRAY <base type> rank <count n> <size 1> .... <size n> <lower bound m>
            // <lb 1> .... <lb m>
            DWORD rank1, rank2;
            DWORD dimension_sizes1, dimension_sizes2;
            DWORD dimension_lowerb1, dimension_lowerb2;
            DWORD i;

            // element type
            if (!CompareElementType(
4003 4004 4005 4006 4007 4008 4009 4010
                    pSig1,
                    pSig2,
                    pEndSig1,
                    pEndSig2,
                    pModule1,
                    pModule2,
                    pSubst1,
                    pSubst2,
4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082
                    pVisited))
            {
                return FALSE;
            }

            IfFailThrow(CorSigUncompressData_EndPtr(pSig1, pEndSig1, &rank1));
            IfFailThrow(CorSigUncompressData_EndPtr(pSig2, pEndSig2, &rank2));
            if (rank1 != rank2)
            {
                return FALSE;
            }
            // A zero ends the array spec
            if (rank1 == 0)
            {
                return TRUE;
            }

            IfFailThrow(CorSigUncompressData_EndPtr(pSig1, pEndSig1, &dimension_sizes1));
            IfFailThrow(CorSigUncompressData_EndPtr(pSig2, pEndSig2, &dimension_sizes2));
            if (dimension_sizes1 != dimension_sizes2)
            {
                return FALSE;
            }

            for (i = 0; i < dimension_sizes1; i++)
            {
                DWORD size1, size2;

                if (pSig1 == pEndSig1)
                {   // premature end ok
                    return TRUE;
                }

                IfFailThrow(CorSigUncompressData_EndPtr(pSig1, pEndSig1, &size1));
                IfFailThrow(CorSigUncompressData_EndPtr(pSig2, pEndSig2, &size2));
                if (size1 != size2)
                {
                    return FALSE;
                }
            }

            if (pSig1 == pEndSig1)
            {   // premature end ok
                return TRUE;
            }

            // # dimensions for lower bounds
            IfFailThrow(CorSigUncompressData_EndPtr(pSig1, pEndSig1, &dimension_lowerb1));
            IfFailThrow(CorSigUncompressData_EndPtr(pSig2, pEndSig2, &dimension_lowerb2));
            if (dimension_lowerb1 != dimension_lowerb2)
            {
                return FALSE;
            }

            for (i = 0; i < dimension_lowerb1; i++)
            {
                DWORD size1, size2;

                if (pSig1 == pEndSig1)
                {   // premature end ok
                    return TRUE;
                }

                IfFailThrow(CorSigUncompressData_EndPtr(pSig1, pEndSig1, &size1));
                IfFailThrow(CorSigUncompressData_EndPtr(pSig2, pEndSig2, &size2));
                if (size1 != size2)
                {
                    return FALSE;
                }
            }
            return TRUE;
        }
4083

4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094
        case ELEMENT_TYPE_INTERNAL:
        {
            TypeHandle hType1, hType2;

            IfFailThrow(CorSigUncompressPointer_EndPtr(pSig1, pEndSig1, (void **)&hType1));
            IfFailThrow(CorSigUncompressPointer_EndPtr(pSig2, pEndSig2, (void **)&hType2));

            return (hType1 == hType2);
        }
    } // switch
    // Unreachable
4095
    UNREACHABLE();
4096 4097 4098 4099 4100 4101 4102
} // MetaSig::CompareElementType
#ifdef _PREFAST_
#pragma warning(pop)
#endif


//---------------------------------------------------------------------------------------
4103 4104
//
BOOL
4105
MetaSig::CompareTypeDefsUnderSubstitutions(
4106 4107 4108 4109
    MethodTable *        pTypeDef1,
    MethodTable *        pTypeDef2,
    const Substitution * pSubst1,
    const Substitution * pSubst2,
4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145
    TokenPairList *      pVisited)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        INJECT_FAULT(COMPlusThrowOM());
        MODE_ANY;
    }
    CONTRACTL_END

    bool fSameTypeDef = (pTypeDef1->GetTypeDefRid() == pTypeDef2->GetTypeDefRid()) && (pTypeDef1->GetModule() == pTypeDef2->GetModule());

    if (!fSameTypeDef)
    {
        if (!pTypeDef1->GetClass()->IsEquivalentType() || !pTypeDef2->GetClass()->IsEquivalentType() || TokenPairList::InTypeEquivalenceForbiddenScope(pVisited))
        {
            return FALSE;
        }
        else
        {
            if (!CompareTypeDefsForEquivalence(pTypeDef1->GetCl(), pTypeDef2->GetCl(), pTypeDef1->GetModule(), pTypeDef2->GetModule(), pVisited))
            {
                return FALSE;
            }
        }
    }

    if (pTypeDef1->GetNumGenericArgs() != pTypeDef2->GetNumGenericArgs())
        return FALSE;

    if (pTypeDef1->GetNumGenericArgs() == 0)
        return TRUE;

    if ((pSubst1 == NULL) || (pSubst2 == NULL) || pSubst1->GetInst().IsNull() || pSubst2->GetInst().IsNull())
        return FALSE;
4146

4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157
    SigPointer inst1 = pSubst1->GetInst();
    SigPointer inst2 = pSubst2->GetInst();
    for (DWORD i = 0; i < pTypeDef1->GetNumGenericArgs(); i++)
    {
        PCCOR_SIGNATURE startInst1 = inst1.GetPtr();
        IfFailThrow(inst1.SkipExactlyOne());
        PCCOR_SIGNATURE endInst1ptr = inst1.GetPtr();
        PCCOR_SIGNATURE startInst2 = inst2.GetPtr();
        IfFailThrow(inst2.SkipExactlyOne());
        PCCOR_SIGNATURE endInst2ptr = inst2.GetPtr();
        if (!CompareElementType(
4158 4159 4160 4161 4162 4163 4164 4165
                startInst1,
                startInst2,
                endInst1ptr,
                endInst2ptr,
                pSubst1->GetModule(),
                pSubst2->GetModule(),
                pSubst1->GetNext(),
                pSubst2->GetNext(),
4166 4167 4168 4169 4170 4171 4172 4173 4174 4175
                pVisited))
        {
            return FALSE;
        }
    }
    return TRUE;

} // MetaSig::CompareTypeDefsUnderSubstitutions

//---------------------------------------------------------------------------------------
4176 4177
//
BOOL
4178
TypeHandleCompareHelper(
4179
    TypeHandle th1,
4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198
    TypeHandle th2)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        INJECT_FAULT(COMPlusThrowOM());
        MODE_ANY;
    }
    CONTRACTL_END

#ifndef DACCESS_COMPILE
    return th1.IsEquivalentTo(th2);
#else
    return TRUE;
#endif // #ifndef DACCESS_COMPILE
}

//---------------------------------------------------------------------------------------
4199
//
4200
//static
4201
BOOL
4202
MetaSig::CompareMethodSigs(
4203 4204
    MetaSig & msig1,
    MetaSig & msig2,
4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215
    BOOL      ignoreCallconv)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        INJECT_FAULT(COMPlusThrowOM());
        MODE_ANY;
    }
    CONTRACTL_END

4216 4217
    if (!ignoreCallconv &&
        ((msig1.GetCallingConventionInfo() & IMAGE_CEE_CS_CALLCONV_MASK)
4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230
         != (msig2.GetCallingConventionInfo() & IMAGE_CEE_CS_CALLCONV_MASK)))
    {
        return FALSE; // calling convention mismatch
    }

    if (msig1.NumFixedArgs() != msig2.NumFixedArgs())
        return FALSE; // number of arguments don't match

    // check that the argument types are equal
    for (DWORD i = 0; i<msig1.NumFixedArgs(); i++) //@GENERICSVER: does this really do the return type too?
    {
        CorElementType  et1 = msig1.NextArg();
        CorElementType  et2 = msig2.NextArg();
4231
        if (et1 != et2)
4232
            return FALSE;
4233
        if (!CorTypeInfo::IsPrimitiveType(et1))
4234 4235 4236 4237
        {
            if (!TypeHandleCompareHelper(msig1.GetLastTypeHandleThrowing(), msig2.GetLastTypeHandleThrowing()))
                return FALSE;
        }
4238
    }
4239 4240 4241 4242 4243 4244

    CorElementType  ret1 = msig1.GetReturnType();
    CorElementType  ret2 = msig2.GetReturnType();
    if (ret1 != ret2)
        return FALSE;

4245
    if (!CorTypeInfo::IsPrimitiveType(ret1))
4246 4247 4248
    {
        return TypeHandleCompareHelper(msig1.GetRetTypeHandleThrowing(), msig2.GetRetTypeHandleThrowing());
    }
4249

4250 4251 4252 4253
    return TRUE;
}

//---------------------------------------------------------------------------------------
4254
//
4255
//static
4256
HRESULT
4257
MetaSig::CompareMethodSigsNT(
4258 4259 4260 4261 4262 4263 4264 4265
    PCCOR_SIGNATURE      pSignature1,
    DWORD                cSig1,
    Module *             pModule1,
    const Substitution * pSubst1,
    PCCOR_SIGNATURE      pSignature2,
    DWORD                cSig2,
    Module *             pModule2,
    const Substitution * pSubst2,
4266 4267 4268 4269 4270 4271 4272
    TokenPairList *      pVisited) //= NULL
{
    STATIC_CONTRACT_NOTHROW;

    HRESULT hr = S_OK;
    EX_TRY
    {
4273
        if (CompareMethodSigs(pSignature1, cSig1, pModule1, pSubst1, pSignature2, cSig2, pModule2, pSubst2, FALSE, pVisited))
4274 4275 4276 4277 4278 4279 4280 4281 4282
            hr = S_OK;
        else
            hr = S_FALSE;
    }
    EX_CATCH_HRESULT_NO_ERRORINFO(hr);
    return hr;
}

//---------------------------------------------------------------------------------------
4283
//
4284 4285
// Compare two method sigs and return whether they are the same.
// @GENERICS: instantiation of the type variables in the second signature
4286
//
4287
//static
4288
BOOL
4289
MetaSig::CompareMethodSigs(
4290 4291
    PCCOR_SIGNATURE      pSignature1,
    DWORD                cSig1,
4292
    ModuleBase *         pModule1,
4293 4294 4295
    const Substitution * pSubst1,
    PCCOR_SIGNATURE      pSignature2,
    DWORD                cSig2,
4296
    ModuleBase *         pModule2,
4297
    const Substitution * pSubst2,
4298
    BOOL                 skipReturnTypeSig,
4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320
    TokenPairList *      pVisited) //= NULL
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        INJECT_FAULT(COMPlusThrowOM());
        MODE_ANY;
    }
    CONTRACTL_END

    PCCOR_SIGNATURE pSig1 = pSignature1;
    PCCOR_SIGNATURE pSig2 = pSignature2;
    PCCOR_SIGNATURE pEndSig1 = pSignature1 + cSig1;
    PCCOR_SIGNATURE pEndSig2 = pSignature2 + cSig2;
    DWORD           ArgCount1;
    DWORD           ArgCount2;
    DWORD           i;

    // If scopes are the same, and sigs are same, can return.
    // If the sigs aren't the same, but same scope, can't return yet, in
    // case there are two AssemblyRefs pointing to the same assembly or such.
4321 4322 4323 4324
    if ((pModule1 == pModule2) &&
        (cSig1 == cSig2) &&
        (pSubst1 == NULL) &&
        (pSubst2 == NULL) &&
4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392
        (memcmp(pSig1, pSig2, cSig1) == 0))
    {
        return TRUE;
    }

    if ((*pSig1 & ~CORINFO_CALLCONV_PARAMTYPE) != (*pSig2 & ~CORINFO_CALLCONV_PARAMTYPE))
    {   // Calling convention or hasThis mismatch
        return FALSE;
    }

    __int8 callConv = *pSig1;

    pSig1++;
    pSig2++;

    if (callConv & IMAGE_CEE_CS_CALLCONV_GENERIC)
    {
        DWORD TyArgCount1;
        IfFailThrow(CorSigUncompressData_EndPtr(pSig1, pEndSig1, &TyArgCount1));
        DWORD TyArgCount2;
        IfFailThrow(CorSigUncompressData_EndPtr(pSig2, pEndSig2, &TyArgCount2));

        if (TyArgCount1 != TyArgCount2)
            return FALSE;
    }

    IfFailThrow(CorSigUncompressData_EndPtr(pSig1, pEndSig1, &ArgCount1));
    IfFailThrow(CorSigUncompressData_EndPtr(pSig2, pEndSig2, &ArgCount2));

    if (ArgCount1 != ArgCount2)
    {
        if ((callConv & IMAGE_CEE_CS_CALLCONV_MASK) != IMAGE_CEE_CS_CALLCONV_VARARG)
            return FALSE;

        // Signature #1 is the caller.  We proceed until we hit the sentinel, or we hit
        // the end of the signature (which is an implied sentinel).  We never worry about
        // what follows the sentinel, because that is the ... part, which is not
        // involved in matching.
        //
        // Theoretically, it's illegal for a sentinel to be the last element in the
        // caller's signature, because it's redundant.  We don't waste our time checking
        // that case, but the metadata validator should.  Also, it is always illegal
        // for a sentinel to appear in a callee's signature.  We assert against this,
        // but in the shipping product the comparison would simply fail.
        //
        // Signature #2 is the callee.  We must hit the exact end of the callee, because
        // we are trying to match on everything up to the variable part.  This allows us
        // to correctly handle overloads, where there are a number of varargs methods
        // to pick from, like m1(int,...) and m2(int,int,...), etc.

        // <= because we want to include a check of the return value!
        for (i = 0; i <= ArgCount1; i++)
        {
            // We may be just going out of bounds on the callee, but no further than that.
            _ASSERTE(i <= ArgCount2 + 1);

            // If we matched all the way on the caller, is the callee now complete?
            if (*pSig1 == ELEMENT_TYPE_SENTINEL)
                return (i > ArgCount2);

            // if we have more to compare on the caller side, but the callee side is
            // exhausted, this isn't our match
            if (i > ArgCount2)
                return FALSE;

            // This would be a breaking change to make this throw... see comment above
            _ASSERT(*pSig2 != ELEMENT_TYPE_SENTINEL);

4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406
            if (i == 0 && skipReturnTypeSig)
            {
                SigPointer ptr1(pSig1, (DWORD)(pEndSig1 - pSig1));
                IfFailThrow(ptr1.SkipExactlyOne());
                pSig1 = ptr1.GetPtr();

                SigPointer ptr2(pSig2, (DWORD)(pEndSig2 - pSig2));
                IfFailThrow(ptr2.SkipExactlyOne());
                pSig2 = ptr2.GetPtr();
            }
            else
            {
                // We are in bounds on both sides.  Compare the element.
                if (!CompareElementType(
4407 4408 4409 4410 4411 4412 4413 4414
                    pSig1,
                    pSig2,
                    pEndSig1,
                    pEndSig2,
                    pModule1,
                    pModule2,
                    pSubst1,
                    pSubst2,
4415
                    pVisited))
4416 4417 4418
                {
                    return FALSE;
                }
4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431
            }
        }

        // If we didn't consume all of the callee signature, then we failed.
        if (i <= ArgCount2)
            return FALSE;

        return TRUE;
    }

    // do return type as well
    for (i = 0; i <= ArgCount1; i++)
    {
4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444
        if (i == 0 && skipReturnTypeSig)
        {
            SigPointer ptr1(pSig1, (DWORD)(pEndSig1 - pSig1));
            IfFailThrow(ptr1.SkipExactlyOne());
            pSig1 = ptr1.GetPtr();

            SigPointer ptr2(pSig2, (DWORD)(pEndSig2 - pSig2));
            IfFailThrow(ptr2.SkipExactlyOne());
            pSig2 = ptr2.GetPtr();
        }
        else
        {
            if (!CompareElementType(
4445 4446 4447 4448 4449 4450 4451 4452
                pSig1,
                pSig2,
                pEndSig1,
                pEndSig2,
                pModule1,
                pModule2,
                pSubst1,
                pSubst2,
4453
                pVisited))
4454 4455 4456
            {
                return FALSE;
            }
4457 4458 4459 4460 4461 4462 4463
        }
    }

    return TRUE;
} // MetaSig::CompareMethodSigs

//---------------------------------------------------------------------------------------
4464
//
4465 4466
//static
BOOL MetaSig::CompareFieldSigs(
4467 4468
    PCCOR_SIGNATURE pSignature1,
    DWORD           cSig1,
4469
    ModuleBase *    pModule1,
4470 4471
    PCCOR_SIGNATURE pSignature2,
    DWORD           cSig2,
4472
    ModuleBase *    pModule2,
4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499
    TokenPairList * pVisited) //= NULL
{
    WRAPPER_NO_CONTRACT;

    PCCOR_SIGNATURE pSig1 = pSignature1;
    PCCOR_SIGNATURE pSig2 = pSignature2;
    PCCOR_SIGNATURE pEndSig1;
    PCCOR_SIGNATURE pEndSig2;

#if 0
    // <TODO>@TODO: If scopes are the same, use identity rule - for now, don't, so that we test the code paths</TODO>
    if (cSig1 != cSig2)
        return(FALSE); // sigs must be same size if they are in the same scope
#endif

    if (*pSig1 != *pSig2)
        return(FALSE); // calling convention, must be IMAGE_CEE_CS_CALLCONV_FIELD

    pEndSig1 = pSig1 + cSig1;
    pEndSig2 = pSig2 + cSig2;

    return(CompareElementType(++pSig1, ++pSig2, pEndSig1, pEndSig2, pModule1, pModule2, NULL, NULL, pVisited));
}

#ifndef DACCESS_COMPILE

//---------------------------------------------------------------------------------------
4500
//
4501
//static
4502
BOOL
4503
MetaSig::CompareElementTypeToToken(
4504
    PCCOR_SIGNATURE &    pSig1,
4505
    PCCOR_SIGNATURE      pEndSig1, // end of sig1
4506
    mdToken              tk2,
4507 4508
    ModuleBase *         pModule1,
    ModuleBase *         pModule2,
4509
    const Substitution * pSubst1,
4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520
    TokenPairList *      pVisited)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        INJECT_FAULT(COMPlusThrowOM());
        MODE_ANY;
    }
    CONTRACTL_END

4521
    _ASSERTE((TypeFromToken(tk2) == mdtTypeDef) ||
4522 4523 4524 4525
             (TypeFromToken(tk2) == mdtTypeRef));

    if (pSig1 >= pEndSig1)
    {   // End of sig encountered prematurely
4526
        return FALSE;
4527 4528 4529 4530 4531 4532 4533 4534
    }

    if ((*pSig1 == ELEMENT_TYPE_VAR) && (pSubst1 != NULL) && !pSubst1->GetInst().IsNull())
    {
        SigPointer inst = pSubst1->GetInst();
        pSig1++;
        DWORD index;
        IfFailThrow(CorSigUncompressData_EndPtr(pSig1, pEndSig1, &index));
4535

4536 4537 4538 4539 4540 4541 4542
        for (DWORD i = 0; i < index; i++)
        {
            IfFailThrow(inst.SkipExactlyOne());
        }
        PCCOR_SIGNATURE pSig3 = inst.GetPtr();
        IfFailThrow(inst.SkipExactlyOne());
        PCCOR_SIGNATURE pEndSig3 = inst.GetPtr();
4543

4544
        return CompareElementTypeToToken(
4545 4546 4547 4548 4549 4550
            pSig3,
            pEndSig3,
            tk2,
            pSubst1->GetModule(),
            pModule2,
            pSubst1->GetNext(),
4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565
            pVisited);
    }

    CorElementType Type1 = ELEMENT_TYPE_MAX; // initialize to illegal

    IfFailThrow(CorSigUncompressElementType_EndPtr(pSig1, pEndSig1, &Type1));
    _ASSERTE(Type1 != ELEMENT_TYPE_INTERNAL);

    if (Type1 == ELEMENT_TYPE_INTERNAL)
    {
        // this check is not functional in DAC and provides no security against a malicious dump
        // the DAC is prepared to receive an invalid type handle
#ifndef DACCESS_COMPILE
        if (pModule1->IsSigInIL(pSig1))
        {
4566
            THROW_BAD_FORMAT(BFA_BAD_SIGNATURE, pModule1);
4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624
        }
#endif
    }

    switch (Type1)
    {
        default:
        {   // Unknown type!
            THROW_BAD_FORMAT(BFA_BAD_COMPLUS_SIG, pModule1);
        }

        case ELEMENT_TYPE_U:
        case ELEMENT_TYPE_I:
        case ELEMENT_TYPE_VOID:
        case ELEMENT_TYPE_I1:
        case ELEMENT_TYPE_U1:
        case ELEMENT_TYPE_I2:
        case ELEMENT_TYPE_U2:
        case ELEMENT_TYPE_I4:
        case ELEMENT_TYPE_U4:
        case ELEMENT_TYPE_I8:
        case ELEMENT_TYPE_U8:
        case ELEMENT_TYPE_R4:
        case ELEMENT_TYPE_R8:
        case ELEMENT_TYPE_BOOLEAN:
        case ELEMENT_TYPE_CHAR:
        case ELEMENT_TYPE_TYPEDBYREF:
        case ELEMENT_TYPE_STRING:
        case ELEMENT_TYPE_OBJECT:
        {
            break;
        }

        case ELEMENT_TYPE_VAR:
        case ELEMENT_TYPE_MVAR:
        {
           return FALSE;
        }
        case ELEMENT_TYPE_CMOD_REQD:
        case ELEMENT_TYPE_CMOD_OPT:
        {
            return FALSE;
        }
        // These take an additional argument, which is the element type
        case ELEMENT_TYPE_SZARRAY:
        case ELEMENT_TYPE_PTR:
        case ELEMENT_TYPE_BYREF:
        {
           return FALSE;
        }
        case ELEMENT_TYPE_VALUETYPE:
        case ELEMENT_TYPE_CLASS:
        {
            mdToken tk1;

            IfFailThrow(CorSigUncompressToken_EndPtr(pSig1, pEndSig1, &tk1));

            return CompareTypeTokens(
4625 4626 4627 4628
                tk1,
                tk2,
                pModule1,
                pModule2,
4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649
                pVisited);
        }
        case ELEMENT_TYPE_FNPTR:
        {
            return FALSE;
        }
        case ELEMENT_TYPE_GENERICINST:
        {
            return FALSE;
        }
        case ELEMENT_TYPE_ARRAY:
        {
            return FALSE;
        }
        case ELEMENT_TYPE_INTERNAL:
        {
            return FALSE;
        }
    }

    return CompareTypeTokens(
4650
        CoreLibBinder::GetElementType(Type1)->GetCl(),
4651
        tk2,
4652
        CoreLibBinder::GetModule(),
4653
        pModule2,
4654 4655 4656 4657 4658 4659
        pVisited);
} // MetaSig::CompareElementTypeToToken

/* static */
BOOL MetaSig::CompareTypeSpecToToken(mdTypeSpec tk1,
                            mdToken tk2,
4660 4661
                            ModuleBase *pModule1,
                            ModuleBase *pModule2,
4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672
                            const Substitution *pSubst1,
                            TokenPairList *pVisited)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        INJECT_FAULT(COMPlusThrowOM());
        MODE_ANY;
    }
    CONTRACTL_END
4673

4674
    _ASSERTE(TypeFromToken(tk1) == mdtTypeSpec);
4675
    _ASSERTE(TypeFromToken(tk2) == mdtTypeDef ||
4676
             TypeFromToken(tk2) == mdtTypeRef);
4677

4678
    IMDInternalImport *pInternalImport = pModule1->GetMDImport();
4679

4680 4681 4682
    PCCOR_SIGNATURE pSig1;
    ULONG cSig1;
    IfFailThrow(pInternalImport->GetTypeSpecFromToken(tk1, &pSig1, &cSig1));
4683

4684 4685 4686 4687 4688 4689 4690
    TokenPairList newVisited = TokenPairList::AdjustForTypeSpec(pVisited, pModule1, pSig1, cSig1);

    return CompareElementTypeToToken(pSig1,pSig1+cSig1,tk2,pModule1,pModule2,pSubst1,&newVisited);
} // MetaSig::CompareTypeSpecToToken


/* static */
4691
BOOL MetaSig::CompareTypeDefOrRefOrSpec(ModuleBase *pModule1, mdToken tok1,
4692
                                        const Substitution *pSubst1,
4693
                                        ModuleBase *pModule2, mdToken tok2,
4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704
                                        const Substitution *pSubst2,
                                        TokenPairList *pVisited)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        INJECT_FAULT(COMPlusThrowOM());
        MODE_ANY;
    }
    CONTRACTL_END
4705

4706 4707 4708 4709 4710 4711
    if (TypeFromToken(tok1) != mdtTypeSpec && TypeFromToken(tok2) != mdtTypeSpec)
    {
        _ASSERTE(TypeFromToken(tok1) == mdtTypeDef || TypeFromToken(tok1) == mdtTypeRef);
        _ASSERTE(TypeFromToken(tok2) == mdtTypeDef || TypeFromToken(tok2) == mdtTypeRef);
        return CompareTypeTokens(tok1,tok2,pModule1,pModule2,pVisited);
    }
4712 4713

    if (TypeFromToken(tok1) != TypeFromToken(tok2))
4714 4715 4716 4717 4718 4719
    {
        if (TypeFromToken(tok1) == mdtTypeSpec)
        {
            return CompareTypeSpecToToken(tok1,tok2,pModule1,pModule2,pSubst1,pVisited);
        }
        else
4720
        {
4721 4722 4723 4724
            _ASSERTE(TypeFromToken(tok2) == mdtTypeSpec);
            return CompareTypeSpecToToken(tok2,tok1,pModule2,pModule1,pSubst2,pVisited);
        }
    }
4725

4726 4727
    _ASSERTE(TypeFromToken(tok1) == mdtTypeSpec &&
             TypeFromToken(tok2) == mdtTypeSpec);
4728

4729 4730
    IMDInternalImport *pInternalImport1 = pModule1->GetMDImport();
    IMDInternalImport *pInternalImport2 = pModule2->GetMDImport();
4731

4732 4733 4734 4735
    PCCOR_SIGNATURE pSig1,pSig2;
    ULONG cSig1,cSig2;
    IfFailThrow(pInternalImport1->GetTypeSpecFromToken(tok1, &pSig1, &cSig1));
    IfFailThrow(pInternalImport2->GetTypeSpecFromToken(tok2, &pSig2, &cSig2));
4736
    return MetaSig::CompareElementType(pSig1, pSig2, pSig1 + cSig1, pSig2 + cSig2, pModule1, pModule2, pSubst1, pSubst2, pVisited);
4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752
} // MetaSig::CompareTypeDefOrRefOrSpec

/* static */
BOOL MetaSig::CompareVariableConstraints(const Substitution *pSubst1,
                                         Module *pModule1, mdGenericParam tok1, //overriding
                                         const Substitution *pSubst2,
                                         Module *pModule2, mdGenericParam tok2) //overridden
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        INJECT_FAULT(COMPlusThrowOM());
        MODE_ANY;
    }
    CONTRACTL_END
4753

4754 4755
    IMDInternalImport *pInternalImport1 = pModule1->GetMDImport();
    IMDInternalImport *pInternalImport2 = pModule2->GetMDImport();
4756

4757
    DWORD specialConstraints1,specialConstraints2;
4758 4759

     // check special constraints
4760 4761 4762 4763 4764
    {
        IfFailThrow(pInternalImport1->GetGenericParamProps(tok1, NULL, &specialConstraints1, NULL, NULL, NULL));
        IfFailThrow(pInternalImport2->GetGenericParamProps(tok2, NULL, &specialConstraints2, NULL, NULL, NULL));
        specialConstraints1 = specialConstraints1 & gpSpecialConstraintMask;
        specialConstraints2 = specialConstraints2 & gpSpecialConstraintMask;
4765

4766
        if ((specialConstraints1 & gpNotNullableValueTypeConstraint) != 0)
4767
        {
4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780
            if ((specialConstraints2 & gpNotNullableValueTypeConstraint) == 0)
                return FALSE;
        }
        if ((specialConstraints1 & gpReferenceTypeConstraint) != 0)
        {
            if ((specialConstraints2 & gpReferenceTypeConstraint) == 0)
                return FALSE;
        }
        if ((specialConstraints1 & gpDefaultConstructorConstraint) != 0)
        {
            if ((specialConstraints2 & (gpDefaultConstructorConstraint | gpNotNullableValueTypeConstraint)) == 0)
                return FALSE;
        }
4781 4782 4783 4784 4785
        if ((specialConstraints1 & gpAcceptByRefLike) != 0)
        {
            if ((specialConstraints2 & gpAcceptByRefLike) == 0)
                return FALSE;
        }
4786
    }
4787 4788


4789 4790 4791
    HENUMInternalHolder hEnum1(pInternalImport1);
    mdGenericParamConstraint tkConstraint1;
    hEnum1.EnumInit(mdtGenericParamConstraint, tok1);
4792

4793 4794 4795 4796 4797
    while (pInternalImport1->EnumNext(&hEnum1, &tkConstraint1))
    {
        mdToken tkConstraintType1, tkParam1;
        IfFailThrow(pInternalImport1->GetGenericParamConstraintProps(tkConstraint1, &tkParam1, &tkConstraintType1));
        _ASSERTE(tkParam1 == tok1);
4798

4799 4800 4801 4802 4803
        // for each non-object constraint,
        // and, in the case of a notNullableValueType, each non-ValueType constraint,
        // find an equivalent constraint on tok2
        // NB: we do not attempt to match constraints equivalent to object (and ValueType when tok1 is notNullable)
        // because they
4804
        // a) are vacuous, and
A
Adeel Mujahid 已提交
4805
        // b) may be implicit (ie. absent) in the overridden variable's declaration
4806
        if (!(CompareTypeDefOrRefOrSpec(pModule1, tkConstraintType1, NULL,
4807
                                       CoreLibBinder::GetModule(), g_pObjectClass->GetCl(), NULL, NULL) ||
4808 4809
          (((specialConstraints1 & gpNotNullableValueTypeConstraint) != 0) &&
           (CompareTypeDefOrRefOrSpec(pModule1, tkConstraintType1, NULL,
4810
                      CoreLibBinder::GetModule(), g_pValueTypeClass->GetCl(), NULL, NULL)))))
4811 4812 4813 4814
        {
            HENUMInternalHolder hEnum2(pInternalImport2);
            mdGenericParamConstraint tkConstraint2;
            hEnum2.EnumInit(mdtGenericParamConstraint, tok2);
4815

4816 4817 4818 4819 4820 4821
            BOOL found = FALSE;
            while (!found && pInternalImport2->EnumNext(&hEnum2, &tkConstraint2) )
            {
                mdToken tkConstraintType2, tkParam2;
                IfFailThrow(pInternalImport2->GetGenericParamConstraintProps(tkConstraint2, &tkParam2, &tkConstraintType2));
                _ASSERTE(tkParam2 == tok2);
4822

4823 4824
                found = CompareTypeDefOrRefOrSpec(pModule1, tkConstraintType1, pSubst1, pModule2, tkConstraintType2, pSubst2, NULL);
            }
4825
            if (!found)
4826 4827
            {
                //none of the constrains on tyvar2 match, exit early
4828
                return FALSE;
4829 4830 4831 4832
            }
        }
        //check next constraint of tok1
    }
4833

4834 4835 4836 4837 4838
    return TRUE;
}

/* static */
BOOL MetaSig::CompareMethodConstraints(const Substitution *pSubst1,
4839
                                       Module *pModule1,
4840 4841 4842
                                       mdMethodDef tok1, //implementation
                                       const Substitution *pSubst2,
                                       Module *pModule2,
A
Adeel Mujahid 已提交
4843
                                       mdMethodDef tok2) //declaration w.r.t substitution
4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        INJECT_FAULT(COMPlusThrowOM());
        MODE_ANY;
    }
    CONTRACTL_END

    IMDInternalImport *pInternalImport1 = pModule1->GetMDImport();
    IMDInternalImport *pInternalImport2 = pModule2->GetMDImport();

4857 4858
    HENUMInternalHolder hEnumTyPars1(pInternalImport1);
    HENUMInternalHolder hEnumTyPars2(pInternalImport2);
4859 4860 4861 4862

    hEnumTyPars1.EnumInit(mdtGenericParam, tok1);
    hEnumTyPars2.EnumInit(mdtGenericParam, tok2);

4863
    mdGenericParam    tkTyPar1,tkTyPar2;
4864 4865 4866 4867 4868 4869 4870 4871 4872 4873

    // enumerate the variables
    DWORD numTyPars1 = pInternalImport1->EnumGetCount(&hEnumTyPars1);
    DWORD numTyPars2 = pInternalImport2->EnumGetCount(&hEnumTyPars2);

    _ASSERTE(numTyPars1 == numTyPars2);
    if (numTyPars1 != numTyPars2) //play it safe
        return FALSE; //throw bad format exception?

    for(unsigned int i = 0; i < numTyPars1; i++)
4874
    {
4875 4876 4877 4878
        pInternalImport1->EnumNext(&hEnumTyPars1, &tkTyPar1);
        pInternalImport2->EnumNext(&hEnumTyPars2, &tkTyPar2);
        if (!CompareVariableConstraints(pSubst1, pModule1, tkTyPar1, pSubst2, pModule2, tkTyPar2))
        {
4879
            return FALSE;
4880
        }
4881
    }
4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904
    return TRUE;
}

#endif // #ifndef DACCESS_COMPILE

// PromoteCarefully
//
// Clients who know they MAY have an interior pointer should come through here.  We
// can efficiently check whether our object lives on the current stack.  If so, our
// reference to it is not an interior pointer.  This is more efficient than asking
// the heap to verify whether our reference is interior, since it would have to
// check all the heap segments, including those containing large objects.
//
// Note that we only have to check against the thread we are currently crawling.  It
// would be illegal for us to have a ByRef from someone else's stack.  And this will
// be asserted if we pass this reference to the heap as a potentially interior pointer.
//
// But the thread we are currently crawling is not the currently executing thread (in
// the general case).  We rely on fragile caching of the interesting thread, in our
// call to UpdateCachedStackInfo() where we initiate the crawl in GcScanRoots() above.
//
// The flags must indicate that the have an interior pointer GC_CALL_INTERIOR
// additionally the flags may indicate that we also have a pinned local byref
4905 4906 4907 4908
//
void PromoteCarefully(promote_func   fn,
                      PTR_PTR_Object ppObj,
                      ScanContext*   sc,
4909
                      uint32_t       flags /* = GC_CALL_INTERIOR*/ )
4910 4911 4912 4913 4914 4915
{
    LIMITED_METHOD_CONTRACT;

    //
    // Sanity check that the flags contain only these three values
    //
4916
    assert((flags & ~(GC_CALL_INTERIOR|GC_CALL_PINNED)) == 0);
4917 4918 4919 4920 4921 4922 4923

    //
    // Sanity check that GC_CALL_INTERIOR FLAG is set
    //
    assert(flags & GC_CALL_INTERIOR);

#if !defined(DACCESS_COMPILE)
4924 4925 4926 4927 4928 4929

    //
    // Sanity check the stack scan limit
    //
    assert(sc->stack_limit != 0);

4930 4931
    // Note that the base is at a higher address than the limit, since the stack
    // grows downwards.
4932 4933
    // To check whether the object is in the stack or not, we also need to check the sc->stack_limit.
    // The reason is that on Unix, the stack size can be unlimited. In such case, the system can
4934
    // shrink the current reserved stack space. That causes the real limit of the stack to move up and
4935 4936 4937
    // the range can be reused for other purposes. But the sc->stack_limit is stable during the scan.
    // Even on Windows, we care just about the stack above the stack_limit.
    if ((sc->thread_under_crawl->IsAddressInStack(*ppObj)) && (PTR_TO_TADDR(*ppObj) >= sc->stack_limit))
4938 4939 4940
    {
        return;
    }
4941

4942 4943 4944 4945 4946 4947 4948 4949
    if (sc->promotion)
    {
        LoaderAllocator*pLoaderAllocator = LoaderAllocator::GetAssociatedLoaderAllocator_Unsafe(PTR_TO_TADDR(*ppObj));
        if (pLoaderAllocator != NULL)
        {
            GcReportLoaderAllocator(fn, sc, pLoaderAllocator);
        }
    }
4950 4951 4952 4953 4954
#endif // !defined(DACCESS_COMPILE)

    (*fn) (ppObj, sc, flags);
}

4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976
class ByRefPointerOffsetsReporter
{
    promote_func* _fn;
    ScanContext* _sc;
    PTR_VOID _src;

    void Report(SIZE_T pointerOffset)
    {
        WRAPPER_NO_CONTRACT;
        PTR_PTR_Object fieldRef = dac_cast<PTR_PTR_Object>(PTR_BYTE(_src) + pointerOffset);
        (*_fn)(fieldRef, _sc, GC_CALL_INTERIOR);
    }

public:
    ByRefPointerOffsetsReporter(promote_func* fn, ScanContext* sc, PTR_VOID pSrc)
        : _fn{fn}
        , _sc{sc}
        , _src{pSrc}
    {
        WRAPPER_NO_CONTRACT;
    }

4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992
    void Find(FieldDesc* pFD, SIZE_T baseOffset)
    {
        if (pFD->GetFieldType() == ELEMENT_TYPE_VALUETYPE)
        {
            PTR_MethodTable pFieldMT = pFD->GetApproxFieldTypeHandleThrowing().AsMethodTable();
            if (pFieldMT->IsByRefLike())
            {
                Find(pFieldMT, baseOffset + pFD->GetOffset());
            }
        }
        else if (pFD->IsByRef())
        {
            Report(baseOffset + pFD->GetOffset());
        }
    }

4993 4994 4995 4996 4997 4998
    void Find(PTR_MethodTable pMT, SIZE_T baseOffset)
    {
        WRAPPER_NO_CONTRACT;
        _ASSERTE(pMT != nullptr);
        _ASSERTE(pMT->IsByRefLike());

4999
        bool isValArray = pMT->GetClass()->IsInlineArray();
5000 5001 5002
        ApproxFieldDescIterator fieldIterator(pMT, ApproxFieldDescIterator::INSTANCE_FIELDS);
        for (FieldDesc* pFD = fieldIterator.Next(); pFD != NULL; pFD = fieldIterator.Next())
        {
5003
            if (isValArray)
5004
            {
5005 5006 5007 5008
                _ASSERTE(pFD->GetOffset() == 0);
                DWORD elementSize = pFD->GetSize();
                DWORD totalSize = pMT->GetNumInstanceFieldBytes();
                for (DWORD offset = 0; offset < totalSize; offset += elementSize)
5009
                {
5010
                    Find(pFD, baseOffset + offset);
5011 5012
                }
            }
5013
            else
5014
            {
5015
                Find(pFD, baseOffset);
5016 5017 5018 5019 5020
            }
        }
    }
};

5021 5022 5023
void ReportPointersFromValueType(promote_func *fn, ScanContext *sc, PTR_MethodTable pMT, PTR_VOID pSrc)
{
    WRAPPER_NO_CONTRACT;
5024

5025 5026
    if (pMT->IsByRefLike())
    {
5027 5028
        ByRefPointerOffsetsReporter reporter{fn, sc, pSrc};
        reporter.Find(pMT, 0 /* baseOffset */);
5029
    }
5030

5031 5032
    if (!pMT->ContainsPointers())
        return;
5033

5034 5035 5036 5037 5038 5039 5040 5041 5042 5043
    CGCDesc* map = CGCDesc::GetCGCDescFromMT(pMT);
    CGCDescSeries* cur = map->GetHighestSeries();
    CGCDescSeries* last = map->GetLowestSeries();
    DWORD size = pMT->GetBaseSize();
    _ASSERTE(cur >= last);

    do
    {
        // offset to embedded references in this series must be
        // adjusted by the VTable pointer, when in the unboxed state.
5044
        size_t offset = cur->GetSeriesOffset() - TARGET_POINTER_SIZE;
5045
        PTR_OBJECTREF srcPtr = dac_cast<PTR_OBJECTREF>(PTR_BYTE(pSrc) + offset);
5046 5047 5048
        PTR_OBJECTREF srcPtrStop = dac_cast<PTR_OBJECTREF>(PTR_BYTE(srcPtr) + cur->GetSeriesSize() + size);
        while (srcPtr < srcPtrStop)
        {
5049
            (*fn)(dac_cast<PTR_PTR_Object>(srcPtr), sc, 0);
5050
            srcPtr = (PTR_OBJECTREF)(PTR_BYTE(srcPtr) + TARGET_POINTER_SIZE);
5051 5052
        }
        cur--;
5053 5054 5055
    } while (cur >= last);
}

5056 5057 5058
void ReportPointersFromValueTypeArg(promote_func *fn, ScanContext *sc, PTR_MethodTable pMT, ArgDestination *pSrc)
{
    WRAPPER_NO_CONTRACT;
5059

5060
    if (!pMT->ContainsPointers() && !pMT->IsByRefLike())
5061
    {
5062
        return;
5063
    }
5064

5065
#if defined(UNIX_AMD64_ABI)
5066
    if (pSrc->IsStructPassedInRegs())
5067
    {
5068
        pSrc->ReportPointersFromStructInRegisters(fn, sc, pMT->GetNumInstanceFieldBytes());
5069 5070
        return;
    }
C
Carol Eidt 已提交
5071
#endif // UNIX_AMD64_ABI
5072 5073 5074 5075

    ReportPointersFromValueType(fn, sc, pMT, pSrc->GetDestinationAddress());
}

5076 5077 5078 5079
//------------------------------------------------------------------
// Perform type-specific GC promotion on the value (based upon the
// last type retrieved by NextArg()).
//------------------------------------------------------------------
5080
VOID MetaSig::GcScanRoots(ArgDestination *pValue,
5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096
                          promote_func *fn,
                          ScanContext* sc,
                          promote_carefully_func *fnc)
{

    CONTRACTL
    {
        INSTANCE_CHECK;
        if (FORBIDGC_LOADER_USE_ENABLED()) NOTHROW; else THROWS;
        if (FORBIDGC_LOADER_USE_ENABLED()) GC_NOTRIGGER; else GC_TRIGGERS;
        if (FORBIDGC_LOADER_USE_ENABLED()) FORBID_FAULT; else { INJECT_FAULT(COMPlusThrowOM()); }
        MODE_ANY;
    }
    CONTRACTL_END


5097
    PTR_PTR_Object pArgPtr = (PTR_PTR_Object)pValue->GetDestinationAddress();
5098 5099 5100 5101 5102 5103 5104
    if (fnc == NULL)
        fnc = &PromoteCarefully;

    TypeHandle thValueType;
    CorElementType  etype = m_pLastType.PeekElemTypeNormalized(m_pModule, &m_typeContext, &thValueType);

    _ASSERTE(etype >= 0 && etype < ELEMENT_TYPE_MAX);
5105

5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122
#ifdef _DEBUG
    PTR_Object pOldLocation;
#endif

    switch (gElementTypeInfo[etype].m_gc)
    {
        case TYPE_GC_NONE:
            // do nothing
            break;

        case TYPE_GC_REF:
            LOG((LF_GC, INFO3,
                 "        Argument at" FMT_ADDR "causes promotion of " FMT_OBJECT "\n",
                 DBG_ADDR(pArgPtr), DBG_ADDR(*pArgPtr) ));
#ifdef _DEBUG
            pOldLocation = *pArgPtr;
#endif
5123
            (*fn)(pArgPtr, sc, 0 );
5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150

            // !!! Do not cast to (OBJECTREF*)
            // !!! If we are in the relocate phase, we may have updated root,
            // !!! but we have not moved the GC heap yet.
            // !!! The root then points to bad locations until GC is done.
#ifdef LOGGING
            if (pOldLocation != *pArgPtr)
                LOG((LF_GC, INFO3,
                     "        Relocating from" FMT_ADDR "to " FMT_ADDR "\n",
                     DBG_ADDR(pOldLocation), DBG_ADDR(*pArgPtr)));
#endif
            break;

        case TYPE_GC_BYREF:
#ifdef ENREGISTERED_PARAMTYPE_MAXSIZE
        case_TYPE_GC_BYREF:
#endif // ENREGISTERED_PARAMTYPE_MAXSIZE

            // value is an interior pointer
            LOG((LF_GC, INFO3,
                 "        Argument at" FMT_ADDR "causes promotion of interior pointer" FMT_ADDR "\n",
                 DBG_ADDR(pArgPtr), DBG_ADDR(*pArgPtr) ));

#ifdef _DEBUG
            pOldLocation = *pArgPtr;
#endif

5151
            (*fnc)(fn, pArgPtr, sc, GC_CALL_INTERIOR);
5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165

            // !!! Do not cast to (OBJECTREF*)
            // !!! If we are in the relocate phase, we may have updated root,
            // !!! but we have not moved the GC heap yet.
            // !!! The root then points to bad locations until GC is done.
#ifdef LOGGING
            if (pOldLocation != *pArgPtr)
                LOG((LF_GC, INFO3,
                     "        Relocating from" FMT_ADDR "to " FMT_ADDR "\n",
                     DBG_ADDR(pOldLocation), DBG_ADDR(*pArgPtr)));
#endif
            break;

        case TYPE_GC_OTHER:
5166
            // value is a ValueClass, generic type parameter
5167 5168 5169 5170 5171
            // See one of the go_through_object() macros in
            // gc.cpp for the code we are emulating here.  But note that the GCDesc
            // for value classes describes the state of the instance in its boxed
            // state.  Here we are dealing with an unboxed instance, so we must adjust
            // the object size and series offsets appropriately.
5172
            _ASSERTE(etype == ELEMENT_TYPE_VALUETYPE || etype == ELEMENT_TYPE_TYPEDBYREF);
5173 5174 5175 5176 5177 5178 5179 5180 5181 5182
            {
                PTR_MethodTable pMT = thValueType.AsMethodTable();

#ifdef ENREGISTERED_PARAMTYPE_MAXSIZE
                if (ArgIterator::IsArgPassedByRef(thValueType))
                {
                    goto case_TYPE_GC_BYREF;
                }
#endif // ENREGISTERED_PARAMTYPE_MAXSIZE

5183
                ReportPointersFromValueTypeArg(fn, sc, pMT, pValue);
5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217
            }
            break;

        default:
            _ASSERTE(0); // can't get here.
    }
}


#ifndef DACCESS_COMPILE

void MetaSig::EnsureSigValueTypesLoaded(MethodDesc *pMD)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        INJECT_FAULT(COMPlusThrowOM());
        MODE_ANY;
    }
    CONTRACTL_END

    SigTypeContext typeContext(pMD);

    Module * pModule = pMD->GetModule();

    // The signature format is approximately:
    // CallingConvention   NumberOfArguments    ReturnType   Arg1  ...
    // There is also a blob length at pSig-1.
    SigPointer ptr(pMD->GetSig());

    // Skip over calling convention.
    IfFailThrowBF(ptr.GetCallingConv(NULL), BFA_BAD_SIGNATURE, pModule);

5218
    uint32_t numArgs = 0;
5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256
    IfFailThrowBF(ptr.GetData(&numArgs), BFA_BAD_SIGNATURE, pModule);

    // Force a load of value type arguments.
    for(ULONG i=0; i <= numArgs; i++)
    {
        ptr.PeekElemTypeNormalized(pModule,&typeContext);
        // Move to next argument token.
        IfFailThrowBF(ptr.SkipExactlyOne(), BFA_BAD_SIGNATURE, pModule);
    }
}

// this walks the sig and checks to see if all  types in the sig can be loaded

// This is used by ComCallableWrapper to give good error reporting
/*static*/
void MetaSig::CheckSigTypesCanBeLoaded(MethodDesc * pMD)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        INJECT_FAULT(COMPlusThrowOM());
        MODE_ANY;
    }
    CONTRACTL_END

    SigTypeContext typeContext(pMD);

    Module * pModule = pMD->GetModule();

    // The signature format is approximately:
    // CallingConvention   NumberOfArguments    ReturnType   Arg1  ...
    // There is also a blob length at pSig-1.
    SigPointer ptr(pMD->GetSig());

    // Skip over calling convention.
    IfFailThrowBF(ptr.GetCallingConv(NULL), BFA_BAD_SIGNATURE, pModule);

5257
    uint32_t numArgs = 0;
5258 5259 5260 5261 5262 5263
    IfFailThrowBF(ptr.GetData(&numArgs), BFA_BAD_SIGNATURE, pModule);

    // must do a skip so we skip any class tokens associated with the return type
    IfFailThrowBF(ptr.SkipExactlyOne(), BFA_BAD_SIGNATURE, pModule);

    // Force a load of value type arguments.
5264
    for(uint32_t i=0; i < numArgs; i++)
5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282
    {
        unsigned type = ptr.PeekElemTypeNormalized(pModule,&typeContext);
        if (type == ELEMENT_TYPE_VALUETYPE || type == ELEMENT_TYPE_CLASS)
        {
            ptr.GetTypeHandleThrowing(pModule, &typeContext);
        }
        // Move to next argument token.
        IfFailThrowBF(ptr.SkipExactlyOne(), BFA_BAD_SIGNATURE, pModule);
    }
}

#endif // #ifndef DACCESS_COMPILE

CorElementType MetaSig::GetReturnTypeNormalized(TypeHandle * pthValueType) const
{
    WRAPPER_NO_CONTRACT;
    SUPPORTS_DAC;

5283
    if ((m_flags & SIG_RET_TYPE_INITTED) &&
5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329
        ((pthValueType == NULL) || (m_corNormalizedRetType !=  ELEMENT_TYPE_VALUETYPE)))
    {
        return( m_corNormalizedRetType );
    }

    MetaSig * pSig = const_cast<MetaSig *>(this);
    pSig->m_corNormalizedRetType = m_pRetType.PeekElemTypeNormalized(m_pModule, &m_typeContext, pthValueType);
    pSig->m_flags |= SIG_RET_TYPE_INITTED;

    return( m_corNormalizedRetType );
}

BOOL MetaSig::IsObjectRefReturnType()
{
    WRAPPER_NO_CONTRACT;

    switch (GetReturnTypeNormalized())
        {
        case ELEMENT_TYPE_CLASS:
        case ELEMENT_TYPE_SZARRAY:
        case ELEMENT_TYPE_ARRAY:
        case ELEMENT_TYPE_STRING:
        case ELEMENT_TYPE_OBJECT:
        case ELEMENT_TYPE_VAR:
            return( TRUE );
        default:
            break;
        }
    return( FALSE );
}

CorElementType MetaSig::GetReturnType() const
{
    WRAPPER_NO_CONTRACT;
    return m_pRetType.PeekElemTypeClosed(GetModule(), &m_typeContext);
}

BOOL MetaSig::IsReturnTypeVoid() const
{
    WRAPPER_NO_CONTRACT;
    return (GetReturnType() == ELEMENT_TYPE_VOID);
}

#ifndef DACCESS_COMPILE

//---------------------------------------------------------------------------------------
5330
//
5331
// Substitution from a token (TypeDef and TypeRef have empty instantiation, TypeSpec gets it from MetaData).
5332
//
5333
Substitution::Substitution(
5334
    mdToken              parentTypeDefOrRefOrSpec,
5335
    ModuleBase *         pModule,
5336 5337 5338 5339
    const Substitution * pNext)
{
    LIMITED_METHOD_CONTRACT;

5340
    m_pModule = pModule;
5341 5342
    m_pNext = pNext;

5343
    if (IsNilToken(parentTypeDefOrRefOrSpec) ||
5344 5345 5346 5347 5348 5349 5350 5351
        (TypeFromToken(parentTypeDefOrRefOrSpec) != mdtTypeSpec))
    {
        return;
    }

    ULONG           cbSig;
    PCCOR_SIGNATURE pSig = NULL;
    if (FAILED(pModule->GetMDImport()->GetTypeSpecFromToken(
5352 5353
            parentTypeDefOrRefOrSpec,
            &pSig,
5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369
            &cbSig)))
    {
        return;
    }
    SigPointer sigptr = SigPointer(pSig, cbSig);
    CorElementType type;

    if (FAILED(sigptr.GetElemType(&type)))
        return;

    // The only kind of type specs that we recognise are instantiated types
    if (type != ELEMENT_TYPE_GENERICINST)
        return;

    if (FAILED(sigptr.GetElemType(&type)))
        return;
5370

5371 5372 5373
    if (type != ELEMENT_TYPE_CLASS)
        return;

5374
    /* mdToken genericTok = */
5375 5376
    if (FAILED(sigptr.GetToken(NULL)))
        return;
5377
    /* DWORD ntypars = */
5378 5379 5380 5381 5382 5383 5384
    if (FAILED(sigptr.GetData(NULL)))
        return;

    m_sigInst = sigptr;
} // Substitution::Substitution

//---------------------------------------------------------------------------------------
5385 5386
//
void
5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403
Substitution::CopyToArray(
    Substitution * pTarget) const
{
    LIMITED_METHOD_CONTRACT;

    const Substitution * pChain = this;
    DWORD i = 0;
    for (; pChain != NULL; pChain = pChain->GetNext())
    {
        CONSISTENCY_CHECK(CheckPointer(pChain->GetModule()));

        Substitution * pNext = (pChain->GetNext() != NULL) ? &pTarget[i + 1] : NULL;
        pTarget[i++] = Substitution(pChain->GetModule(), pChain->GetInst(), pNext);
    }
}

//---------------------------------------------------------------------------------------
5404 5405 5406 5407 5408
//
DWORD Substitution::GetLength() const
{
    LIMITED_METHOD_CONTRACT;
    DWORD res = 0;
5409 5410
    for (const Substitution * pChain = this; pChain != NULL; pChain = pChain->m_pNext)
    {
5411
        res++;
5412
    }
5413
    return res;
5414 5415 5416
}

//---------------------------------------------------------------------------------------
5417 5418
//
void Substitution::DeleteChain()
5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429
{
    LIMITED_METHOD_CONTRACT;
    if (m_pNext != NULL)
    {
        ((Substitution *)m_pNext)->DeleteChain();
    }
    delete this;
}

#endif // #ifndef DACCESS_COMPILE
//---------------------------------------------------------------------------------------
5430
//
5431
// static
5432
TokenPairList TokenPairList::AdjustForTypeSpec(TokenPairList *pTemplate, ModuleBase *pTypeSpecModule, PCCOR_SIGNATURE pTypeSpecSig, DWORD cbTypeSpecSig)
5433 5434 5435 5436 5437 5438
{
    CONTRACTL
    {
        THROWS;
        MODE_ANY;
        GC_TRIGGERS;
5439
    }
5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460
    CONTRACTL_END

    TokenPairList result(pTemplate);

    if (InTypeEquivalenceForbiddenScope(&result))
    {
        // it cannot get any worse
        return result;
    }

    SigParser sig(pTypeSpecSig, cbTypeSpecSig);
    CorElementType elemType;

    IfFailThrow(sig.GetElemType(&elemType));
    if (elemType != ELEMENT_TYPE_GENERICINST)
    {
        // we don't care about anything else than generic instantiations
        return result;
    }

    IfFailThrow(sig.GetElemType(&elemType));
5461

5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500
    if (elemType == ELEMENT_TYPE_CLASS)
    {
        mdToken tkType;
        IfFailThrow(sig.GetToken(&tkType));

        Module *pModule;
        if (!ClassLoader::ResolveTokenToTypeDefThrowing(pTypeSpecModule,
                                                        tkType,
                                                        &pModule,
                                                        &tkType))
        {
            // we couldn't prove otherwise so assume that this is not an interface
            result.m_bInTypeEquivalenceForbiddenScope = TRUE;
        }
        else
        {
            DWORD dwAttrType;
            IfFailThrow(pModule->GetMDImport()->GetTypeDefProps(tkType, &dwAttrType, NULL));

            result.m_bInTypeEquivalenceForbiddenScope = !IsTdInterface(dwAttrType);
        }
    }
    else
    {
        _ASSERTE(elemType == ELEMENT_TYPE_VALUETYPE);
        result.m_bInTypeEquivalenceForbiddenScope = TRUE;
    }

    return result;
}

// static
TokenPairList TokenPairList::AdjustForTypeEquivalenceForbiddenScope(TokenPairList *pTemplate)
{
    CONTRACTL
    {
        THROWS;
        MODE_ANY;
        GC_TRIGGERS;
5501
    }
5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518
    CONTRACTL_END

    TokenPairList result(pTemplate);
    result.m_bInTypeEquivalenceForbiddenScope = TRUE;
    return result;
}

// TRUE if the two TypeDefs have the same layout and field marshal information.
BOOL CompareTypeLayout(mdToken tk1, mdToken tk2, Module *pModule1, Module *pModule2)
{
    CONTRACTL
    {
        THROWS;
        MODE_ANY;
        GC_NOTRIGGER;
        PRECONDITION(TypeFromToken(tk1) == mdtTypeDef);
        PRECONDITION(TypeFromToken(tk2) == mdtTypeDef);
5519
    }
5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556
    CONTRACTL_END

    DWORD dwAttr1, dwAttr2;
    IMDInternalImport *pInternalImport1 = pModule1->GetMDImport();
    IMDInternalImport *pInternalImport2 = pModule2->GetMDImport();

    IfFailThrow(pInternalImport1->GetTypeDefProps(tk1, &dwAttr1, NULL));
    IfFailThrow(pInternalImport2->GetTypeDefProps(tk2, &dwAttr2, NULL));

    // we need both to have sequential or explicit layout
    BOOL fExplicitLayout = FALSE;
    if (IsTdSequentialLayout(dwAttr1))
    {
        if (!IsTdSequentialLayout(dwAttr2))
            return FALSE;
    }
    else if (IsTdExplicitLayout(dwAttr1))
    {
        if (!IsTdExplicitLayout(dwAttr2))
            return FALSE;

        fExplicitLayout = TRUE;
    }
    else
    {
        return FALSE;
    }

    // they must have the same charset
    if ((dwAttr1 & tdStringFormatMask) != (dwAttr2 & tdStringFormatMask))
        return FALSE;

    // they must have the same packing
    DWORD dwPackSize1, dwPackSize2;
    HRESULT hr1 = pInternalImport1->GetClassPackSize(tk1, &dwPackSize1);
    HRESULT hr2 = pInternalImport2->GetClassPackSize(tk2, &dwPackSize2);

5557
    if (hr1 == CLDB_E_RECORD_NOTFOUND)
5558 5559 5560 5561
        dwPackSize1 = 0;
    else
        IfFailThrow(hr1);

5562
    if (hr2 == CLDB_E_RECORD_NOTFOUND)
5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574
        dwPackSize2 = 0;
    else
        IfFailThrow(hr2);

    if (dwPackSize1 != dwPackSize2)
        return FALSE;

    // they must have the same explicit size
    DWORD dwTotalSize1, dwTotalSize2;
    hr1 = pInternalImport1->GetClassTotalSize(tk1, &dwTotalSize1);
    hr2 = pInternalImport2->GetClassTotalSize(tk2, &dwTotalSize2);

5575
    if (hr1 == CLDB_E_RECORD_NOTFOUND)
5576 5577 5578 5579
        dwTotalSize1 = 0;
    else
        IfFailThrow(hr1);

5580
    if (hr2 == CLDB_E_RECORD_NOTFOUND)
5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637
        dwTotalSize2 = 0;
    else
        IfFailThrow(hr2);

    if (dwTotalSize1 != dwTotalSize2)
        return FALSE;

    // same offsets, same field marshal
    HENUMInternalHolder hFieldEnum1(pInternalImport1);
    HENUMInternalHolder hFieldEnum2(pInternalImport2);

    hFieldEnum1.EnumInit(mdtFieldDef, tk1);
    hFieldEnum2.EnumInit(mdtFieldDef, tk2);

    mdToken tkField1, tkField2;

    while (hFieldEnum1.EnumNext(&tkField1))
    {
        if (!hFieldEnum2.EnumNext(&tkField2))
            return FALSE;

        // check for same offsets
        if (fExplicitLayout)
        {
            ULONG uOffset1, uOffset2;
            IfFailThrow(pInternalImport1->GetFieldOffset(tkField1, &uOffset1));
            IfFailThrow(pInternalImport2->GetFieldOffset(tkField2, &uOffset2));

            if (uOffset1 != uOffset2)
                return FALSE;
        }

        // check for same field marshal
        DWORD dwAttrField1, dwAttrField2;
        IfFailThrow(pInternalImport1->GetFieldDefProps(tkField1, &dwAttrField1));
        IfFailThrow(pInternalImport2->GetFieldDefProps(tkField2, &dwAttrField2));

        if (IsFdHasFieldMarshal(dwAttrField1) != IsFdHasFieldMarshal(dwAttrField2))
            return FALSE;

        if (IsFdHasFieldMarshal(dwAttrField1))
        {
            // both fields have field marshal info - make sure it's same
            PCCOR_SIGNATURE pNativeSig1, pNativeSig2;
            ULONG cbNativeSig1, cbNativeSig2;

            IfFailThrow(pInternalImport1->GetFieldMarshal(tkField1, &pNativeSig1, &cbNativeSig1));
            IfFailThrow(pInternalImport2->GetFieldMarshal(tkField2, &pNativeSig2, &cbNativeSig2));

            // just check if the blobs are identical
            if (cbNativeSig1 != cbNativeSig2 || memcmp(pNativeSig1, pNativeSig2, cbNativeSig1) != 0)
                return FALSE;
        }
    }

    return TRUE;
}