repo_name
stringclasses
6 values
pr_number
int64
512
78.9k
pr_title
stringlengths
3
144
pr_description
stringlengths
0
30.3k
author
stringlengths
2
21
date_created
timestamp[ns, tz=UTC]
date_merged
timestamp[ns, tz=UTC]
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
17
30.4k
filepath
stringlengths
9
210
before_content
stringlengths
0
112M
after_content
stringlengths
0
112M
label
int64
-1
1
dotnet/runtime
66,474
Update repo CMake configuration to target /W4 by default
Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
AaronRobinsonMSFT
2022-03-10T20:20:31Z
2022-03-11T04:59:21Z
ba5207b0f4054fe8963fc3e87c2bd32907516961
5ce2b9f860f7a84c3059650bb67817d59d8f4953
Update repo CMake configuration to target /W4 by default. Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
./src/coreclr/vm/arm/armsinglestepper.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // // Emulate hardware single-step on ARM. // #include "common.h" #include "armsinglestepper.h" // // ITState methods. // ITState::ITState() { #ifdef _DEBUG m_fValid = false; #endif } // Must call Get() (or Init()) to initialize this instance from a specific context before calling any other // (non-static) method. void ITState::Get(T_CONTEXT *pCtx) { m_bITState = (BYTE)((BitExtract((WORD)pCtx->Cpsr, 15, 10) << 2) | BitExtract((WORD)(pCtx->Cpsr >> 16), 10, 9)); #ifdef _DEBUG m_fValid = true; #endif } // Must call Init() (or Get()) to initialize this instance from a raw byte value before calling any other // (non-static) method. void ITState::Init(BYTE bState) { m_bITState = bState; #ifdef _DEBUG m_fValid = true; #endif } // Does the current IT state indicate we're executing within an IT block? bool ITState::InITBlock() { _ASSERTE(m_fValid); return (m_bITState & 0x1f) != 0; } // Only valid within an IT block. Returns the condition code which will be evaluated for the current // instruction. DWORD ITState::CurrentCondition() { _ASSERTE(m_fValid); _ASSERTE(InITBlock()); return BitExtract(m_bITState, 7, 4); } // Transition the IT state to that for the next instruction. void ITState::Advance() { _ASSERTE(m_fValid); if ((m_bITState & 0x7) == 0) m_bITState = 0; else m_bITState = (m_bITState & 0xe0) | ((m_bITState << 1) & 0x1f); } // Write the current IT state back into the given context. void ITState::Set(T_CONTEXT *pCtx) { _ASSERTE(m_fValid); Clear(pCtx); pCtx->Cpsr |= BitExtract(m_bITState, 1, 0) << 25; pCtx->Cpsr |= BitExtract(m_bITState, 7, 2) << 10; } // Clear IT state (i.e. force execution to be outside of an IT block) in the given context. /* static */ void ITState::Clear(T_CONTEXT *pCtx) { pCtx->Cpsr &= 0xf9ff03ff; } // // ArmSingleStepper methods. // ArmSingleStepper::ArmSingleStepper() : m_originalPc(0), m_targetPc(0), m_rgCode(0), m_state(Disabled), m_fEmulatedITInstruction(false), m_fRedirectedPc(false), m_fEmulate(false), m_fBypass(false), m_fSkipIT(false) { m_opcodes[0] = 0; m_opcodes[1] = 0; } ArmSingleStepper::~ArmSingleStepper() { #if !defined(DACCESS_COMPILE) SystemDomain::GetGlobalLoaderAllocator()->GetExecutableHeap()->BackoutMem(m_rgCode, kMaxCodeBuffer * sizeof(WORD)); #endif } void ArmSingleStepper::Init() { #if !defined(DACCESS_COMPILE) if (m_rgCode == NULL) { m_rgCode = (WORD *)(void *)SystemDomain::GetGlobalLoaderAllocator()->GetExecutableHeap()->AllocMem(S_SIZE_T(kMaxCodeBuffer * sizeof(WORD))); } #endif } // Given the context with which a thread will be resumed, modify that context such that resuming the thread // will execute a single instruction before raising an EXCEPTION_BREAKPOINT. The thread context must be // cleaned up via the Fixup method below before any further exception processing can occur (at which point the // caller can behave as though EXCEPTION_SINGLE_STEP was raised). void ArmSingleStepper::Enable() { _ASSERTE(m_state != Applied); if (m_state == Enabled) { // We allow single-stepping to be enabled multiple times before the thread is resumed, but we require // that the thread state is the same in all cases (i.e. additional step requests are treated as // no-ops). _ASSERTE(!m_fBypass); _ASSERTE(m_opcodes[0] == 0); _ASSERTE(m_opcodes[1] == 0); return; } LOG((LF_CORDB, LL_INFO100000, "ArmSingleStepper::Enable\n")); m_fBypass = false; m_opcodes[0] = 0; m_opcodes[1] = 0; m_state = Enabled; } void ArmSingleStepper::Bypass(DWORD ip, WORD opcode1, WORD opcode2) { _ASSERTE(m_state != Applied); if (m_state == Enabled) { // We allow single-stepping to be enabled multiple times before the thread is resumed, but we require // that the thread state is the same in all cases (i.e. additional step requests are treated as // no-ops). if (m_fBypass) { _ASSERTE(m_opcodes[0] == opcode1); _ASSERTE(m_opcodes[1] == opcode2); _ASSERTE(m_originalPc == ip); return; } } LOG((LF_CORDB, LL_INFO100000, "ArmSingleStepper::Bypass(pc=%x, opcode=%x %x)\n", (DWORD)ip, (DWORD)opcode1, (DWORD)opcode2)); m_fBypass = true; m_originalPc = ip; m_opcodes[0] = opcode1; m_opcodes[1] = opcode2; m_state = Enabled; } void ArmSingleStepper::Apply(T_CONTEXT *pCtx) { if (m_rgCode == NULL) { Init(); // OOM. We will simply ignore the single step. if (m_rgCode == NULL) return; } _ASSERTE(pCtx != NULL); if (!m_fBypass) { DWORD pc = ((DWORD)pCtx->Pc) & ~THUMB_CODE; m_opcodes[0] = *(WORD*)pc; if (Is32BitInstruction( m_opcodes[0])) m_opcodes[1] = *(WORD*)(pc+2); } WORD opcode1 = m_opcodes[0]; WORD opcode2 = m_opcodes[1]; LOG((LF_CORDB, LL_INFO100000, "ArmSingleStepper::Apply(pc=%x, opcode=%x %x)\n", (DWORD)pCtx->Pc, (DWORD)opcode1, (DWORD)opcode2)); #ifdef _DEBUG // Make sure that we aren't trying to step through our own buffer. If this asserts, something is horribly // wrong with the debugging layer. Likely GetManagedStoppedCtx is retrieving a Pc that points to our // buffer, even though the single stepper is disabled. DWORD codestart = (DWORD)(DWORD_PTR)m_rgCode; DWORD codeend = codestart + (kMaxCodeBuffer * sizeof(WORD)); _ASSERTE((pCtx->Pc < codestart) || (pCtx->Pc >= codeend)); #endif // All stepping is simulated using a breakpoint instruction. Since other threads are not suspended while // we step, we avoid race conditions and other complexity by redirecting the thread into a thread-local // execution buffer. We can either copy the instruction we wish to step over into the buffer followed by a // breakpoint or we can emulate the instruction (which is useful for instruction that depend on the value // of the PC or that branch or call to an alternate location). Even in the emulation case we still // redirect execution into the buffer and insert a breakpoint; this simplifies our interface since the // rest of the runtime is not set up to expect single stepping to occur inline. Instead there is always a // 1:1 relationship between setting the single-step mode and receiving an exception once the thread is // restarted. // // There are two parts to the emulation: // 1) In this method we either emulate the instruction (updating the input thread context as a result) or // copy the single instruction into the execution buffer. In both cases we copy a breakpoint into the // execution buffer as well then update the thread context to redirect execution into this buffer. // 2) In the runtime's first chance vectored exception handler we perform the necessary fixups to make // the exception look like the result of a single step. This includes resetting the PC to its correct // value (either the instruction following the stepped instruction or the target PC cached in this // object when we emulated an instruction that alters the PC). It also involves switching // EXCEPTION_BREAKPOINT to EXCEPTION_SINGLE_STEP. // // If we encounter an exception while emulating an instruction (currently this can only happen if we A/V // trying to read a value from memory) then we abandon emulation and fall back to the copy instruction // mechanism. When we run the execution buffer the exception should be raised and handled as normal (we // still peform context fixup in this case but we don't attempt to alter any exception code other than // EXCEPTION_BREAKPOINT to EXCEPTION_SINGLE_STEP). There is a very small timing window here where another // thread could alter memory protections to avoid the A/V when we run the instruction for real but the // liklihood of this happening (in managed code no less) is judged sufficiently small that it's not worth // the alternate solution (where we'd have to set the thread up to raise an exception with exactly the // right thread context). // // Matters are complicated by the ARM IT instruction (upto four following instructions are executed // conditionally based on a single condition or its negation). The issues are that the current instruction // may be rendered into a no-op or that a breakpoint immediately following the current instruction may not // be executed. To simplify matters we may modify the IT state to force our instructions to execute. We // cache the real state and re-apply it along with the rest of our fixups when handling the breakpoint // exception. Note that when executing general instructions we can't simply disable any IT state since // many instructions alter their behavior depending on whether they're executing within an IT block // (mostly it's used to determine whether these instructions set condition flags or not). // Cache thread's initial PC and IT state since we'll overwrite them as part of the emulation and we need // to get back to the correct values at fixup time. We also cache a target PC (set below) since some // instructions will set the PC directly or otherwise make it difficult for us to compute the final PC // from the original. We still need the original PC however since this is the one we'll use if an // exception (other than a breakpoint) occurs. _ASSERTE(!m_fBypass || (m_originalPc == pCtx->Pc)); m_originalPc = pCtx->Pc; m_originalITState.Get(pCtx); // By default assume the next PC is right after the current instruction. m_targetPc = m_originalPc + (Is32BitInstruction(opcode1) ? 4 : 2); m_fEmulate = false; // One more special case: if we attempt to single-step over an IT instruction it's easier to emulate this, // set the new IT state in m_originalITState and set a special flag that lets Fixup() know we don't need // to advance the state (this only works because we know IT will never raise an exception so we don't need // m_originalITState to store the real original IT state, though in truth a legal IT instruction cannot be // executed inside an IT block anyway). This flag (and m_originalITState) will be set inside TryEmulate() // as needed. m_fEmulatedITInstruction = false; m_fSkipIT = false; // There are three different scenarios we must deal with (listed in priority order). In all cases we will // redirect the thread to execute code from our buffer and end by raising a breakpoint exception: // 1) We're executing in an IT block and the current instruction doesn't meet the condition requirements. // We leave the state unchanged and in fixup will advance the PC to the next instruction slot. // 2) The current instruction either takes the PC as an input or modifies the PC in a non-trivial manner. // We can't easily run these instructions from the redirect buffer so we emulate their effect (i.e. // update the current context in the same way as executing the instruction would). The breakpoint // fixup logic will restore the PC to the real resultant PC we cache in m_targetPc. // 3) For all other cases (including emulation cases where we aborted due to a memory fault) we copy the // single instruction into the redirect buffer for execution followed by a breakpoint (once we regain // control in the breakpoint fixup logic we can then reset the PC to its proper location. DWORD idxNextInstruction = 0; ExecutableWriterHolder<WORD> codeWriterHolder(m_rgCode, kMaxCodeBuffer * sizeof(m_rgCode[0])); if (m_originalITState.InITBlock() && !ConditionHolds(pCtx, m_originalITState.CurrentCondition())) { LOG((LF_CORDB, LL_INFO100000, "ArmSingleStepper: Case 1: ITState::Clear;\n")); // Case 1: The current instruction is a no-op because due to the IT instruction. We've already set the // target PC to the next instruction slot. Disable the IT block since we want our breakpoint // to execute. We'll put the correct value back during fixup. ITState::Clear(pCtx); m_fSkipIT = true; codeWriterHolder.GetRW()[idxNextInstruction++] = kBreakpointOp; } else if (TryEmulate(pCtx, opcode1, opcode2, false)) { LOG((LF_CORDB, LL_INFO100000, "ArmSingleStepper: Case 2: Emulate\n")); // Case 2: Successfully emulated an instruction that reads or writes the PC. Cache the new target PC // so upon fixup we'll resume execution there rather than the following instruction. No need // to mess with IT state since we know the next instruction is scheduled to execute (we dealt // with the case where it wasn't above) and we're going to execute a breakpoint in that slot. m_targetPc = pCtx->Pc; m_fEmulate = true; // Set breakpoints to stop the execution. This will get us right back here. codeWriterHolder.GetRW()[idxNextInstruction++] = kBreakpointOp; codeWriterHolder.GetRW()[idxNextInstruction++] = kBreakpointOp; } else { LOG((LF_CORDB, LL_INFO100000, "ArmSingleStepper: Case 3: CopyInstruction. Is32Bit=%d\n", (DWORD)Is32BitInstruction(opcode1))); // Case 3: In all other cases copy the instruction to the buffer and we'll run it directly. If we're // in an IT block there could be up to three instructions following this one whose execution // is skipped. We could try to be clever here and either alter IT state to force the next // instruction to execute or calculate the how many filler instructions we need to insert // before we're guaranteed our breakpoint will be respected. But it's easier to just insert // three additional breakpoints here (code below will add the fourth) and that way we'll // guarantee one of them will be hit (we don't care which one -- the fixup code will update // the PC and IT state to make it look as though the CPU just executed the current // instruction). codeWriterHolder.GetRW()[idxNextInstruction++] = opcode1; if (Is32BitInstruction(opcode1)) codeWriterHolder.GetRW()[idxNextInstruction++] = opcode2; codeWriterHolder.GetRW()[idxNextInstruction++] = kBreakpointOp; codeWriterHolder.GetRW()[idxNextInstruction++] = kBreakpointOp; codeWriterHolder.GetRW()[idxNextInstruction++] = kBreakpointOp; } // Always terminate the redirection buffer with a breakpoint. codeWriterHolder.GetRW()[idxNextInstruction++] = kBreakpointOp; _ASSERTE(idxNextInstruction <= kMaxCodeBuffer); // Set the thread up so it will redirect to our buffer when execution resumes. pCtx->Pc = ((DWORD)(DWORD_PTR)m_rgCode) | THUMB_CODE; // Make sure the CPU sees the updated contents of the buffer. FlushInstructionCache(GetCurrentProcess(), m_rgCode, kMaxCodeBuffer * sizeof(m_rgCode[0])); // Done, set the state. m_state = Applied; } void ArmSingleStepper::Disable() { _ASSERTE(m_state != Applied); m_state = Disabled; } // When called in response to an exception (preferably in a first chance vectored handler before anyone else // has looked at the thread context) this method will (a) determine whether this exception was raised by a // call to Enable() above, in which case true will be returned and (b) perform final fixup of the thread // context passed in to complete the emulation of a hardware single step. Note that this routine must be // called even if the exception code is not EXCEPTION_BREAKPOINT since the instruction stepped might have // raised its own exception (e.g. A/V) and we still need to fix the thread context in this case. bool ArmSingleStepper::Fixup(T_CONTEXT *pCtx, DWORD dwExceptionCode) { #ifdef _DEBUG DWORD codestart = (DWORD)(DWORD_PTR)m_rgCode; DWORD codeend = codestart + (kMaxCodeBuffer * sizeof(WORD)); #endif // If we reach fixup, we should either be Disabled or Applied. If we reach here with Enabled it means // that the debugging layer Enabled the single stepper, but we never applied it to a CONTEXT. _ASSERTE(m_state != Enabled); // Nothing to do if the stepper is disabled on this thread. if (m_state == Disabled) { // We better not be inside our internal code buffer though. _ASSERTE((pCtx->Pc < codestart) || (pCtx->Pc >= codeend)); return false; } // Turn off the single stepper after we have executed one instruction. m_state = Disabled; // We should always have a PC somewhere in our redirect buffer. #ifdef _DEBUG _ASSERTE((pCtx->Pc >= codestart) && (pCtx->Pc < codeend)); #endif if (dwExceptionCode == EXCEPTION_BREAKPOINT) { // The single step went as planned. Set the PC back to its real value (either following the // instruction we stepped or the computed destination we cached after emulating an instruction that // modifies the PC). Advance the IT state from the value we cached before the single step (unless we // stepped an IT instruction itself, in which case m_originalITState holds the new state and we should // just set that). if (!m_fEmulate) { if (m_rgCode[0] != kBreakpointOp) { LOG((LF_CORDB, LL_INFO100000, "ArmSingleStepper::Fixup executed code, ip = %x\n", m_targetPc)); pCtx->Pc = m_targetPc; if (!m_fEmulatedITInstruction) m_originalITState.Advance(); m_originalITState.Set(pCtx); } else { if (m_fSkipIT) { // We needed to skip over an instruction due to a false condition in an IT block. LOG((LF_CORDB, LL_INFO100000, "ArmSingleStepper::Fixup skipped instruction due to IT\n")); pCtx->Pc = m_targetPc; _ASSERTE(!m_fEmulatedITInstruction); m_originalITState.Advance(); m_originalITState.Set(pCtx); } else { // We've hit a breakpoint in the code stream. We will return false here (which causes us to NOT // replace the breakpoint code with single step), and place the Pc back to the original Pc. The // debugger patch skipping code will move past this breakpoint. LOG((LF_CORDB, LL_INFO100000, "ArmSingleStepper::Fixup emulated breakpoint\n")); pCtx->Pc = m_originalPc; _ASSERTE(pCtx->Pc & THUMB_CODE); return false; } } } else { bool res = TryEmulate(pCtx, m_opcodes[0], m_opcodes[1], true); _ASSERTE(res); // We should always successfully emulate since we ran it through TryEmulate already. if (!m_fRedirectedPc) pCtx->Pc = m_targetPc; LOG((LF_CORDB, LL_INFO100000, "ArmSingleStepper::Fixup emulated, ip = %x\n", pCtx->Pc)); } } else { // The stepped instruction caused an exception. Reset the PC and IT state to their original values we // cached before stepping. (We should never seen this when stepping an IT instruction which overwrites // m_originalITState). _ASSERTE(!m_fEmulatedITInstruction); _ASSERTE(m_fEmulate == false); pCtx->Pc = m_originalPc; m_originalITState.Set(pCtx); LOG((LF_CORDB, LL_INFO100000, "ArmSingleStepper::Fixup hit exception pc = %x ex = %x\n", pCtx->Pc, dwExceptionCode)); } _ASSERTE(pCtx->Pc & THUMB_CODE); return true; } // Count the number of bits set in a DWORD. DWORD ArmSingleStepper::BitCount(DWORD dwValue) { // There are faster implementations but speed isn't critical here. DWORD cBits = 0; while (dwValue) { cBits += dwValue & 1; dwValue >>= 1; } return cBits; } // Return true if the given condition (C, N, Z or V) holds in the current context. #define GET_FLAG(pCtx, _flag) \ ((pCtx->Cpsr & (1 << APSR_##_flag)) != 0) // Returns true if the current context indicates the ARM condition specified holds. bool ArmSingleStepper::ConditionHolds(T_CONTEXT *pCtx, DWORD cond) { switch (cond) { case 0: // EQ (Z==1) return GET_FLAG(pCtx, Z); case 1: // NE (Z==0) return !GET_FLAG(pCtx, Z); case 2: // CS (C==1) return GET_FLAG(pCtx, C); case 3: // CC (C==0) return !GET_FLAG(pCtx, C); case 4: // MI (N==1) return GET_FLAG(pCtx, N); case 5: // PL (N==0) return !GET_FLAG(pCtx, N); case 6: // VS (V==1) return GET_FLAG(pCtx, V); case 7: // VC (V==0) return !GET_FLAG(pCtx, V); case 8: // HI (C==1 && Z==0) return GET_FLAG(pCtx, C) && !GET_FLAG(pCtx, Z); case 9: // LS (C==0 || Z==1) return !GET_FLAG(pCtx, C) || GET_FLAG(pCtx, Z); case 10: // GE (N==V) return GET_FLAG(pCtx, N) == GET_FLAG(pCtx, V); case 11: // LT (N!=V) return GET_FLAG(pCtx, N) != GET_FLAG(pCtx, V); case 12: // GT (Z==0 && N==V) return !GET_FLAG(pCtx, Z) && (GET_FLAG(pCtx, N) == GET_FLAG(pCtx, V)); case 13: // LE (Z==1 || N!=V) return GET_FLAG(pCtx, Z) || (GET_FLAG(pCtx, N) != GET_FLAG(pCtx, V)); case 14: // AL return true; case 15: _ASSERTE(!"Unsupported condition code: 15"); return false; default: // UNREACHABLE(); return false; } } // Get the current value of a register. PC (register 15) is always reported as the current instruction PC + 4 // as per the ARM architecture. DWORD ArmSingleStepper::GetReg(T_CONTEXT *pCtx, DWORD reg) { _ASSERTE(reg <= 15); if (reg == 15) return (m_originalPc + 4) & ~THUMB_CODE; return (&pCtx->R0)[reg]; } // Set the current value of a register. If the PC (register 15) is set then m_fRedirectedPc is set to true. void ArmSingleStepper::SetReg(T_CONTEXT *pCtx, DWORD reg, DWORD value) { _ASSERTE(reg <= 15); if (reg == 15) { value |= THUMB_CODE; m_fRedirectedPc = true; } (&pCtx->R0)[reg] = value; } // Attempt to read a 1, 2 or 4 byte value from memory, zero or sign extend it to a 4-byte value and place that // value into the buffer pointed at by pdwResult. Returns false if attempting to read the location caused a // fault. bool ArmSingleStepper::GetMem(DWORD *pdwResult, DWORD_PTR pAddress, DWORD cbSize, bool fSignExtend) { struct Param { DWORD *pdwResult; DWORD_PTR pAddress; DWORD cbSize; bool fSignExtend; bool bReturnValue; } param; param.pdwResult = pdwResult; param.pAddress = pAddress; param.cbSize = cbSize; param.fSignExtend = fSignExtend; param.bReturnValue = true; PAL_TRY(Param *, pParam, &param) { switch (pParam->cbSize) { case 1: *pParam->pdwResult = *(BYTE*)pParam->pAddress; if (pParam->fSignExtend && (*pParam->pdwResult & 0x00000080)) *pParam->pdwResult |= 0xffffff00; break; case 2: *pParam->pdwResult = *(WORD*)pParam->pAddress; if (pParam->fSignExtend && (*pParam->pdwResult & 0x00008000)) *pParam->pdwResult |= 0xffff0000; break; case 4: *pParam->pdwResult = *(DWORD*)pParam->pAddress; break; default: UNREACHABLE(); pParam->bReturnValue = false; } } PAL_EXCEPT(EXCEPTION_EXECUTE_HANDLER) { param.bReturnValue = false; } PAL_ENDTRY; return param.bReturnValue; } // Wrapper around GetMem above that will automatically return from TryEmulate() indicating the instruction // could not be emulated if we try to read memory and fail due to an exception. This logic works (i.e. we can // simply return without worrying whether we've already updated the thread context) due to the fact that we // either (a) read memory before updating any registers (the various LDR literal variants) or (b) update the // register list before the base register in LDM-like operations (and this should therefore be an idempotent // operation when we re-execute the instruction). If this ever changes we will have to store a copy of the // original context we can use to revert changes (it gets even more complex if we ever have to emulate an // instruction that writes memory). #define GET_MEM(_result, _addr, _size, _signextend) \ do { \ if (!GetMem((_result), (_addr), (_size), (_signextend))) \ return false; \ } while (false) // Implements the various LDM-style multi-register load instructions (these include POP). #define LDM(ctx, _base, _registerlist, _writeback, _ia) \ do { \ DWORD _pAddr = GetReg(ctx, _base); \ if (!(_ia)) \ _pAddr -= BitCount(_registerlist) * sizeof(void*); \ DWORD _pStartAddr = _pAddr; \ for (DWORD _i = 0; _i < 16; _i++) \ { \ if ((_registerlist) & (1 << _i)) \ { \ DWORD _tmpresult; \ GET_MEM(&_tmpresult, _pAddr, 4, false); \ SetReg(ctx, _i, _tmpresult); \ _pAddr += sizeof(void*); \ } \ } \ if (_writeback) \ SetReg(ctx, _base, (_ia) ? _pAddr : _pStartAddr); \ } while (false) // Parse the instruction whose first word is given in opcode1 (if the instruction is 32-bit TryEmulate will // fetch the second word using the value of the PC stored in the current context). If the instruction reads or // writes the PC or is the IT instruction then it will be emulated by updating the thread context // appropriately and true will be returned. If the instruction is not one of those cases (or it is but we // faulted trying to read memory during the emulation) no state is updated and false is returned instead. bool ArmSingleStepper::TryEmulate(T_CONTEXT *pCtx, WORD opcode1, WORD opcode2, bool execute) { LOG((LF_CORDB, LL_INFO100000, "ArmSingleStepper::TryEmulate(opcode=%x %x, execute=%s)\n", (DWORD)opcode1, (DWORD)opcode2, execute ? "true" : "false")); // Track whether instruction emulation wrote a modified PC. m_fRedirectedPc = false; // Track whether we successfully emulated an instruction. If we did and we didn't modify the PC (e.g. a // ADR instruction or a conditional branch not taken) then we'll need to explicitly set the PC to the next // instruction (since our caller expects that whenever we return true m_pCtx->Pc holds the next // instruction address). bool fEmulated = false; if (Is32BitInstruction(opcode1)) { if (((opcode1 & 0xfbff) == 0xf2af) && ((opcode2 & 0x8000) == 0x0000)) { // ADR.W : T2 if (execute) { DWORD Rd = BitExtract(opcode2, 11, 8); DWORD i = BitExtract(opcode1, 10, 10); DWORD imm3 = BitExtract(opcode2, 14, 12); DWORD imm8 = BitExtract(opcode2, 7, 0); SetReg(pCtx, Rd, (GetReg(pCtx, 15) & ~3) - ((i << 11) | (imm3 << 8) | imm8)); } fEmulated = true; } else if (((opcode1 & 0xfbff) == 0xf20f) && ((opcode2 & 0x8000) == 0x0000)) { // ADR.W : T3 if (execute) { DWORD Rd = BitExtract(opcode2, 11, 8); DWORD i = BitExtract(opcode1, 10, 10); DWORD imm3 = BitExtract(opcode2, 14, 12); DWORD imm8 = BitExtract(opcode2, 7, 0); SetReg(pCtx, Rd, (GetReg(pCtx, 15) & ~3) + ((i << 11) | (imm3 << 8) | imm8)); } fEmulated = true; } else if (((opcode1 & 0xf800) == 0xf000) && ((opcode2 & 0xd000) == 0x8000) && ((opcode1 & 0x0380) != 0x0380)) { // B.W : T3 if (execute) { DWORD S = BitExtract(opcode1, 10, 10); DWORD cond = BitExtract(opcode1, 9, 6); DWORD imm6 = BitExtract(opcode1, 5, 0); DWORD J1 = BitExtract(opcode2, 13, 13); DWORD J2 = BitExtract(opcode2, 11, 11); DWORD imm11 = BitExtract(opcode2, 10, 0); if (ConditionHolds(pCtx, cond) && execute) { DWORD disp = (S ? 0xfff00000 : 0) | (J2 << 19) | (J1 << 18) | (imm6 << 12) | (imm11 << 1); SetReg(pCtx, 15, GetReg(pCtx, 15) + disp); } } fEmulated = true; } else if (((opcode1 & 0xf800) == 0xf000) && ((opcode2 & 0xd000) == 0x9000)) { // B.W : T4 if (execute) { DWORD S = BitExtract(opcode1, 10, 10); DWORD imm10 = BitExtract(opcode1, 9, 0); DWORD J1 = BitExtract(opcode2, 13, 13); DWORD J2 = BitExtract(opcode2, 11, 11); DWORD imm11 = BitExtract(opcode2, 10, 0); DWORD I1 = (J1 ^ S) ^ 1; DWORD I2 = (J2 ^ S) ^ 1; DWORD disp = (S ? 0xff000000 : 0) | (I1 << 23) | (I2 << 22) | (imm10 << 12) | (imm11 << 1); SetReg(pCtx, 15, GetReg(pCtx, 15) + disp); } fEmulated = true; } else if (((opcode1 & 0xf800) == 0xf000) && ((opcode2 & 0xd000) == 0xd000)) { // BL (immediate) : T1 if (execute) { DWORD S = BitExtract(opcode1, 10, 10); DWORD imm10 = BitExtract(opcode1, 9, 0); DWORD J1 = BitExtract(opcode2, 13, 13); DWORD J2 = BitExtract(opcode2, 11, 11); DWORD imm11 = BitExtract(opcode2, 10, 0); DWORD I1 = (J1 ^ S) ^ 1; DWORD I2 = (J2 ^ S) ^ 1; SetReg(pCtx, 14, GetReg(pCtx, 15) | 1); DWORD disp = (S ? 0xff000000 : 0) | (I1 << 23) | (I2 << 22) | (imm10 << 12) | (imm11 << 1); SetReg(pCtx, 15, GetReg(pCtx, 15) + disp); } fEmulated = true; } else if (((opcode1 & 0xffd0) == 0xe890) && ((opcode2 & 0x2000) == 0x0000)) { // LDM.W : T2, POP.W : T2 if (execute) { DWORD W = BitExtract(opcode1, 5, 5); DWORD Rn = BitExtract(opcode1, 3, 0); DWORD registerList = opcode2; LDM(pCtx, Rn, registerList, W, true); fEmulated = true; } else { // We should only emulate this instruction if Pc is set if (opcode2 & (1<<15)) fEmulated = true; } } else if (((opcode1 & 0xffd0) == 0xe410) && ((opcode2 & 0x2000) == 0x0000)) { // LDMDB : T1 if (execute) { DWORD W = BitExtract(opcode1, 5, 5); DWORD Rn = BitExtract(opcode1, 3, 0); DWORD registerList = opcode2; LDM(pCtx, Rn, registerList, W, false); fEmulated = true; } else { // We should only emulate this instruction if Pc is set if (opcode2 & (1<<15)) fEmulated = true; } } else if (((opcode1 & 0xfff0) == 0xf8d0) && ((opcode1 & 0x000f) != 0x000f)) { // LDR.W (immediate): T3 DWORD Rt = BitExtract(opcode2, 15, 12); DWORD Rn = BitExtract(opcode1, 3, 0); if (execute) { DWORD imm12 = BitExtract(opcode2, 11, 0); DWORD value; GET_MEM(&value, GetReg(pCtx, Rn) + imm12, 4, false); SetReg(pCtx, Rt, value); fEmulated = true; } else { // We should only emulate this instruction if Pc is used if (Rt == 15 || Rn == 15) fEmulated = true; } } else if (((opcode1 & 0xfff0) == 0xf850) && ((opcode2 & 0x0800) == 0x0800) && ((opcode1 & 0x000f) != 0x000f)) { // LDR (immediate) : T4, POP : T3 DWORD Rn = BitExtract(opcode1, 3, 0); DWORD Rt = BitExtract(opcode2, 15, 12); if (execute) { DWORD P = BitExtract(opcode2, 10, 10); DWORD U = BitExtract(opcode2, 9, 9); DWORD W = BitExtract(opcode2, 8, 8); DWORD imm8 = BitExtract(opcode2, 7, 0); DWORD offset_addr = U ? GetReg(pCtx, Rn) + imm8 : GetReg(pCtx, Rn) - imm8; DWORD addr = P ? offset_addr : GetReg(pCtx, Rn); DWORD value; GET_MEM(&value, addr, 4, false); if (W) SetReg(pCtx, Rn, offset_addr); SetReg(pCtx, Rt, value); fEmulated = true; } else { // We should only emulate this instruction if Pc is used if (Rt == 15 || Rn == 15) fEmulated = true; } } else if (((opcode1 & 0xff7f) == 0xf85f)) { // LDR.W (literal) : T2 DWORD Rt = BitExtract(opcode2, 15, 12); if (execute) { DWORD U = BitExtract(opcode1, 7, 7); DWORD imm12 = BitExtract(opcode2, 11, 0); // This instruction always reads relative to R15/PC DWORD addr = GetReg(pCtx, 15) & ~3; addr = U ? addr + imm12 : addr - imm12; DWORD value; GET_MEM(&value, addr, 4, false); SetReg(pCtx, Rt, value); } // We should ALWAYS emulate this instruction, because this instruction // always reads the memory relative to PC fEmulated = true; } else if (((opcode1 & 0xfff0) == 0xf850) && ((opcode2 & 0x0fc0) == 0x0000) && ((opcode1 & 0x000f) != 0x000f)) { // LDR.W : T2 DWORD Rn = BitExtract(opcode1, 3, 0); DWORD Rt = BitExtract(opcode2, 15, 12); DWORD Rm = BitExtract(opcode2, 3, 0); if (execute) { DWORD imm2 = BitExtract(opcode2, 5, 4); DWORD addr = GetReg(pCtx, Rn) + (GetReg(pCtx, Rm) << imm2); DWORD value; GET_MEM(&value, addr, 4, false); SetReg(pCtx, Rt, value); fEmulated = true; } else { // We should only emulate this instruction if Pc is used if (Rt == 15 || Rn == 15 || Rm == 15) fEmulated = true; } } else if (((opcode1 & 0xff7f) == 0xf81f) && ((opcode2 & 0xf000) != 0xf000)) { // LDRB (literal) : T2 if (execute) { DWORD U = BitExtract(opcode1, 7, 7); DWORD Rt = BitExtract(opcode2, 15, 12); DWORD imm12 = BitExtract(opcode2, 11, 0); DWORD addr = (GetReg(pCtx, 15) & ~3); addr = U ? addr + imm12 : addr - imm12; DWORD value; GET_MEM(&value, addr, 1, false); SetReg(pCtx, Rt, value); } fEmulated = true; } else if (((opcode1 & 0xfe5f) == 0xe85f) && ((opcode1 & 0x0120) != 0x0000)) { // LDRD (literal) : T1 if (execute) { DWORD U = BitExtract(opcode1, 7, 7); DWORD Rt = BitExtract(opcode2, 15, 12); DWORD Rt2 = BitExtract(opcode2, 11, 8); DWORD imm8 = BitExtract(opcode2, 7, 0); DWORD addr = (GetReg(pCtx, 15) & ~3); addr = U ? addr + (imm8 << 2) : addr - (imm8 << 2); DWORD value1; GET_MEM(&value1, addr, 4, false); DWORD value2; GET_MEM(&value2, addr + 4, 4, false); SetReg(pCtx, Rt, value1); SetReg(pCtx, Rt2, value2); } fEmulated = true; } else if (((opcode1 & 0xff7f) == 0xf83f) && ((opcode2 & 0xf000) != 0xf000)) { // LDRH (literal) : T1 if (execute) { DWORD U = BitExtract(opcode1, 7, 7); DWORD Rt = BitExtract(opcode2, 15, 12); DWORD imm12 = BitExtract(opcode2, 11, 0); DWORD addr = (GetReg(pCtx, 15) & ~3); addr = U ? addr + imm12 : addr - imm12; DWORD value; GET_MEM(&value, addr, 2, false); SetReg(pCtx, Rt, value); } fEmulated = true; } else if (((opcode1 & 0xff7f) == 0xf91f) && ((opcode2 & 0xf000) != 0xf000)) { // LDRSB (literal) : T1 if (execute) { DWORD U = BitExtract(opcode1, 7, 7); DWORD Rt = BitExtract(opcode2, 15, 12); DWORD imm12 = BitExtract(opcode2, 11, 0); DWORD addr = (GetReg(pCtx, 15) & ~3); addr = U ? addr + imm12 : addr - imm12; DWORD value; GET_MEM(&value, addr, 1, true); SetReg(pCtx, Rt, value); } fEmulated = true; } else if (((opcode1 & 0xff7f) == 0xf53f) && ((opcode2 & 0xf000) != 0xf000)) { // LDRSH (literal) : T1 if (execute) { DWORD U = BitExtract(opcode1, 7, 7); DWORD Rt = BitExtract(opcode2, 15, 12); DWORD imm12 = BitExtract(opcode2, 11, 0); DWORD addr = (GetReg(pCtx, 15) & ~3); addr = U ? addr + imm12 : addr - imm12; DWORD value; GET_MEM(&value, addr, 2, true); SetReg(pCtx, Rt, value); } fEmulated = true; } else if (((opcode1 & 0xfff0) == 0xe8d0) && ((opcode2 & 0xffe0) == 0xf000)) { // TBB/TBH : T1 if (execute) { DWORD Rn = BitExtract(opcode1, 3, 0); DWORD H = BitExtract(opcode2, 4, 4); DWORD Rm = BitExtract(opcode2, 3, 0); DWORD addr = GetReg(pCtx, Rn); DWORD value; if (H) GET_MEM(&value, addr + (GetReg(pCtx, Rm) << 1), 2, false); else GET_MEM(&value, addr + GetReg(pCtx, Rm), 1, false); SetReg(pCtx, 15, GetReg(pCtx, 15) + (value << 1)); } fEmulated = true; } // If we emulated an instruction but didn't set the PC explicitly we have to do so now (in such cases // the next PC will always point directly after the instruction we just emulated). if (fEmulated && !m_fRedirectedPc) SetReg(pCtx, 15, GetReg(pCtx, 15)); } else { // Handle 16-bit instructions. if ((opcode1 & 0xf800) == 0xa000) { // ADR : T1 if (execute) { DWORD Rd = BitExtract(opcode1, 10, 8); DWORD imm8 = BitExtract(opcode1, 7, 0); SetReg(pCtx, Rd, (GetReg(pCtx, 15) & 3) + (imm8 << 2)); } fEmulated = true; } else if ((opcode1 & 0xff00) == 0x4400) { // A8.8.6 ADD (register, Thumb) : T2 DWORD Rm = BitExtract(opcode1, 6, 3); // We should only emulate this instruction if Pc is used if (Rm == 15) fEmulated = true; if (execute) { DWORD Rd = BitExtract(opcode1, 2, 0) | BitExtract(opcode1, 7, 7) << 3; SetReg(pCtx, Rd, GetReg(pCtx, Rm) + GetReg(pCtx, Rd)); } } else if (((opcode1 & 0xf000) == 0xd000) && ((opcode1 & 0x0f00) != 0x0e00)) { // B : T1 // We only emulate this instruction if we take the conditional // jump. If not we'll pass right over the jump and set the // target IP as normal. DWORD cond = BitExtract(opcode1, 11, 8); if (execute) { _ASSERTE(ConditionHolds(pCtx, cond)); DWORD imm8 = BitExtract(opcode1, 7, 0); DWORD disp = (imm8 << 1) | ((imm8 & 0x80) ? 0xffffff00 : 0); SetReg(pCtx, 15, GetReg(pCtx, 15) + disp); fEmulated = true; } else { if (ConditionHolds(pCtx, cond)) { fEmulated = true; } } } else if ((opcode1 & 0xf800) == 0xe000) { if (execute) { // B : T2 DWORD imm11 = BitExtract(opcode1, 10, 0); DWORD disp = (imm11 << 1) | ((imm11 & 0x400) ? 0xfffff000 : 0); SetReg(pCtx, 15, GetReg(pCtx, 15) + disp); } fEmulated = true; } else if ((opcode1 & 0xff87) == 0x4780) { // BLX (register) : T1 if (execute) { DWORD Rm = BitExtract(opcode1, 6, 3); DWORD addr = GetReg(pCtx, Rm); SetReg(pCtx, 14, (GetReg(pCtx, 15) - 2) | 1); SetReg(pCtx, 15, addr); } fEmulated = true; } else if ((opcode1 & 0xff87) == 0x4700) { // BX : T1 if (execute) { DWORD Rm = BitExtract(opcode1, 6, 3); SetReg(pCtx, 15, GetReg(pCtx, Rm)); } fEmulated = true; } else if ((opcode1 & 0xf500) == 0xb100) { // CBNZ/CBZ : T1 if (execute) { DWORD op = BitExtract(opcode1, 11, 11); DWORD i = BitExtract(opcode1, 9, 9); DWORD imm5 = BitExtract(opcode1, 7, 3); DWORD Rn = BitExtract(opcode1, 2, 0); if ((op && (GetReg(pCtx, Rn) != 0)) || (!op && (GetReg(pCtx, Rn) == 0))) { SetReg(pCtx, 15, GetReg(pCtx, 15) + ((i << 6) | (imm5 << 1))); } } fEmulated = true; } else if (((opcode1 & 0xff00) == 0xbf00) && ((opcode1 & 0x000f) != 0x0000)) { // IT : T1 if (execute) { DWORD firstcond = BitExtract(opcode1, 7, 4); DWORD mask = BitExtract(opcode1, 3, 0); // The IT instruction is special. We compute the IT state bits for the CPSR and cache them in // m_originalITState. We then set m_fEmulatedITInstruction so that Fixup() knows not to advance // this state (simply write it as-is back into the CPSR). m_originalITState.Init((BYTE)((firstcond << 4) | mask)); m_originalITState.Set(pCtx); m_fEmulatedITInstruction = true; } fEmulated = true; } else if ((opcode1 & 0xf800) == 0x4800) { // LDR (literal) : T1 if (execute) { DWORD Rt = BitExtract(opcode1, 10, 8); DWORD imm8 = BitExtract(opcode1, 7, 0); DWORD addr = (GetReg(pCtx, 15) & ~3) + (imm8 << 2); DWORD value = 0; GET_MEM(&value, addr, 4, false); SetReg(pCtx, Rt, value); } fEmulated = true; } else if ((opcode1 & 0xff00) == 0x4600) { // MOV (register) : T1 DWORD D = BitExtract(opcode1, 7, 7); DWORD Rm = BitExtract(opcode1, 6, 3); DWORD Rd = (D << 3) | BitExtract(opcode1, 2, 0); if (execute) { SetReg(pCtx, Rd, GetReg(pCtx, Rm)); fEmulated = true; } else { // Only emulate if we change Pc if (Rm == 15 || Rd == 15) fEmulated = true; } } else if ((opcode1 & 0xfe00) == 0xbc00) { // POP : T1 DWORD P = BitExtract(opcode1, 8, 8); DWORD registerList = (P << 15) | BitExtract(opcode1, 7, 0); if (execute) { LDM(pCtx, 13, registerList, true, true); fEmulated = true; } else { // Only emulate if Pc is in the register list if (registerList & (1<<15)) fEmulated = true; } } // If we emulated an instruction but didn't set the PC explicitly we have to do so now (in such cases // the next PC will always point directly after the instruction we just emulated). if (execute && fEmulated && !m_fRedirectedPc) SetReg(pCtx, 15, GetReg(pCtx, 15) - 2); } LOG((LF_CORDB, LL_INFO100000, "ArmSingleStepper::TryEmulate(opcode=%x %x) emulated=%s redirectedPc=%s\n", (DWORD)opcode1, (DWORD)opcode2, fEmulated ? "true" : "false", m_fRedirectedPc ? "true" : "false")); return fEmulated; }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // // Emulate hardware single-step on ARM. // #include "common.h" #include "armsinglestepper.h" // // ITState methods. // ITState::ITState() { #ifdef _DEBUG m_fValid = false; #endif } // Must call Get() (or Init()) to initialize this instance from a specific context before calling any other // (non-static) method. void ITState::Get(T_CONTEXT *pCtx) { m_bITState = (BYTE)((BitExtract((WORD)pCtx->Cpsr, 15, 10) << 2) | BitExtract((WORD)(pCtx->Cpsr >> 16), 10, 9)); #ifdef _DEBUG m_fValid = true; #endif } // Must call Init() (or Get()) to initialize this instance from a raw byte value before calling any other // (non-static) method. void ITState::Init(BYTE bState) { m_bITState = bState; #ifdef _DEBUG m_fValid = true; #endif } // Does the current IT state indicate we're executing within an IT block? bool ITState::InITBlock() { _ASSERTE(m_fValid); return (m_bITState & 0x1f) != 0; } // Only valid within an IT block. Returns the condition code which will be evaluated for the current // instruction. DWORD ITState::CurrentCondition() { _ASSERTE(m_fValid); _ASSERTE(InITBlock()); return BitExtract(m_bITState, 7, 4); } // Transition the IT state to that for the next instruction. void ITState::Advance() { _ASSERTE(m_fValid); if ((m_bITState & 0x7) == 0) m_bITState = 0; else m_bITState = (m_bITState & 0xe0) | ((m_bITState << 1) & 0x1f); } // Write the current IT state back into the given context. void ITState::Set(T_CONTEXT *pCtx) { _ASSERTE(m_fValid); Clear(pCtx); pCtx->Cpsr |= BitExtract(m_bITState, 1, 0) << 25; pCtx->Cpsr |= BitExtract(m_bITState, 7, 2) << 10; } // Clear IT state (i.e. force execution to be outside of an IT block) in the given context. /* static */ void ITState::Clear(T_CONTEXT *pCtx) { pCtx->Cpsr &= 0xf9ff03ff; } // // ArmSingleStepper methods. // ArmSingleStepper::ArmSingleStepper() : m_originalPc(0), m_targetPc(0), m_rgCode(0), m_state(Disabled), m_fEmulatedITInstruction(false), m_fRedirectedPc(false), m_fEmulate(false), m_fBypass(false), m_fSkipIT(false) { m_opcodes[0] = 0; m_opcodes[1] = 0; } ArmSingleStepper::~ArmSingleStepper() { #if !defined(DACCESS_COMPILE) SystemDomain::GetGlobalLoaderAllocator()->GetExecutableHeap()->BackoutMem(m_rgCode, kMaxCodeBuffer * sizeof(WORD)); #endif } void ArmSingleStepper::Init() { #if !defined(DACCESS_COMPILE) if (m_rgCode == NULL) { m_rgCode = (WORD *)(void *)SystemDomain::GetGlobalLoaderAllocator()->GetExecutableHeap()->AllocMem(S_SIZE_T(kMaxCodeBuffer * sizeof(WORD))); } #endif } // Given the context with which a thread will be resumed, modify that context such that resuming the thread // will execute a single instruction before raising an EXCEPTION_BREAKPOINT. The thread context must be // cleaned up via the Fixup method below before any further exception processing can occur (at which point the // caller can behave as though EXCEPTION_SINGLE_STEP was raised). void ArmSingleStepper::Enable() { _ASSERTE(m_state != Applied); if (m_state == Enabled) { // We allow single-stepping to be enabled multiple times before the thread is resumed, but we require // that the thread state is the same in all cases (i.e. additional step requests are treated as // no-ops). _ASSERTE(!m_fBypass); _ASSERTE(m_opcodes[0] == 0); _ASSERTE(m_opcodes[1] == 0); return; } LOG((LF_CORDB, LL_INFO100000, "ArmSingleStepper::Enable\n")); m_fBypass = false; m_opcodes[0] = 0; m_opcodes[1] = 0; m_state = Enabled; } void ArmSingleStepper::Bypass(DWORD ip, WORD opcode1, WORD opcode2) { _ASSERTE(m_state != Applied); if (m_state == Enabled) { // We allow single-stepping to be enabled multiple times before the thread is resumed, but we require // that the thread state is the same in all cases (i.e. additional step requests are treated as // no-ops). if (m_fBypass) { _ASSERTE(m_opcodes[0] == opcode1); _ASSERTE(m_opcodes[1] == opcode2); _ASSERTE(m_originalPc == ip); return; } } LOG((LF_CORDB, LL_INFO100000, "ArmSingleStepper::Bypass(pc=%x, opcode=%x %x)\n", (DWORD)ip, (DWORD)opcode1, (DWORD)opcode2)); m_fBypass = true; m_originalPc = ip; m_opcodes[0] = opcode1; m_opcodes[1] = opcode2; m_state = Enabled; } void ArmSingleStepper::Apply(T_CONTEXT *pCtx) { if (m_rgCode == NULL) { Init(); // OOM. We will simply ignore the single step. if (m_rgCode == NULL) return; } _ASSERTE(pCtx != NULL); if (!m_fBypass) { DWORD pc = ((DWORD)pCtx->Pc) & ~THUMB_CODE; m_opcodes[0] = *(WORD*)pc; if (Is32BitInstruction( m_opcodes[0])) m_opcodes[1] = *(WORD*)(pc+2); } WORD opcode1 = m_opcodes[0]; WORD opcode2 = m_opcodes[1]; LOG((LF_CORDB, LL_INFO100000, "ArmSingleStepper::Apply(pc=%x, opcode=%x %x)\n", (DWORD)pCtx->Pc, (DWORD)opcode1, (DWORD)opcode2)); #ifdef _DEBUG // Make sure that we aren't trying to step through our own buffer. If this asserts, something is horribly // wrong with the debugging layer. Likely GetManagedStoppedCtx is retrieving a Pc that points to our // buffer, even though the single stepper is disabled. DWORD codestart = (DWORD)(DWORD_PTR)m_rgCode; DWORD codeend = codestart + (kMaxCodeBuffer * sizeof(WORD)); _ASSERTE((pCtx->Pc < codestart) || (pCtx->Pc >= codeend)); #endif // All stepping is simulated using a breakpoint instruction. Since other threads are not suspended while // we step, we avoid race conditions and other complexity by redirecting the thread into a thread-local // execution buffer. We can either copy the instruction we wish to step over into the buffer followed by a // breakpoint or we can emulate the instruction (which is useful for instruction that depend on the value // of the PC or that branch or call to an alternate location). Even in the emulation case we still // redirect execution into the buffer and insert a breakpoint; this simplifies our interface since the // rest of the runtime is not set up to expect single stepping to occur inline. Instead there is always a // 1:1 relationship between setting the single-step mode and receiving an exception once the thread is // restarted. // // There are two parts to the emulation: // 1) In this method we either emulate the instruction (updating the input thread context as a result) or // copy the single instruction into the execution buffer. In both cases we copy a breakpoint into the // execution buffer as well then update the thread context to redirect execution into this buffer. // 2) In the runtime's first chance vectored exception handler we perform the necessary fixups to make // the exception look like the result of a single step. This includes resetting the PC to its correct // value (either the instruction following the stepped instruction or the target PC cached in this // object when we emulated an instruction that alters the PC). It also involves switching // EXCEPTION_BREAKPOINT to EXCEPTION_SINGLE_STEP. // // If we encounter an exception while emulating an instruction (currently this can only happen if we A/V // trying to read a value from memory) then we abandon emulation and fall back to the copy instruction // mechanism. When we run the execution buffer the exception should be raised and handled as normal (we // still peform context fixup in this case but we don't attempt to alter any exception code other than // EXCEPTION_BREAKPOINT to EXCEPTION_SINGLE_STEP). There is a very small timing window here where another // thread could alter memory protections to avoid the A/V when we run the instruction for real but the // liklihood of this happening (in managed code no less) is judged sufficiently small that it's not worth // the alternate solution (where we'd have to set the thread up to raise an exception with exactly the // right thread context). // // Matters are complicated by the ARM IT instruction (upto four following instructions are executed // conditionally based on a single condition or its negation). The issues are that the current instruction // may be rendered into a no-op or that a breakpoint immediately following the current instruction may not // be executed. To simplify matters we may modify the IT state to force our instructions to execute. We // cache the real state and re-apply it along with the rest of our fixups when handling the breakpoint // exception. Note that when executing general instructions we can't simply disable any IT state since // many instructions alter their behavior depending on whether they're executing within an IT block // (mostly it's used to determine whether these instructions set condition flags or not). // Cache thread's initial PC and IT state since we'll overwrite them as part of the emulation and we need // to get back to the correct values at fixup time. We also cache a target PC (set below) since some // instructions will set the PC directly or otherwise make it difficult for us to compute the final PC // from the original. We still need the original PC however since this is the one we'll use if an // exception (other than a breakpoint) occurs. _ASSERTE(!m_fBypass || (m_originalPc == pCtx->Pc)); m_originalPc = pCtx->Pc; m_originalITState.Get(pCtx); // By default assume the next PC is right after the current instruction. m_targetPc = m_originalPc + (Is32BitInstruction(opcode1) ? 4 : 2); m_fEmulate = false; // One more special case: if we attempt to single-step over an IT instruction it's easier to emulate this, // set the new IT state in m_originalITState and set a special flag that lets Fixup() know we don't need // to advance the state (this only works because we know IT will never raise an exception so we don't need // m_originalITState to store the real original IT state, though in truth a legal IT instruction cannot be // executed inside an IT block anyway). This flag (and m_originalITState) will be set inside TryEmulate() // as needed. m_fEmulatedITInstruction = false; m_fSkipIT = false; // There are three different scenarios we must deal with (listed in priority order). In all cases we will // redirect the thread to execute code from our buffer and end by raising a breakpoint exception: // 1) We're executing in an IT block and the current instruction doesn't meet the condition requirements. // We leave the state unchanged and in fixup will advance the PC to the next instruction slot. // 2) The current instruction either takes the PC as an input or modifies the PC in a non-trivial manner. // We can't easily run these instructions from the redirect buffer so we emulate their effect (i.e. // update the current context in the same way as executing the instruction would). The breakpoint // fixup logic will restore the PC to the real resultant PC we cache in m_targetPc. // 3) For all other cases (including emulation cases where we aborted due to a memory fault) we copy the // single instruction into the redirect buffer for execution followed by a breakpoint (once we regain // control in the breakpoint fixup logic we can then reset the PC to its proper location. DWORD idxNextInstruction = 0; ExecutableWriterHolder<WORD> codeWriterHolder(m_rgCode, kMaxCodeBuffer * sizeof(m_rgCode[0])); if (m_originalITState.InITBlock() && !ConditionHolds(pCtx, m_originalITState.CurrentCondition())) { LOG((LF_CORDB, LL_INFO100000, "ArmSingleStepper: Case 1: ITState::Clear;\n")); // Case 1: The current instruction is a no-op because due to the IT instruction. We've already set the // target PC to the next instruction slot. Disable the IT block since we want our breakpoint // to execute. We'll put the correct value back during fixup. ITState::Clear(pCtx); m_fSkipIT = true; codeWriterHolder.GetRW()[idxNextInstruction++] = kBreakpointOp; } else if (TryEmulate(pCtx, opcode1, opcode2, false)) { LOG((LF_CORDB, LL_INFO100000, "ArmSingleStepper: Case 2: Emulate\n")); // Case 2: Successfully emulated an instruction that reads or writes the PC. Cache the new target PC // so upon fixup we'll resume execution there rather than the following instruction. No need // to mess with IT state since we know the next instruction is scheduled to execute (we dealt // with the case where it wasn't above) and we're going to execute a breakpoint in that slot. m_targetPc = pCtx->Pc; m_fEmulate = true; // Set breakpoints to stop the execution. This will get us right back here. codeWriterHolder.GetRW()[idxNextInstruction++] = kBreakpointOp; codeWriterHolder.GetRW()[idxNextInstruction++] = kBreakpointOp; } else { LOG((LF_CORDB, LL_INFO100000, "ArmSingleStepper: Case 3: CopyInstruction. Is32Bit=%d\n", (DWORD)Is32BitInstruction(opcode1))); // Case 3: In all other cases copy the instruction to the buffer and we'll run it directly. If we're // in an IT block there could be up to three instructions following this one whose execution // is skipped. We could try to be clever here and either alter IT state to force the next // instruction to execute or calculate the how many filler instructions we need to insert // before we're guaranteed our breakpoint will be respected. But it's easier to just insert // three additional breakpoints here (code below will add the fourth) and that way we'll // guarantee one of them will be hit (we don't care which one -- the fixup code will update // the PC and IT state to make it look as though the CPU just executed the current // instruction). codeWriterHolder.GetRW()[idxNextInstruction++] = opcode1; if (Is32BitInstruction(opcode1)) codeWriterHolder.GetRW()[idxNextInstruction++] = opcode2; codeWriterHolder.GetRW()[idxNextInstruction++] = kBreakpointOp; codeWriterHolder.GetRW()[idxNextInstruction++] = kBreakpointOp; codeWriterHolder.GetRW()[idxNextInstruction++] = kBreakpointOp; } // Always terminate the redirection buffer with a breakpoint. codeWriterHolder.GetRW()[idxNextInstruction++] = kBreakpointOp; _ASSERTE(idxNextInstruction <= kMaxCodeBuffer); // Set the thread up so it will redirect to our buffer when execution resumes. pCtx->Pc = ((DWORD)(DWORD_PTR)m_rgCode) | THUMB_CODE; // Make sure the CPU sees the updated contents of the buffer. FlushInstructionCache(GetCurrentProcess(), m_rgCode, kMaxCodeBuffer * sizeof(m_rgCode[0])); // Done, set the state. m_state = Applied; } void ArmSingleStepper::Disable() { _ASSERTE(m_state != Applied); m_state = Disabled; } // When called in response to an exception (preferably in a first chance vectored handler before anyone else // has looked at the thread context) this method will (a) determine whether this exception was raised by a // call to Enable() above, in which case true will be returned and (b) perform final fixup of the thread // context passed in to complete the emulation of a hardware single step. Note that this routine must be // called even if the exception code is not EXCEPTION_BREAKPOINT since the instruction stepped might have // raised its own exception (e.g. A/V) and we still need to fix the thread context in this case. bool ArmSingleStepper::Fixup(T_CONTEXT *pCtx, DWORD dwExceptionCode) { #ifdef _DEBUG DWORD codestart = (DWORD)(DWORD_PTR)m_rgCode; DWORD codeend = codestart + (kMaxCodeBuffer * sizeof(WORD)); #endif // If we reach fixup, we should either be Disabled or Applied. If we reach here with Enabled it means // that the debugging layer Enabled the single stepper, but we never applied it to a CONTEXT. _ASSERTE(m_state != Enabled); // Nothing to do if the stepper is disabled on this thread. if (m_state == Disabled) { // We better not be inside our internal code buffer though. _ASSERTE((pCtx->Pc < codestart) || (pCtx->Pc >= codeend)); return false; } // Turn off the single stepper after we have executed one instruction. m_state = Disabled; // We should always have a PC somewhere in our redirect buffer. #ifdef _DEBUG _ASSERTE((pCtx->Pc >= codestart) && (pCtx->Pc < codeend)); #endif if (dwExceptionCode == EXCEPTION_BREAKPOINT) { // The single step went as planned. Set the PC back to its real value (either following the // instruction we stepped or the computed destination we cached after emulating an instruction that // modifies the PC). Advance the IT state from the value we cached before the single step (unless we // stepped an IT instruction itself, in which case m_originalITState holds the new state and we should // just set that). if (!m_fEmulate) { if (m_rgCode[0] != kBreakpointOp) { LOG((LF_CORDB, LL_INFO100000, "ArmSingleStepper::Fixup executed code, ip = %x\n", m_targetPc)); pCtx->Pc = m_targetPc; if (!m_fEmulatedITInstruction) m_originalITState.Advance(); m_originalITState.Set(pCtx); } else { if (m_fSkipIT) { // We needed to skip over an instruction due to a false condition in an IT block. LOG((LF_CORDB, LL_INFO100000, "ArmSingleStepper::Fixup skipped instruction due to IT\n")); pCtx->Pc = m_targetPc; _ASSERTE(!m_fEmulatedITInstruction); m_originalITState.Advance(); m_originalITState.Set(pCtx); } else { // We've hit a breakpoint in the code stream. We will return false here (which causes us to NOT // replace the breakpoint code with single step), and place the Pc back to the original Pc. The // debugger patch skipping code will move past this breakpoint. LOG((LF_CORDB, LL_INFO100000, "ArmSingleStepper::Fixup emulated breakpoint\n")); pCtx->Pc = m_originalPc; _ASSERTE(pCtx->Pc & THUMB_CODE); return false; } } } else { bool res = TryEmulate(pCtx, m_opcodes[0], m_opcodes[1], true); _ASSERTE(res); // We should always successfully emulate since we ran it through TryEmulate already. if (!m_fRedirectedPc) pCtx->Pc = m_targetPc; LOG((LF_CORDB, LL_INFO100000, "ArmSingleStepper::Fixup emulated, ip = %x\n", pCtx->Pc)); } } else { // The stepped instruction caused an exception. Reset the PC and IT state to their original values we // cached before stepping. (We should never seen this when stepping an IT instruction which overwrites // m_originalITState). _ASSERTE(!m_fEmulatedITInstruction); _ASSERTE(m_fEmulate == false); pCtx->Pc = m_originalPc; m_originalITState.Set(pCtx); LOG((LF_CORDB, LL_INFO100000, "ArmSingleStepper::Fixup hit exception pc = %x ex = %x\n", pCtx->Pc, dwExceptionCode)); } _ASSERTE(pCtx->Pc & THUMB_CODE); return true; } // Count the number of bits set in a DWORD. DWORD ArmSingleStepper::BitCount(DWORD dwValue) { // There are faster implementations but speed isn't critical here. DWORD cBits = 0; while (dwValue) { cBits += dwValue & 1; dwValue >>= 1; } return cBits; } // Return true if the given condition (C, N, Z or V) holds in the current context. #define GET_FLAG(pCtx, _flag) \ ((pCtx->Cpsr & (1 << APSR_##_flag)) != 0) // Returns true if the current context indicates the ARM condition specified holds. bool ArmSingleStepper::ConditionHolds(T_CONTEXT *pCtx, DWORD cond) { switch (cond) { case 0: // EQ (Z==1) return GET_FLAG(pCtx, Z); case 1: // NE (Z==0) return !GET_FLAG(pCtx, Z); case 2: // CS (C==1) return GET_FLAG(pCtx, C); case 3: // CC (C==0) return !GET_FLAG(pCtx, C); case 4: // MI (N==1) return GET_FLAG(pCtx, N); case 5: // PL (N==0) return !GET_FLAG(pCtx, N); case 6: // VS (V==1) return GET_FLAG(pCtx, V); case 7: // VC (V==0) return !GET_FLAG(pCtx, V); case 8: // HI (C==1 && Z==0) return GET_FLAG(pCtx, C) && !GET_FLAG(pCtx, Z); case 9: // LS (C==0 || Z==1) return !GET_FLAG(pCtx, C) || GET_FLAG(pCtx, Z); case 10: // GE (N==V) return GET_FLAG(pCtx, N) == GET_FLAG(pCtx, V); case 11: // LT (N!=V) return GET_FLAG(pCtx, N) != GET_FLAG(pCtx, V); case 12: // GT (Z==0 && N==V) return !GET_FLAG(pCtx, Z) && (GET_FLAG(pCtx, N) == GET_FLAG(pCtx, V)); case 13: // LE (Z==1 || N!=V) return GET_FLAG(pCtx, Z) || (GET_FLAG(pCtx, N) != GET_FLAG(pCtx, V)); case 14: // AL return true; case 15: _ASSERTE(!"Unsupported condition code: 15"); return false; default: // UNREACHABLE(); return false; } } // Get the current value of a register. PC (register 15) is always reported as the current instruction PC + 4 // as per the ARM architecture. DWORD ArmSingleStepper::GetReg(T_CONTEXT *pCtx, DWORD reg) { _ASSERTE(reg <= 15); if (reg == 15) return (m_originalPc + 4) & ~THUMB_CODE; return (&pCtx->R0)[reg]; } // Set the current value of a register. If the PC (register 15) is set then m_fRedirectedPc is set to true. void ArmSingleStepper::SetReg(T_CONTEXT *pCtx, DWORD reg, DWORD value) { _ASSERTE(reg <= 15); if (reg == 15) { value |= THUMB_CODE; m_fRedirectedPc = true; } (&pCtx->R0)[reg] = value; } // Attempt to read a 1, 2 or 4 byte value from memory, zero or sign extend it to a 4-byte value and place that // value into the buffer pointed at by pdwResult. Returns false if attempting to read the location caused a // fault. bool ArmSingleStepper::GetMem(DWORD *pdwResult, DWORD_PTR pAddress, DWORD cbSize, bool fSignExtend) { struct Param { DWORD *pdwResult; DWORD_PTR pAddress; DWORD cbSize; bool fSignExtend; bool bReturnValue; } param; param.pdwResult = pdwResult; param.pAddress = pAddress; param.cbSize = cbSize; param.fSignExtend = fSignExtend; param.bReturnValue = true; PAL_TRY(Param *, pParam, &param) { switch (pParam->cbSize) { case 1: *pParam->pdwResult = *(BYTE*)pParam->pAddress; if (pParam->fSignExtend && (*pParam->pdwResult & 0x00000080)) *pParam->pdwResult |= 0xffffff00; break; case 2: *pParam->pdwResult = *(WORD*)pParam->pAddress; if (pParam->fSignExtend && (*pParam->pdwResult & 0x00008000)) *pParam->pdwResult |= 0xffff0000; break; case 4: *pParam->pdwResult = *(DWORD*)pParam->pAddress; break; default: UNREACHABLE(); pParam->bReturnValue = false; } } PAL_EXCEPT(EXCEPTION_EXECUTE_HANDLER) { param.bReturnValue = false; } PAL_ENDTRY; return param.bReturnValue; } // Wrapper around GetMem above that will automatically return from TryEmulate() indicating the instruction // could not be emulated if we try to read memory and fail due to an exception. This logic works (i.e. we can // simply return without worrying whether we've already updated the thread context) due to the fact that we // either (a) read memory before updating any registers (the various LDR literal variants) or (b) update the // register list before the base register in LDM-like operations (and this should therefore be an idempotent // operation when we re-execute the instruction). If this ever changes we will have to store a copy of the // original context we can use to revert changes (it gets even more complex if we ever have to emulate an // instruction that writes memory). #define GET_MEM(_result, _addr, _size, _signextend) \ do { \ if (!GetMem((_result), (_addr), (_size), (_signextend))) \ return false; \ } while (false) // Implements the various LDM-style multi-register load instructions (these include POP). #define LDM(ctx, _base, _registerlist, _writeback, _ia) \ do { \ DWORD _pAddr = GetReg(ctx, _base); \ if (!(_ia)) \ _pAddr -= BitCount(_registerlist) * sizeof(void*); \ DWORD _pStartAddr = _pAddr; \ for (DWORD _i = 0; _i < 16; _i++) \ { \ if ((_registerlist) & (1 << _i)) \ { \ DWORD _tmpresult; \ GET_MEM(&_tmpresult, _pAddr, 4, false); \ SetReg(ctx, _i, _tmpresult); \ _pAddr += sizeof(void*); \ } \ } \ if (_writeback) \ SetReg(ctx, _base, (_ia) ? _pAddr : _pStartAddr); \ } while (false) // Parse the instruction whose first word is given in opcode1 (if the instruction is 32-bit TryEmulate will // fetch the second word using the value of the PC stored in the current context). If the instruction reads or // writes the PC or is the IT instruction then it will be emulated by updating the thread context // appropriately and true will be returned. If the instruction is not one of those cases (or it is but we // faulted trying to read memory during the emulation) no state is updated and false is returned instead. bool ArmSingleStepper::TryEmulate(T_CONTEXT *pCtx, WORD opcode1, WORD opcode2, bool execute) { LOG((LF_CORDB, LL_INFO100000, "ArmSingleStepper::TryEmulate(opcode=%x %x, execute=%s)\n", (DWORD)opcode1, (DWORD)opcode2, execute ? "true" : "false")); // Track whether instruction emulation wrote a modified PC. m_fRedirectedPc = false; // Track whether we successfully emulated an instruction. If we did and we didn't modify the PC (e.g. a // ADR instruction or a conditional branch not taken) then we'll need to explicitly set the PC to the next // instruction (since our caller expects that whenever we return true m_pCtx->Pc holds the next // instruction address). bool fEmulated = false; if (Is32BitInstruction(opcode1)) { if (((opcode1 & 0xfbff) == 0xf2af) && ((opcode2 & 0x8000) == 0x0000)) { // ADR.W : T2 if (execute) { DWORD Rd = BitExtract(opcode2, 11, 8); DWORD i = BitExtract(opcode1, 10, 10); DWORD imm3 = BitExtract(opcode2, 14, 12); DWORD imm8 = BitExtract(opcode2, 7, 0); SetReg(pCtx, Rd, (GetReg(pCtx, 15) & ~3) - ((i << 11) | (imm3 << 8) | imm8)); } fEmulated = true; } else if (((opcode1 & 0xfbff) == 0xf20f) && ((opcode2 & 0x8000) == 0x0000)) { // ADR.W : T3 if (execute) { DWORD Rd = BitExtract(opcode2, 11, 8); DWORD i = BitExtract(opcode1, 10, 10); DWORD imm3 = BitExtract(opcode2, 14, 12); DWORD imm8 = BitExtract(opcode2, 7, 0); SetReg(pCtx, Rd, (GetReg(pCtx, 15) & ~3) + ((i << 11) | (imm3 << 8) | imm8)); } fEmulated = true; } else if (((opcode1 & 0xf800) == 0xf000) && ((opcode2 & 0xd000) == 0x8000) && ((opcode1 & 0x0380) != 0x0380)) { // B.W : T3 if (execute) { DWORD S = BitExtract(opcode1, 10, 10); DWORD cond = BitExtract(opcode1, 9, 6); DWORD imm6 = BitExtract(opcode1, 5, 0); DWORD J1 = BitExtract(opcode2, 13, 13); DWORD J2 = BitExtract(opcode2, 11, 11); DWORD imm11 = BitExtract(opcode2, 10, 0); if (ConditionHolds(pCtx, cond) && execute) { DWORD disp = (S ? 0xfff00000 : 0) | (J2 << 19) | (J1 << 18) | (imm6 << 12) | (imm11 << 1); SetReg(pCtx, 15, GetReg(pCtx, 15) + disp); } } fEmulated = true; } else if (((opcode1 & 0xf800) == 0xf000) && ((opcode2 & 0xd000) == 0x9000)) { // B.W : T4 if (execute) { DWORD S = BitExtract(opcode1, 10, 10); DWORD imm10 = BitExtract(opcode1, 9, 0); DWORD J1 = BitExtract(opcode2, 13, 13); DWORD J2 = BitExtract(opcode2, 11, 11); DWORD imm11 = BitExtract(opcode2, 10, 0); DWORD I1 = (J1 ^ S) ^ 1; DWORD I2 = (J2 ^ S) ^ 1; DWORD disp = (S ? 0xff000000 : 0) | (I1 << 23) | (I2 << 22) | (imm10 << 12) | (imm11 << 1); SetReg(pCtx, 15, GetReg(pCtx, 15) + disp); } fEmulated = true; } else if (((opcode1 & 0xf800) == 0xf000) && ((opcode2 & 0xd000) == 0xd000)) { // BL (immediate) : T1 if (execute) { DWORD S = BitExtract(opcode1, 10, 10); DWORD imm10 = BitExtract(opcode1, 9, 0); DWORD J1 = BitExtract(opcode2, 13, 13); DWORD J2 = BitExtract(opcode2, 11, 11); DWORD imm11 = BitExtract(opcode2, 10, 0); DWORD I1 = (J1 ^ S) ^ 1; DWORD I2 = (J2 ^ S) ^ 1; SetReg(pCtx, 14, GetReg(pCtx, 15) | 1); DWORD disp = (S ? 0xff000000 : 0) | (I1 << 23) | (I2 << 22) | (imm10 << 12) | (imm11 << 1); SetReg(pCtx, 15, GetReg(pCtx, 15) + disp); } fEmulated = true; } else if (((opcode1 & 0xffd0) == 0xe890) && ((opcode2 & 0x2000) == 0x0000)) { // LDM.W : T2, POP.W : T2 if (execute) { DWORD W = BitExtract(opcode1, 5, 5); DWORD Rn = BitExtract(opcode1, 3, 0); DWORD registerList = opcode2; LDM(pCtx, Rn, registerList, W, true); fEmulated = true; } else { // We should only emulate this instruction if Pc is set if (opcode2 & (1<<15)) fEmulated = true; } } else if (((opcode1 & 0xffd0) == 0xe410) && ((opcode2 & 0x2000) == 0x0000)) { // LDMDB : T1 if (execute) { DWORD W = BitExtract(opcode1, 5, 5); DWORD Rn = BitExtract(opcode1, 3, 0); DWORD registerList = opcode2; LDM(pCtx, Rn, registerList, W, false); fEmulated = true; } else { // We should only emulate this instruction if Pc is set if (opcode2 & (1<<15)) fEmulated = true; } } else if (((opcode1 & 0xfff0) == 0xf8d0) && ((opcode1 & 0x000f) != 0x000f)) { // LDR.W (immediate): T3 DWORD Rt = BitExtract(opcode2, 15, 12); DWORD Rn = BitExtract(opcode1, 3, 0); if (execute) { DWORD imm12 = BitExtract(opcode2, 11, 0); DWORD value; GET_MEM(&value, GetReg(pCtx, Rn) + imm12, 4, false); SetReg(pCtx, Rt, value); fEmulated = true; } else { // We should only emulate this instruction if Pc is used if (Rt == 15 || Rn == 15) fEmulated = true; } } else if (((opcode1 & 0xfff0) == 0xf850) && ((opcode2 & 0x0800) == 0x0800) && ((opcode1 & 0x000f) != 0x000f)) { // LDR (immediate) : T4, POP : T3 DWORD Rn = BitExtract(opcode1, 3, 0); DWORD Rt = BitExtract(opcode2, 15, 12); if (execute) { DWORD P = BitExtract(opcode2, 10, 10); DWORD U = BitExtract(opcode2, 9, 9); DWORD W = BitExtract(opcode2, 8, 8); DWORD imm8 = BitExtract(opcode2, 7, 0); DWORD offset_addr = U ? GetReg(pCtx, Rn) + imm8 : GetReg(pCtx, Rn) - imm8; DWORD addr = P ? offset_addr : GetReg(pCtx, Rn); DWORD value; GET_MEM(&value, addr, 4, false); if (W) SetReg(pCtx, Rn, offset_addr); SetReg(pCtx, Rt, value); fEmulated = true; } else { // We should only emulate this instruction if Pc is used if (Rt == 15 || Rn == 15) fEmulated = true; } } else if (((opcode1 & 0xff7f) == 0xf85f)) { // LDR.W (literal) : T2 DWORD Rt = BitExtract(opcode2, 15, 12); if (execute) { DWORD U = BitExtract(opcode1, 7, 7); DWORD imm12 = BitExtract(opcode2, 11, 0); // This instruction always reads relative to R15/PC DWORD addr = GetReg(pCtx, 15) & ~3; addr = U ? addr + imm12 : addr - imm12; DWORD value; GET_MEM(&value, addr, 4, false); SetReg(pCtx, Rt, value); } // We should ALWAYS emulate this instruction, because this instruction // always reads the memory relative to PC fEmulated = true; } else if (((opcode1 & 0xfff0) == 0xf850) && ((opcode2 & 0x0fc0) == 0x0000) && ((opcode1 & 0x000f) != 0x000f)) { // LDR.W : T2 DWORD Rn = BitExtract(opcode1, 3, 0); DWORD Rt = BitExtract(opcode2, 15, 12); DWORD Rm = BitExtract(opcode2, 3, 0); if (execute) { DWORD imm2 = BitExtract(opcode2, 5, 4); DWORD addr = GetReg(pCtx, Rn) + (GetReg(pCtx, Rm) << imm2); DWORD value; GET_MEM(&value, addr, 4, false); SetReg(pCtx, Rt, value); fEmulated = true; } else { // We should only emulate this instruction if Pc is used if (Rt == 15 || Rn == 15 || Rm == 15) fEmulated = true; } } else if (((opcode1 & 0xff7f) == 0xf81f) && ((opcode2 & 0xf000) != 0xf000)) { // LDRB (literal) : T2 if (execute) { DWORD U = BitExtract(opcode1, 7, 7); DWORD Rt = BitExtract(opcode2, 15, 12); DWORD imm12 = BitExtract(opcode2, 11, 0); DWORD addr = (GetReg(pCtx, 15) & ~3); addr = U ? addr + imm12 : addr - imm12; DWORD value; GET_MEM(&value, addr, 1, false); SetReg(pCtx, Rt, value); } fEmulated = true; } else if (((opcode1 & 0xfe5f) == 0xe85f) && ((opcode1 & 0x0120) != 0x0000)) { // LDRD (literal) : T1 if (execute) { DWORD U = BitExtract(opcode1, 7, 7); DWORD Rt = BitExtract(opcode2, 15, 12); DWORD Rt2 = BitExtract(opcode2, 11, 8); DWORD imm8 = BitExtract(opcode2, 7, 0); DWORD addr = (GetReg(pCtx, 15) & ~3); addr = U ? addr + (imm8 << 2) : addr - (imm8 << 2); DWORD value1; GET_MEM(&value1, addr, 4, false); DWORD value2; GET_MEM(&value2, addr + 4, 4, false); SetReg(pCtx, Rt, value1); SetReg(pCtx, Rt2, value2); } fEmulated = true; } else if (((opcode1 & 0xff7f) == 0xf83f) && ((opcode2 & 0xf000) != 0xf000)) { // LDRH (literal) : T1 if (execute) { DWORD U = BitExtract(opcode1, 7, 7); DWORD Rt = BitExtract(opcode2, 15, 12); DWORD imm12 = BitExtract(opcode2, 11, 0); DWORD addr = (GetReg(pCtx, 15) & ~3); addr = U ? addr + imm12 : addr - imm12; DWORD value; GET_MEM(&value, addr, 2, false); SetReg(pCtx, Rt, value); } fEmulated = true; } else if (((opcode1 & 0xff7f) == 0xf91f) && ((opcode2 & 0xf000) != 0xf000)) { // LDRSB (literal) : T1 if (execute) { DWORD U = BitExtract(opcode1, 7, 7); DWORD Rt = BitExtract(opcode2, 15, 12); DWORD imm12 = BitExtract(opcode2, 11, 0); DWORD addr = (GetReg(pCtx, 15) & ~3); addr = U ? addr + imm12 : addr - imm12; DWORD value; GET_MEM(&value, addr, 1, true); SetReg(pCtx, Rt, value); } fEmulated = true; } else if (((opcode1 & 0xff7f) == 0xf53f) && ((opcode2 & 0xf000) != 0xf000)) { // LDRSH (literal) : T1 if (execute) { DWORD U = BitExtract(opcode1, 7, 7); DWORD Rt = BitExtract(opcode2, 15, 12); DWORD imm12 = BitExtract(opcode2, 11, 0); DWORD addr = (GetReg(pCtx, 15) & ~3); addr = U ? addr + imm12 : addr - imm12; DWORD value; GET_MEM(&value, addr, 2, true); SetReg(pCtx, Rt, value); } fEmulated = true; } else if (((opcode1 & 0xfff0) == 0xe8d0) && ((opcode2 & 0xffe0) == 0xf000)) { // TBB/TBH : T1 if (execute) { DWORD Rn = BitExtract(opcode1, 3, 0); DWORD H = BitExtract(opcode2, 4, 4); DWORD Rm = BitExtract(opcode2, 3, 0); DWORD addr = GetReg(pCtx, Rn); DWORD value; if (H) GET_MEM(&value, addr + (GetReg(pCtx, Rm) << 1), 2, false); else GET_MEM(&value, addr + GetReg(pCtx, Rm), 1, false); SetReg(pCtx, 15, GetReg(pCtx, 15) + (value << 1)); } fEmulated = true; } // If we emulated an instruction but didn't set the PC explicitly we have to do so now (in such cases // the next PC will always point directly after the instruction we just emulated). if (fEmulated && !m_fRedirectedPc) SetReg(pCtx, 15, GetReg(pCtx, 15)); } else { // Handle 16-bit instructions. if ((opcode1 & 0xf800) == 0xa000) { // ADR : T1 if (execute) { DWORD Rd = BitExtract(opcode1, 10, 8); DWORD imm8 = BitExtract(opcode1, 7, 0); SetReg(pCtx, Rd, (GetReg(pCtx, 15) & 3) + (imm8 << 2)); } fEmulated = true; } else if ((opcode1 & 0xff00) == 0x4400) { // A8.8.6 ADD (register, Thumb) : T2 DWORD Rm = BitExtract(opcode1, 6, 3); // We should only emulate this instruction if Pc is used if (Rm == 15) fEmulated = true; if (execute) { DWORD Rd = BitExtract(opcode1, 2, 0) | BitExtract(opcode1, 7, 7) << 3; SetReg(pCtx, Rd, GetReg(pCtx, Rm) + GetReg(pCtx, Rd)); } } else if (((opcode1 & 0xf000) == 0xd000) && ((opcode1 & 0x0f00) != 0x0e00)) { // B : T1 // We only emulate this instruction if we take the conditional // jump. If not we'll pass right over the jump and set the // target IP as normal. DWORD cond = BitExtract(opcode1, 11, 8); if (execute) { _ASSERTE(ConditionHolds(pCtx, cond)); DWORD imm8 = BitExtract(opcode1, 7, 0); DWORD disp = (imm8 << 1) | ((imm8 & 0x80) ? 0xffffff00 : 0); SetReg(pCtx, 15, GetReg(pCtx, 15) + disp); fEmulated = true; } else { if (ConditionHolds(pCtx, cond)) { fEmulated = true; } } } else if ((opcode1 & 0xf800) == 0xe000) { if (execute) { // B : T2 DWORD imm11 = BitExtract(opcode1, 10, 0); DWORD disp = (imm11 << 1) | ((imm11 & 0x400) ? 0xfffff000 : 0); SetReg(pCtx, 15, GetReg(pCtx, 15) + disp); } fEmulated = true; } else if ((opcode1 & 0xff87) == 0x4780) { // BLX (register) : T1 if (execute) { DWORD Rm = BitExtract(opcode1, 6, 3); DWORD addr = GetReg(pCtx, Rm); SetReg(pCtx, 14, (GetReg(pCtx, 15) - 2) | 1); SetReg(pCtx, 15, addr); } fEmulated = true; } else if ((opcode1 & 0xff87) == 0x4700) { // BX : T1 if (execute) { DWORD Rm = BitExtract(opcode1, 6, 3); SetReg(pCtx, 15, GetReg(pCtx, Rm)); } fEmulated = true; } else if ((opcode1 & 0xf500) == 0xb100) { // CBNZ/CBZ : T1 if (execute) { DWORD op = BitExtract(opcode1, 11, 11); DWORD i = BitExtract(opcode1, 9, 9); DWORD imm5 = BitExtract(opcode1, 7, 3); DWORD Rn = BitExtract(opcode1, 2, 0); if ((op && (GetReg(pCtx, Rn) != 0)) || (!op && (GetReg(pCtx, Rn) == 0))) { SetReg(pCtx, 15, GetReg(pCtx, 15) + ((i << 6) | (imm5 << 1))); } } fEmulated = true; } else if (((opcode1 & 0xff00) == 0xbf00) && ((opcode1 & 0x000f) != 0x0000)) { // IT : T1 if (execute) { DWORD firstcond = BitExtract(opcode1, 7, 4); DWORD mask = BitExtract(opcode1, 3, 0); // The IT instruction is special. We compute the IT state bits for the CPSR and cache them in // m_originalITState. We then set m_fEmulatedITInstruction so that Fixup() knows not to advance // this state (simply write it as-is back into the CPSR). m_originalITState.Init((BYTE)((firstcond << 4) | mask)); m_originalITState.Set(pCtx); m_fEmulatedITInstruction = true; } fEmulated = true; } else if ((opcode1 & 0xf800) == 0x4800) { // LDR (literal) : T1 if (execute) { DWORD Rt = BitExtract(opcode1, 10, 8); DWORD imm8 = BitExtract(opcode1, 7, 0); DWORD addr = (GetReg(pCtx, 15) & ~3) + (imm8 << 2); DWORD value = 0; GET_MEM(&value, addr, 4, false); SetReg(pCtx, Rt, value); } fEmulated = true; } else if ((opcode1 & 0xff00) == 0x4600) { // MOV (register) : T1 DWORD D = BitExtract(opcode1, 7, 7); DWORD Rm = BitExtract(opcode1, 6, 3); DWORD Rd = (D << 3) | BitExtract(opcode1, 2, 0); if (execute) { SetReg(pCtx, Rd, GetReg(pCtx, Rm)); fEmulated = true; } else { // Only emulate if we change Pc if (Rm == 15 || Rd == 15) fEmulated = true; } } else if ((opcode1 & 0xfe00) == 0xbc00) { // POP : T1 DWORD P = BitExtract(opcode1, 8, 8); DWORD registerList = (P << 15) | BitExtract(opcode1, 7, 0); if (execute) { LDM(pCtx, 13, registerList, true, true); fEmulated = true; } else { // Only emulate if Pc is in the register list if (registerList & (1<<15)) fEmulated = true; } } // If we emulated an instruction but didn't set the PC explicitly we have to do so now (in such cases // the next PC will always point directly after the instruction we just emulated). if (execute && fEmulated && !m_fRedirectedPc) SetReg(pCtx, 15, GetReg(pCtx, 15) - 2); } LOG((LF_CORDB, LL_INFO100000, "ArmSingleStepper::TryEmulate(opcode=%x %x) emulated=%s redirectedPc=%s\n", (DWORD)opcode1, (DWORD)opcode2, fEmulated ? "true" : "false", m_fRedirectedPc ? "true" : "false")); return fEmulated; }
-1
dotnet/runtime
66,474
Update repo CMake configuration to target /W4 by default
Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
AaronRobinsonMSFT
2022-03-10T20:20:31Z
2022-03-11T04:59:21Z
ba5207b0f4054fe8963fc3e87c2bd32907516961
5ce2b9f860f7a84c3059650bb67817d59d8f4953
Update repo CMake configuration to target /W4 by default. Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
./src/coreclr/pal/tests/palsuite/composite/synchronization/nativecs_interlocked/pal_composite_native_cs.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <time.h> //#include <pthread.h> //#include "mtx_critsect.cpp" #include "mtx_critsect.h" #include "resultbuffer.h" #define LONGLONG long long #define ULONGLONG unsigned LONGLONG /*Defining Global Variables*/ int THREAD_COUNT=0; int REPEAT_COUNT=0; int GLOBAL_COUNTER=0; int USE_PROCESS_COUNT = 0; int RELATION_ID =0; int g_counter = 0; int MAX_PATH = 256; LONGLONG callibrationValue = 0; pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t g_cv = PTHREAD_COND_INITIALIZER; pthread_cond_t g_cv2 = PTHREAD_COND_INITIALIZER; CRITICAL_SECTION g_cs; /* Capture statistics for each worker thread */ struct statistics{ unsigned int processId; unsigned int operationsFailed; unsigned int operationsPassed; unsigned int operationsTotal; DWORD operationTime; unsigned int relationId; }; struct applicationStatistics{ DWORD operationTime; unsigned int relationId; unsigned int processCount; unsigned int threadCount; unsigned int repeatCount; char* buildNumber; }; ResultBuffer *resultBuffer; void* waitforworkerthreads(void*); void starttests(int); int setuptest(void); int cleanuptest(void); int GetParameters( int , char **); void incrementCounter(void); ULONGLONG GetTicks(void); ULONGLONG getPerfCallibrationValue(void); PALTEST(composite_synchronization_nativecs_interlocked_paltest_synchronization_nativecs_interlocked, "composite/synchronization/nativecs_interlocked/paltest_synchronization_nativecs_interlocked") { //Variable Declaration pthread_t pthreads[640]; int threadID[640]; int i=0; int j=0; int rtn=0; ULONGLONG startTicks = 0; /* Variables to capture the file name and the file pointer*/ char fileName[MAX_PATH]; FILE *hFile; struct statistics* buffer; int statisticsSize = 0; /*Variable to Captutre Information at the Application Level*/ struct applicationStatistics appStats; char mainFileName[MAX_PATH]; FILE *hMainFile; //Get perfCallibrationValue callibrationValue = getPerfCallibrationValue(); printf("Callibration Value for this Platform %llu \n", callibrationValue); //Get Parameters if(GetParameters(argc, argv)) { printf("Error in obtaining the parameters\n"); exit(-1); } //Assign Values to Application Statistics Members appStats.relationId=RELATION_ID; appStats.operationTime=0; appStats.buildNumber = "999.99"; appStats.processCount = USE_PROCESS_COUNT; appStats.threadCount = THREAD_COUNT; appStats.repeatCount = REPEAT_COUNT; printf("RELATION ID : %d\n", appStats.relationId); printf("Process Count : %d\n", appStats.processCount); printf("Thread Count : %d\n", appStats.threadCount); printf("Repeat Count : %d\n", appStats.repeatCount); //Open file for Application Statistics Collection snprintf(mainFileName, MAX_PATH, "main_nativecriticalsection_%d_.txt",appStats.relationId); hMainFile = fopen(mainFileName, "w+"); if(hMainFile == NULL) { printf("Error in opening main file for write\n"); } for (i=0;i<THREAD_COUNT;i++) { threadID[i] = i; } statisticsSize = sizeof(struct statistics); snprintf(fileName, MAX_PATH, "%d_thread_nativecriticalsection_%d_.txt", USE_PROCESS_COUNT, RELATION_ID); hFile = fopen(fileName, "w+"); if(hFile == NULL) { printf("Error in opening file for write for process [%d]\n", USE_PROCESS_COUNT); } // For each thread we will log operations failed (int), passed (int), total (int) // and number of ticks (DWORD) for the operations resultBuffer = new ResultBuffer( THREAD_COUNT, statisticsSize); //Call Test Case Setup Routine if (0!=setuptest()) { //Error Condition printf("Error Initializing Test Case\n"); exit(-1); } //Accquire Lock if (0!=pthread_mutex_lock(&g_mutex)) { //Error Condition printf("Error Accquiring Lock\n"); exit(-1); } //USE NATIVE METHOD TO GET TICK COUNT startTicks = GetTicks(); /*Loop to create number THREAD_COUNT number of threads*/ for (i=0;i< THREAD_COUNT;i++) { //printf("Creating Thread Count %d\n", i); //printf("Thread arrary value = %d\n", threadID[i]); rtn=pthread_create(&pthreads[i], NULL, waitforworkerthreads, &threadID[i]); if (0 != rtn) { /* ERROR Condition */ printf("Error: pthread Creat, %s \n", strerror(rtn)); exit(-1); } } //printf("Main Thread waits to recevie signal when all threads are done\n"); pthread_cond_wait(&g_cv2,&g_mutex); //printf("Main thread has received signal\n"); /*Signal Threads to Start Working*/ //printf("Raise signal for all threads to start working\n"); if (0!=pthread_cond_broadcast(&g_cv)) { //Error Condition printf("Error Broadcasting Conditional Event\n"); exit(-1); } //Release the lock if (0!=pthread_mutex_unlock(&g_mutex)) { //Error Condition printf("Error Releasing Lock\n"); exit(-1); } /*Join Threads */ while (j < THREAD_COUNT) { if (0 != pthread_join(pthreads[j],NULL)) { //Error Condition printf("Error Joining Threads\n"); exit(-1); } j++; } /*Write Application Results to File*/ //CAPTURE NATIVE TICK COUNT HERE appStats.operationTime = (DWORD)(GetTicks() - startTicks)/callibrationValue; /* Write Results to a file*/ if(hFile!= NULL) { for( i = 0; i < THREAD_COUNT; i++ ) { buffer = (struct statistics *)resultBuffer->getResultBuffer(i); fprintf(hFile, "%d,%d,%d,%d,%lu,%d\n", buffer->processId, buffer->operationsFailed, buffer->operationsPassed, buffer->operationsTotal, buffer->operationTime, buffer->relationId ); //printf("Iteration %d over\n", i); } } fclose(hFile); //Call Test Case Cleanup Routine if (0!=cleanuptest()) { //Error Condition printf("Error Cleaning up Test Case"); exit(-1); } if(hMainFile!= NULL) { printf("Writing to Main File \n"); fprintf(hMainFile, "%lu,%d,%d,%d,%d,%s\n", appStats.operationTime, appStats.relationId, appStats.processCount, appStats.threadCount, appStats.repeatCount, appStats.buildNumber); } fclose(hMainFile); return 0; } void * waitforworkerthreads(void * threadId) { int *threadParam = (int*) threadId; // printf("Thread ID : %d \n", *threadParam); //Accquire Lock if (0!=pthread_mutex_lock(&g_mutex)) { //Error Condition printf("Error Accquiring Mutex Lock in Wait for Worker Thread\n"); exit(-1); } //Increment Global Counter GLOBAL_COUNTER++; //If global counter is equal to thread count then signal main thread if (GLOBAL_COUNTER == THREAD_COUNT) { if (0!=pthread_cond_signal(&g_cv2)) { //Error Condition printf("Error in setting conditional variable\n"); exit(-1); } } //Wait for main thread to signal if (0!=pthread_cond_wait(&g_cv,&g_mutex)) { //Error Condition printf("Error waiting on conditional variable in Worker Thread\n"); exit(-1); } //Release the mutex lock if (0!=pthread_mutex_unlock(&g_mutex)) { //Error Condition printf("Error Releasing Mutex Lock in Worker Thread\n"); exit(-1); } //Start the test starttests(*threadParam); } void starttests(int threadID) { /*All threads beign executing tests cases*/ int i = 0; int Id = threadID; struct statistics stats; ULONGLONG startTime = 0; ULONGLONG endTime = 0; LONG volatile Destination; LONG Exchange; LONG Comperand; LONG result; stats.relationId = RELATION_ID; stats.processId = USE_PROCESS_COUNT; stats.operationsFailed = 0; stats.operationsPassed = 0; stats.operationsTotal = 0; stats.operationTime = 0; //Enter and Leave Critical Section in a loop REPEAT_COUNT Times startTime = GetTicks(); for (i=0;i<REPEAT_COUNT;i++) { Destination = (LONG volatile) threadID; Exchange = (LONG) i; Comperand = (LONG) threadID; result = InterlockedCompareExchange(&Destination, Exchange, Comperand); if( i != result ) { stats.operationsFailed++; stats.operationsTotal++; continue; } } stats.operationTime = (DWORD)(GetTicks() - startTime)/callibrationValue; // printf("Operation Time %d \n", stats.operationTime); if(resultBuffer->LogResult(Id, (char *)&stats)) { printf("Error while writing to shared memory, Thread Id is[??] and Process id is [%d]\n", USE_PROCESS_COUNT); } } int setuptest(void) { //Initalize Critical Section /* if (0!=MTXInitializeCriticalSection( &g_cs)) { return -1; } */ return 0; } int cleanuptest(void) { //Delete Critical Section /* if (0!=MTXDeleteCriticalSection(&g_cs)) { return -1; } */ return 0; } int GetParameters( int argc, char **argv) { if( (argc != 5) || ((argc == 1) && !strcmp(argv[1],"/?")) || !strcmp(argv[1],"/h") || !strcmp(argv[1],"/H")) { printf("PAL -Composite Native Critical Section Test\n"); printf("Usage:\n"); printf("\t[PROCESS_ID ( greater than 1] \n"); printf("\t[THREAD_COUNT ( greater than 1] \n"); printf("\t[REPEAT_COUNT ( greater than 1]\n"); printf("\t[RELATION_ID [greater than or Equal to 1]\n"); return -1; } USE_PROCESS_COUNT = atoi(argv[1]); if( USE_PROCESS_COUNT < 0) { printf("\nInvalid THREAD_COUNT number, Pass greater than 1\n"); return -1; } THREAD_COUNT = atoi(argv[2]); if( THREAD_COUNT < 1) { printf("\nInvalid THREAD_COUNT number, Pass greater than 1\n"); return -1; } REPEAT_COUNT = atoi(argv[3]); if( REPEAT_COUNT < 1) { printf("\nInvalid REPEAT_COUNT number, Pass greater than 1\n"); return -1; } RELATION_ID = atoi(argv[4]); if( RELATION_ID < 1) { printf("\nInvalid RELATION_ID number, Pass greater than 1\n"); return -1; } return 0; } void incrementCounter(void) { g_counter ++; } //Implementation borrowed from pertrace.c ULONGLONG GetTicks(void) { #ifdef i386 unsigned long a, d; asm volatile("rdtsc":"=a" (a), "=d" (d)); return ((ULONGLONG)((unsigned int)(d)) << 32) | (unsigned int)(a); #else // #error Don''t know how to get ticks on this platform return (ULONGLONG)gethrtime(); #endif // i386 } /**/ ULONGLONG getPerfCallibrationValue(void) { ULONGLONG startTicks; ULONGLONG endTicks; startTicks = GetTicks(); sleep(1); endTicks = GetTicks(); return ((endTicks-startTicks)/1000); //Return number of Ticks in One Milliseconds }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <time.h> //#include <pthread.h> //#include "mtx_critsect.cpp" #include "mtx_critsect.h" #include "resultbuffer.h" #define LONGLONG long long #define ULONGLONG unsigned LONGLONG /*Defining Global Variables*/ int THREAD_COUNT=0; int REPEAT_COUNT=0; int GLOBAL_COUNTER=0; int USE_PROCESS_COUNT = 0; int RELATION_ID =0; int g_counter = 0; int MAX_PATH = 256; LONGLONG callibrationValue = 0; pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t g_cv = PTHREAD_COND_INITIALIZER; pthread_cond_t g_cv2 = PTHREAD_COND_INITIALIZER; CRITICAL_SECTION g_cs; /* Capture statistics for each worker thread */ struct statistics{ unsigned int processId; unsigned int operationsFailed; unsigned int operationsPassed; unsigned int operationsTotal; DWORD operationTime; unsigned int relationId; }; struct applicationStatistics{ DWORD operationTime; unsigned int relationId; unsigned int processCount; unsigned int threadCount; unsigned int repeatCount; char* buildNumber; }; ResultBuffer *resultBuffer; void* waitforworkerthreads(void*); void starttests(int); int setuptest(void); int cleanuptest(void); int GetParameters( int , char **); void incrementCounter(void); ULONGLONG GetTicks(void); ULONGLONG getPerfCallibrationValue(void); PALTEST(composite_synchronization_nativecs_interlocked_paltest_synchronization_nativecs_interlocked, "composite/synchronization/nativecs_interlocked/paltest_synchronization_nativecs_interlocked") { //Variable Declaration pthread_t pthreads[640]; int threadID[640]; int i=0; int j=0; int rtn=0; ULONGLONG startTicks = 0; /* Variables to capture the file name and the file pointer*/ char fileName[MAX_PATH]; FILE *hFile; struct statistics* buffer; int statisticsSize = 0; /*Variable to Captutre Information at the Application Level*/ struct applicationStatistics appStats; char mainFileName[MAX_PATH]; FILE *hMainFile; //Get perfCallibrationValue callibrationValue = getPerfCallibrationValue(); printf("Callibration Value for this Platform %llu \n", callibrationValue); //Get Parameters if(GetParameters(argc, argv)) { printf("Error in obtaining the parameters\n"); exit(-1); } //Assign Values to Application Statistics Members appStats.relationId=RELATION_ID; appStats.operationTime=0; appStats.buildNumber = "999.99"; appStats.processCount = USE_PROCESS_COUNT; appStats.threadCount = THREAD_COUNT; appStats.repeatCount = REPEAT_COUNT; printf("RELATION ID : %d\n", appStats.relationId); printf("Process Count : %d\n", appStats.processCount); printf("Thread Count : %d\n", appStats.threadCount); printf("Repeat Count : %d\n", appStats.repeatCount); //Open file for Application Statistics Collection snprintf(mainFileName, MAX_PATH, "main_nativecriticalsection_%d_.txt",appStats.relationId); hMainFile = fopen(mainFileName, "w+"); if(hMainFile == NULL) { printf("Error in opening main file for write\n"); } for (i=0;i<THREAD_COUNT;i++) { threadID[i] = i; } statisticsSize = sizeof(struct statistics); snprintf(fileName, MAX_PATH, "%d_thread_nativecriticalsection_%d_.txt", USE_PROCESS_COUNT, RELATION_ID); hFile = fopen(fileName, "w+"); if(hFile == NULL) { printf("Error in opening file for write for process [%d]\n", USE_PROCESS_COUNT); } // For each thread we will log operations failed (int), passed (int), total (int) // and number of ticks (DWORD) for the operations resultBuffer = new ResultBuffer( THREAD_COUNT, statisticsSize); //Call Test Case Setup Routine if (0!=setuptest()) { //Error Condition printf("Error Initializing Test Case\n"); exit(-1); } //Accquire Lock if (0!=pthread_mutex_lock(&g_mutex)) { //Error Condition printf("Error Accquiring Lock\n"); exit(-1); } //USE NATIVE METHOD TO GET TICK COUNT startTicks = GetTicks(); /*Loop to create number THREAD_COUNT number of threads*/ for (i=0;i< THREAD_COUNT;i++) { //printf("Creating Thread Count %d\n", i); //printf("Thread arrary value = %d\n", threadID[i]); rtn=pthread_create(&pthreads[i], NULL, waitforworkerthreads, &threadID[i]); if (0 != rtn) { /* ERROR Condition */ printf("Error: pthread Creat, %s \n", strerror(rtn)); exit(-1); } } //printf("Main Thread waits to recevie signal when all threads are done\n"); pthread_cond_wait(&g_cv2,&g_mutex); //printf("Main thread has received signal\n"); /*Signal Threads to Start Working*/ //printf("Raise signal for all threads to start working\n"); if (0!=pthread_cond_broadcast(&g_cv)) { //Error Condition printf("Error Broadcasting Conditional Event\n"); exit(-1); } //Release the lock if (0!=pthread_mutex_unlock(&g_mutex)) { //Error Condition printf("Error Releasing Lock\n"); exit(-1); } /*Join Threads */ while (j < THREAD_COUNT) { if (0 != pthread_join(pthreads[j],NULL)) { //Error Condition printf("Error Joining Threads\n"); exit(-1); } j++; } /*Write Application Results to File*/ //CAPTURE NATIVE TICK COUNT HERE appStats.operationTime = (DWORD)(GetTicks() - startTicks)/callibrationValue; /* Write Results to a file*/ if(hFile!= NULL) { for( i = 0; i < THREAD_COUNT; i++ ) { buffer = (struct statistics *)resultBuffer->getResultBuffer(i); fprintf(hFile, "%d,%d,%d,%d,%lu,%d\n", buffer->processId, buffer->operationsFailed, buffer->operationsPassed, buffer->operationsTotal, buffer->operationTime, buffer->relationId ); //printf("Iteration %d over\n", i); } } fclose(hFile); //Call Test Case Cleanup Routine if (0!=cleanuptest()) { //Error Condition printf("Error Cleaning up Test Case"); exit(-1); } if(hMainFile!= NULL) { printf("Writing to Main File \n"); fprintf(hMainFile, "%lu,%d,%d,%d,%d,%s\n", appStats.operationTime, appStats.relationId, appStats.processCount, appStats.threadCount, appStats.repeatCount, appStats.buildNumber); } fclose(hMainFile); return 0; } void * waitforworkerthreads(void * threadId) { int *threadParam = (int*) threadId; // printf("Thread ID : %d \n", *threadParam); //Accquire Lock if (0!=pthread_mutex_lock(&g_mutex)) { //Error Condition printf("Error Accquiring Mutex Lock in Wait for Worker Thread\n"); exit(-1); } //Increment Global Counter GLOBAL_COUNTER++; //If global counter is equal to thread count then signal main thread if (GLOBAL_COUNTER == THREAD_COUNT) { if (0!=pthread_cond_signal(&g_cv2)) { //Error Condition printf("Error in setting conditional variable\n"); exit(-1); } } //Wait for main thread to signal if (0!=pthread_cond_wait(&g_cv,&g_mutex)) { //Error Condition printf("Error waiting on conditional variable in Worker Thread\n"); exit(-1); } //Release the mutex lock if (0!=pthread_mutex_unlock(&g_mutex)) { //Error Condition printf("Error Releasing Mutex Lock in Worker Thread\n"); exit(-1); } //Start the test starttests(*threadParam); } void starttests(int threadID) { /*All threads beign executing tests cases*/ int i = 0; int Id = threadID; struct statistics stats; ULONGLONG startTime = 0; ULONGLONG endTime = 0; LONG volatile Destination; LONG Exchange; LONG Comperand; LONG result; stats.relationId = RELATION_ID; stats.processId = USE_PROCESS_COUNT; stats.operationsFailed = 0; stats.operationsPassed = 0; stats.operationsTotal = 0; stats.operationTime = 0; //Enter and Leave Critical Section in a loop REPEAT_COUNT Times startTime = GetTicks(); for (i=0;i<REPEAT_COUNT;i++) { Destination = (LONG volatile) threadID; Exchange = (LONG) i; Comperand = (LONG) threadID; result = InterlockedCompareExchange(&Destination, Exchange, Comperand); if( i != result ) { stats.operationsFailed++; stats.operationsTotal++; continue; } } stats.operationTime = (DWORD)(GetTicks() - startTime)/callibrationValue; // printf("Operation Time %d \n", stats.operationTime); if(resultBuffer->LogResult(Id, (char *)&stats)) { printf("Error while writing to shared memory, Thread Id is[??] and Process id is [%d]\n", USE_PROCESS_COUNT); } } int setuptest(void) { //Initalize Critical Section /* if (0!=MTXInitializeCriticalSection( &g_cs)) { return -1; } */ return 0; } int cleanuptest(void) { //Delete Critical Section /* if (0!=MTXDeleteCriticalSection(&g_cs)) { return -1; } */ return 0; } int GetParameters( int argc, char **argv) { if( (argc != 5) || ((argc == 1) && !strcmp(argv[1],"/?")) || !strcmp(argv[1],"/h") || !strcmp(argv[1],"/H")) { printf("PAL -Composite Native Critical Section Test\n"); printf("Usage:\n"); printf("\t[PROCESS_ID ( greater than 1] \n"); printf("\t[THREAD_COUNT ( greater than 1] \n"); printf("\t[REPEAT_COUNT ( greater than 1]\n"); printf("\t[RELATION_ID [greater than or Equal to 1]\n"); return -1; } USE_PROCESS_COUNT = atoi(argv[1]); if( USE_PROCESS_COUNT < 0) { printf("\nInvalid THREAD_COUNT number, Pass greater than 1\n"); return -1; } THREAD_COUNT = atoi(argv[2]); if( THREAD_COUNT < 1) { printf("\nInvalid THREAD_COUNT number, Pass greater than 1\n"); return -1; } REPEAT_COUNT = atoi(argv[3]); if( REPEAT_COUNT < 1) { printf("\nInvalid REPEAT_COUNT number, Pass greater than 1\n"); return -1; } RELATION_ID = atoi(argv[4]); if( RELATION_ID < 1) { printf("\nInvalid RELATION_ID number, Pass greater than 1\n"); return -1; } return 0; } void incrementCounter(void) { g_counter ++; } //Implementation borrowed from pertrace.c ULONGLONG GetTicks(void) { #ifdef i386 unsigned long a, d; asm volatile("rdtsc":"=a" (a), "=d" (d)); return ((ULONGLONG)((unsigned int)(d)) << 32) | (unsigned int)(a); #else // #error Don''t know how to get ticks on this platform return (ULONGLONG)gethrtime(); #endif // i386 } /**/ ULONGLONG getPerfCallibrationValue(void) { ULONGLONG startTicks; ULONGLONG endTicks; startTicks = GetTicks(); sleep(1); endTicks = GetTicks(); return ((endTicks-startTicks)/1000); //Return number of Ticks in One Milliseconds }
-1
dotnet/runtime
66,474
Update repo CMake configuration to target /W4 by default
Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
AaronRobinsonMSFT
2022-03-10T20:20:31Z
2022-03-11T04:59:21Z
ba5207b0f4054fe8963fc3e87c2bd32907516961
5ce2b9f860f7a84c3059650bb67817d59d8f4953
Update repo CMake configuration to target /W4 by default. Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
./src/coreclr/pal/tests/palsuite/compilableTests.txt
c_runtime/abs/test1/paltest_abs_test1 c_runtime/acos/test1/paltest_acos_test1 c_runtime/acosf/test1/paltest_acosf_test1 c_runtime/acosh/test1/paltest_acosh_test1 c_runtime/acoshf/test1/paltest_acoshf_test1 c_runtime/asin/test1/paltest_asin_test1 c_runtime/asinf/test1/paltest_asinf_test1 c_runtime/asinh/test1/paltest_asinh_test1 c_runtime/asinhf/test1/paltest_asinhf_test1 c_runtime/atan/test1/paltest_atan_test1 c_runtime/atan2/test1/paltest_atan2_test1 c_runtime/atan2f/test1/paltest_atan2f_test1 c_runtime/atanf/test1/paltest_atanf_test1 c_runtime/atanh/test1/paltest_atanh_test1 c_runtime/atanhf/test1/paltest_atanhf_test1 c_runtime/atof/test1/paltest_atof_test1 c_runtime/atoi/test1/paltest_atoi_test1 c_runtime/bsearch/test1/paltest_bsearch_test1 c_runtime/bsearch/test2/paltest_bsearch_test2 c_runtime/cbrt/test1/paltest_cbrt_test1 c_runtime/cbrtf/test1/paltest_cbrtf_test1 c_runtime/ceil/test1/paltest_ceil_test1 c_runtime/ceilf/test1/paltest_ceilf_test1 c_runtime/cos/test1/paltest_cos_test1 c_runtime/cosf/test1/paltest_cosf_test1 c_runtime/cosh/test1/paltest_cosh_test1 c_runtime/coshf/test1/paltest_coshf_test1 c_runtime/errno/test1/paltest_errno_test1 c_runtime/errno/test2/paltest_errno_test2 c_runtime/exit/test1/paltest_exit_test1 c_runtime/exit/test2/paltest_exit_test2 c_runtime/exp/test1/paltest_exp_test1 c_runtime/expf/test1/paltest_expf_test1 c_runtime/fabs/test1/paltest_fabs_test1 c_runtime/fabsf/test1/paltest_fabsf_test1 c_runtime/fclose/test1/paltest_fclose_test1 c_runtime/fclose/test2/paltest_fclose_test2 c_runtime/ferror/test1/paltest_ferror_test1 c_runtime/ferror/test2/paltest_ferror_test2 c_runtime/fflush/test1/paltest_fflush_test1 c_runtime/fgets/test1/paltest_fgets_test1 c_runtime/fgets/test2/paltest_fgets_test2 c_runtime/fgets/test3/paltest_fgets_test3 c_runtime/floor/test1/paltest_floor_test1 c_runtime/floorf/test1/paltest_floorf_test1 c_runtime/fma/test1/paltest_fma_test1 c_runtime/fmaf/test1/paltest_fmaf_test1 c_runtime/fmod/test1/paltest_fmod_test1 c_runtime/fmodf/test1/paltest_fmodf_test1 c_runtime/fopen/test1/paltest_fopen_test1 c_runtime/fopen/test2/paltest_fopen_test2 c_runtime/fopen/test3/paltest_fopen_test3 c_runtime/fopen/test4/paltest_fopen_test4 c_runtime/fopen/test5/paltest_fopen_test5 c_runtime/fopen/test6/paltest_fopen_test6 c_runtime/fopen/test7/paltest_fopen_test7 c_runtime/fprintf/test1/paltest_fprintf_test1 c_runtime/fprintf/test10/paltest_fprintf_test10 c_runtime/fprintf/test11/paltest_fprintf_test11 c_runtime/fprintf/test12/paltest_fprintf_test12 c_runtime/fprintf/test13/paltest_fprintf_test13 c_runtime/fprintf/test14/paltest_fprintf_test14 c_runtime/fprintf/test15/paltest_fprintf_test15 c_runtime/fprintf/test16/paltest_fprintf_test16 c_runtime/fprintf/test17/paltest_fprintf_test17 c_runtime/fprintf/test18/paltest_fprintf_test18 c_runtime/fprintf/test19/paltest_fprintf_test19 c_runtime/fprintf/test2/paltest_fprintf_test2 c_runtime/fprintf/test3/paltest_fprintf_test3 c_runtime/fprintf/test4/paltest_fprintf_test4 c_runtime/fprintf/test5/paltest_fprintf_test5 c_runtime/fprintf/test6/paltest_fprintf_test6 c_runtime/fprintf/test7/paltest_fprintf_test7 c_runtime/fprintf/test8/paltest_fprintf_test8 c_runtime/fprintf/test9/paltest_fprintf_test9 c_runtime/fputs/test1/paltest_fputs_test1 c_runtime/fputs/test2/paltest_fputs_test2 c_runtime/fread/test1/paltest_fread_test1 c_runtime/fread/test2/paltest_fread_test2 c_runtime/fread/test3/paltest_fread_test3 c_runtime/free/test1/paltest_free_test1 c_runtime/fseek/test1/paltest_fseek_test1 c_runtime/ftell/test1/paltest_ftell_test1 c_runtime/fwprintf/test1/paltest_fwprintf_test1 c_runtime/fwprintf/test10/paltest_fwprintf_test10 c_runtime/fwprintf/test11/paltest_fwprintf_test11 c_runtime/fwprintf/test12/paltest_fwprintf_test12 c_runtime/fwprintf/test13/paltest_fwprintf_test13 c_runtime/fwprintf/test14/paltest_fwprintf_test14 c_runtime/fwprintf/test15/paltest_fwprintf_test15 c_runtime/fwprintf/test16/paltest_fwprintf_test16 c_runtime/fwprintf/test17/paltest_fwprintf_test17 c_runtime/fwprintf/test18/paltest_fwprintf_test18 c_runtime/fwprintf/test19/paltest_fwprintf_test19 c_runtime/fwprintf/test2/paltest_fwprintf_test2 c_runtime/fwprintf/test3/paltest_fwprintf_test3 c_runtime/fwprintf/test4/paltest_fwprintf_test4 c_runtime/fwprintf/test5/paltest_fwprintf_test5 c_runtime/fwprintf/test6/paltest_fwprintf_test6 c_runtime/fwprintf/test7/paltest_fwprintf_test7 c_runtime/fwprintf/test8/paltest_fwprintf_test8 c_runtime/fwprintf/test9/paltest_fwprintf_test9 c_runtime/fwrite/test1/paltest_fwrite_test1 c_runtime/getenv/test1/paltest_getenv_test1 c_runtime/getenv/test2/paltest_getenv_test2 c_runtime/getenv/test3/paltest_getenv_test3 c_runtime/ilogb/test1/paltest_ilogb_test1 c_runtime/ilogbf/test1/paltest_ilogbf_test1 c_runtime/isalnum/test1/paltest_isalnum_test1 c_runtime/isalpha/test1/paltest_isalpha_test1 c_runtime/isdigit/test1/paltest_isdigit_test1 c_runtime/islower/test1/paltest_islower_test1 c_runtime/isprint/test1/paltest_isprint_test1 c_runtime/isprint/test2/paltest_isprint_test2 c_runtime/isspace/test1/paltest_isspace_test1 c_runtime/isupper/test1/paltest_isupper_test1 c_runtime/iswdigit/test1/paltest_iswdigit_test1 c_runtime/iswspace/test1/paltest_iswspace_test1 c_runtime/iswupper/test1/paltest_iswupper_test1 c_runtime/isxdigit/test1/paltest_isxdigit_test1 c_runtime/llabs/test1/paltest_llabs_test1 c_runtime/log/test1/paltest_log_test1 c_runtime/log10/test1/paltest_log10_test1 c_runtime/log10f/test1/paltest_log10f_test1 c_runtime/log2/test1/paltest_log2_test1 c_runtime/log2f/test1/paltest_log2f_test1 c_runtime/logf/test1/paltest_logf_test1 c_runtime/malloc/test1/paltest_malloc_test1 c_runtime/malloc/test2/paltest_malloc_test2 c_runtime/memchr/test1/paltest_memchr_test1 c_runtime/memcmp/test1/paltest_memcmp_test1 c_runtime/memcpy/test1/paltest_memcpy_test1 c_runtime/memmove/test1/paltest_memmove_test1 c_runtime/memset/test1/paltest_memset_test1 c_runtime/modf/test1/paltest_modf_test1 c_runtime/modff/test1/paltest_modff_test1 c_runtime/pow/test1/paltest_pow_test1 c_runtime/powf/test1/paltest_powf_test1 c_runtime/printf/test1/paltest_printf_test1 c_runtime/printf/test10/paltest_printf_test10 c_runtime/printf/test11/paltest_printf_test11 c_runtime/printf/test12/paltest_printf_test12 c_runtime/printf/test13/paltest_printf_test13 c_runtime/printf/test14/paltest_printf_test14 c_runtime/printf/test15/paltest_printf_test15 c_runtime/printf/test16/paltest_printf_test16 c_runtime/printf/test17/paltest_printf_test17 c_runtime/printf/test18/paltest_printf_test18 c_runtime/printf/test19/paltest_printf_test19 c_runtime/printf/test2/paltest_printf_test2 c_runtime/printf/test3/paltest_printf_test3 c_runtime/printf/test4/paltest_printf_test4 c_runtime/printf/test5/paltest_printf_test5 c_runtime/printf/test6/paltest_printf_test6 c_runtime/printf/test7/paltest_printf_test7 c_runtime/printf/test8/paltest_printf_test8 c_runtime/printf/test9/paltest_printf_test9 c_runtime/qsort/test1/paltest_qsort_test1 c_runtime/qsort/test2/paltest_qsort_test2 c_runtime/rand_srand/test1/paltest_rand_srand_test1 c_runtime/realloc/test1/paltest_realloc_test1 c_runtime/sin/test1/paltest_sin_test1 c_runtime/sincos/test1/paltest_sincos_test1 c_runtime/sincosf/test1/paltest_sincosf_test1 c_runtime/sinf/test1/paltest_sinf_test1 c_runtime/sinh/test1/paltest_sinh_test1 c_runtime/sinhf/test1/paltest_sinhf_test1 c_runtime/sprintf_s/test1/paltest_sprintf_test1 c_runtime/sprintf_s/test10/paltest_sprintf_test10 c_runtime/sprintf_s/test11/paltest_sprintf_test11 c_runtime/sprintf_s/test12/paltest_sprintf_test12 c_runtime/sprintf_s/test13/paltest_sprintf_test13 c_runtime/sprintf_s/test14/paltest_sprintf_test14 c_runtime/sprintf_s/test15/paltest_sprintf_test15 c_runtime/sprintf_s/test16/paltest_sprintf_test16 c_runtime/sprintf_s/test17/paltest_sprintf_test17 c_runtime/sprintf_s/test18/paltest_sprintf_test18 c_runtime/sprintf_s/test19/paltest_sprintf_test19 c_runtime/sprintf_s/test2/paltest_sprintf_test2 c_runtime/sprintf_s/test3/paltest_sprintf_test3 c_runtime/sprintf_s/test4/paltest_sprintf_test4 c_runtime/sprintf_s/test6/paltest_sprintf_test6 c_runtime/sprintf_s/test7/paltest_sprintf_test7 c_runtime/sprintf_s/test8/paltest_sprintf_test8 c_runtime/sprintf_s/test9/paltest_sprintf_test9 c_runtime/sqrt/test1/paltest_sqrt_test1 c_runtime/sqrtf/test1/paltest_sqrtf_test1 c_runtime/sscanf_s/test1/paltest_sscanf_test1 c_runtime/sscanf_s/test10/paltest_sscanf_test10 c_runtime/sscanf_s/test11/paltest_sscanf_test11 c_runtime/sscanf_s/test12/paltest_sscanf_test12 c_runtime/sscanf_s/test13/paltest_sscanf_test13 c_runtime/sscanf_s/test14/paltest_sscanf_test14 c_runtime/sscanf_s/test15/paltest_sscanf_test15 c_runtime/sscanf_s/test16/paltest_sscanf_test16 c_runtime/sscanf_s/test17/paltest_sscanf_test17 c_runtime/sscanf_s/test2/paltest_sscanf_test2 c_runtime/sscanf_s/test3/paltest_sscanf_test3 c_runtime/sscanf_s/test4/paltest_sscanf_test4 c_runtime/sscanf_s/test5/paltest_sscanf_test5 c_runtime/sscanf_s/test6/paltest_sscanf_test6 c_runtime/sscanf_s/test7/paltest_sscanf_test7 c_runtime/sscanf_s/test8/paltest_sscanf_test8 c_runtime/sscanf_s/test9/paltest_sscanf_test9 c_runtime/strcat/test1/paltest_strcat_test1 c_runtime/strchr/test1/paltest_strchr_test1 c_runtime/strcmp/test1/paltest_strcmp_test1 c_runtime/strcpy/test1/paltest_strcpy_test1 c_runtime/strcspn/test1/paltest_strcspn_test1 c_runtime/strlen/test1/paltest_strlen_test1 c_runtime/strncat/test1/paltest_strncat_test1 c_runtime/strncmp/test1/paltest_strncmp_test1 c_runtime/strncpy/test1/paltest_strncpy_test1 c_runtime/strpbrk/test1/paltest_strpbrk_test1 c_runtime/strrchr/test1/paltest_strrchr_test1 c_runtime/strspn/test1/paltest_strspn_test1 c_runtime/strstr/test1/paltest_strstr_test1 c_runtime/strtod/test1/paltest_strtod_test1 c_runtime/strtod/test2/paltest_strtod_test2 c_runtime/strtok/test1/paltest_strtok_test1 c_runtime/strtoul/test1/paltest_strtoul_test1 c_runtime/swprintf/test1/paltest_swprintf_test1 c_runtime/swprintf/test10/paltest_swprintf_test10 c_runtime/swprintf/test11/paltest_swprintf_test11 c_runtime/swprintf/test12/paltest_swprintf_test12 c_runtime/swprintf/test13/paltest_swprintf_test13 c_runtime/swprintf/test14/paltest_swprintf_test14 c_runtime/swprintf/test15/paltest_swprintf_test15 c_runtime/swprintf/test16/paltest_swprintf_test16 c_runtime/swprintf/test17/paltest_swprintf_test17 c_runtime/swprintf/test18/paltest_swprintf_test18 c_runtime/swprintf/test19/paltest_swprintf_test19 c_runtime/swprintf/test2/paltest_swprintf_test2 c_runtime/swprintf/test3/paltest_swprintf_test3 c_runtime/swprintf/test4/paltest_swprintf_test4 c_runtime/swprintf/test6/paltest_swprintf_test6 c_runtime/swprintf/test7/paltest_swprintf_test7 c_runtime/swprintf/test8/paltest_swprintf_test8 c_runtime/swprintf/test9/paltest_swprintf_test9 c_runtime/swscanf/test1/paltest_swscanf_test1 c_runtime/swscanf/test10/paltest_swscanf_test10 c_runtime/swscanf/test11/paltest_swscanf_test11 c_runtime/swscanf/test12/paltest_swscanf_test12 c_runtime/swscanf/test13/paltest_swscanf_test13 c_runtime/swscanf/test14/paltest_swscanf_test14 c_runtime/swscanf/test15/paltest_swscanf_test15 c_runtime/swscanf/test16/paltest_swscanf_test16 c_runtime/swscanf/test17/paltest_swscanf_test17 c_runtime/swscanf/test2/paltest_swscanf_test2 c_runtime/swscanf/test3/paltest_swscanf_test3 c_runtime/swscanf/test4/paltest_swscanf_test4 c_runtime/swscanf/test5/paltest_swscanf_test5 c_runtime/swscanf/test6/paltest_swscanf_test6 c_runtime/swscanf/test7/paltest_swscanf_test7 c_runtime/swscanf/test8/paltest_swscanf_test8 c_runtime/swscanf/test9/paltest_swscanf_test9 c_runtime/tan/test1/paltest_tan_test1 c_runtime/tanf/test1/paltest_tanf_test1 c_runtime/tanh/test1/paltest_tanh_test1 c_runtime/tanhf/test1/paltest_tanhf_test1 c_runtime/time/test1/paltest_time_test1 c_runtime/tolower/test1/paltest_tolower_test1 c_runtime/toupper/test1/paltest_toupper_test1 c_runtime/towlower/test1/paltest_towlower_test1 c_runtime/towupper/test1/paltest_towupper_test1 c_runtime/vfprintf/test1/paltest_vfprintf_test1 c_runtime/vfprintf/test10/paltest_vfprintf_test10 c_runtime/vfprintf/test11/paltest_vfprintf_test11 c_runtime/vfprintf/test12/paltest_vfprintf_test12 c_runtime/vfprintf/test13/paltest_vfprintf_test13 c_runtime/vfprintf/test14/paltest_vfprintf_test14 c_runtime/vfprintf/test15/paltest_vfprintf_test15 c_runtime/vfprintf/test16/paltest_vfprintf_test16 c_runtime/vfprintf/test17/paltest_vfprintf_test17 c_runtime/vfprintf/test18/paltest_vfprintf_test18 c_runtime/vfprintf/test19/paltest_vfprintf_test19 c_runtime/vfprintf/test2/paltest_vfprintf_test2 c_runtime/vfprintf/test3/paltest_vfprintf_test3 c_runtime/vfprintf/test4/paltest_vfprintf_test4 c_runtime/vfprintf/test5/paltest_vfprintf_test5 c_runtime/vfprintf/test6/paltest_vfprintf_test6 c_runtime/vfprintf/test7/paltest_vfprintf_test7 c_runtime/vfprintf/test8/paltest_vfprintf_test8 c_runtime/vfprintf/test9/paltest_vfprintf_test9 c_runtime/vprintf/test10/paltest_vprintf_test10 c_runtime/vprintf/test11/paltest_vprintf_test11 c_runtime/vprintf/test12/paltest_vprintf_test12 c_runtime/vprintf/test13/paltest_vprintf_test13 c_runtime/vprintf/test14/paltest_vprintf_test14 c_runtime/vprintf/test15/paltest_vprintf_test15 c_runtime/vprintf/test16/paltest_vprintf_test16 c_runtime/vprintf/test17/paltest_vprintf_test17 c_runtime/vprintf/test18/paltest_vprintf_test18 c_runtime/vprintf/test19/paltest_vprintf_test19 c_runtime/vprintf/test2/paltest_vprintf_test2 c_runtime/vprintf/test3/paltest_vprintf_test3 c_runtime/vprintf/test4/paltest_vprintf_test4 c_runtime/vprintf/test5/paltest_vprintf_test5 c_runtime/vprintf/test6/paltest_vprintf_test6 c_runtime/vprintf/test7/paltest_vprintf_test7 c_runtime/vprintf/test8/paltest_vprintf_test8 c_runtime/vprintf/test9/paltest_vprintf_test9 c_runtime/vsprintf/test1/paltest_vsprintf_test1 c_runtime/vsprintf/test10/paltest_vsprintf_test10 c_runtime/vsprintf/test11/paltest_vsprintf_test11 c_runtime/vsprintf/test12/paltest_vsprintf_test12 c_runtime/vsprintf/test13/paltest_vsprintf_test13 c_runtime/vsprintf/test14/paltest_vsprintf_test14 c_runtime/vsprintf/test15/paltest_vsprintf_test15 c_runtime/vsprintf/test16/paltest_vsprintf_test16 c_runtime/vsprintf/test17/paltest_vsprintf_test17 c_runtime/vsprintf/test18/paltest_vsprintf_test18 c_runtime/vsprintf/test19/paltest_vsprintf_test19 c_runtime/vsprintf/test2/paltest_vsprintf_test2 c_runtime/vsprintf/test3/paltest_vsprintf_test3 c_runtime/vsprintf/test4/paltest_vsprintf_test4 c_runtime/vsprintf/test6/paltest_vsprintf_test6 c_runtime/vsprintf/test7/paltest_vsprintf_test7 c_runtime/vsprintf/test8/paltest_vsprintf_test8 c_runtime/vsprintf/test9/paltest_vsprintf_test9 c_runtime/vswprintf/test1/paltest_vswprintf_test1 c_runtime/vswprintf/test10/paltest_vswprintf_test10 c_runtime/vswprintf/test11/paltest_vswprintf_test11 c_runtime/vswprintf/test12/paltest_vswprintf_test12 c_runtime/vswprintf/test13/paltest_vswprintf_test13 c_runtime/vswprintf/test14/paltest_vswprintf_test14 c_runtime/vswprintf/test15/paltest_vswprintf_test15 c_runtime/vswprintf/test16/paltest_vswprintf_test16 c_runtime/vswprintf/test17/paltest_vswprintf_test17 c_runtime/vswprintf/test18/paltest_vswprintf_test18 c_runtime/vswprintf/test19/paltest_vswprintf_test19 c_runtime/vswprintf/test2/paltest_vswprintf_test2 c_runtime/vswprintf/test3/paltest_vswprintf_test3 c_runtime/vswprintf/test4/paltest_vswprintf_test4 c_runtime/vswprintf/test6/paltest_vswprintf_test6 c_runtime/vswprintf/test7/paltest_vswprintf_test7 c_runtime/vswprintf/test8/paltest_vswprintf_test8 c_runtime/vswprintf/test9/paltest_vswprintf_test9 c_runtime/wcscat/test1/paltest_wcscat_test1 c_runtime/wcschr/test1/paltest_wcschr_test1 c_runtime/wcscmp/test1/paltest_wcscmp_test1 c_runtime/wcscpy/test1/paltest_wcscpy_test1 c_runtime/wcslen/test1/paltest_wcslen_test1 c_runtime/wcsncmp/test1/paltest_wcsncmp_test1 c_runtime/wcsncpy/test1/paltest_wcsncpy_test1 c_runtime/wcspbrk/test1/paltest_wcspbrk_test1 c_runtime/wcsrchr/test1/paltest_wcsrchr_test1 c_runtime/wcsstr/test1/paltest_wcsstr_test1 c_runtime/wcstod/test1/paltest_wcstod_test1 c_runtime/wcstod/test2/paltest_wcstod_test2 c_runtime/wcstoul/test1/paltest_wcstoul_test1 c_runtime/wcstoul/test2/paltest_wcstoul_test2 c_runtime/wcstoul/test3/paltest_wcstoul_test3 c_runtime/wcstoul/test4/paltest_wcstoul_test4 c_runtime/wcstoul/test5/paltest_wcstoul_test5 c_runtime/wcstoul/test6/paltest_wcstoul_test6 c_runtime/wprintf/test1/paltest_wprintf_test1 c_runtime/wprintf/test2/paltest_wprintf_test2 c_runtime/_alloca/test1/paltest_alloca_test1 c_runtime/_fdopen/test1/paltest_fdopen_test1 c_runtime/_finite/test1/paltest_finite_test1 c_runtime/_finitef/test1/paltest_finitef_test1 c_runtime/_isnan/test1/paltest_isnan_test1 c_runtime/_isnanf/test1/paltest_isnanf_test1 c_runtime/_itow/test1/paltest_itow_test1 c_runtime/_putenv/test1/paltest_putenv_test1 c_runtime/_putenv/test2/paltest_putenv_test2 c_runtime/_putenv/test3/paltest_putenv_test3 c_runtime/_putenv/test4/paltest_putenv_test4 c_runtime/_rotl/test1/paltest_rotl_test1 c_runtime/_rotr/test1/paltest_rotr_test1 c_runtime/_snprintf_s/test1/paltest_snprintf_test1 c_runtime/_snprintf_s/test10/paltest_snprintf_test10 c_runtime/_snprintf_s/test11/paltest_snprintf_test11 c_runtime/_snprintf_s/test12/paltest_snprintf_test12 c_runtime/_snprintf_s/test13/paltest_snprintf_test13 c_runtime/_snprintf_s/test14/paltest_snprintf_test14 c_runtime/_snprintf_s/test15/paltest_snprintf_test15 c_runtime/_snprintf_s/test16/paltest_snprintf_test16 c_runtime/_snprintf_s/test17/paltest_snprintf_test17 c_runtime/_snprintf_s/test18/paltest_snprintf_test18 c_runtime/_snprintf_s/test19/paltest_snprintf_test19 c_runtime/_snprintf_s/test2/paltest_snprintf_test2 c_runtime/_snprintf_s/test3/paltest_snprintf_test3 c_runtime/_snprintf_s/test4/paltest_snprintf_test4 c_runtime/_snprintf_s/test6/paltest_snprintf_test6 c_runtime/_snprintf_s/test7/paltest_snprintf_test7 c_runtime/_snprintf_s/test8/paltest_snprintf_test8 c_runtime/_snprintf_s/test9/paltest_snprintf_test9 c_runtime/_snwprintf_s/test1/paltest_snwprintf_test1 c_runtime/_snwprintf_s/test10/paltest_snwprintf_test10 c_runtime/_snwprintf_s/test11/paltest_snwprintf_test11 c_runtime/_snwprintf_s/test12/paltest_snwprintf_test12 c_runtime/_snwprintf_s/test13/paltest_snwprintf_test13 c_runtime/_snwprintf_s/test14/paltest_snwprintf_test14 c_runtime/_snwprintf_s/test15/paltest_snwprintf_test15 c_runtime/_snwprintf_s/test16/paltest_snwprintf_test16 c_runtime/_snwprintf_s/test17/paltest_snwprintf_test17 c_runtime/_snwprintf_s/test18/paltest_snwprintf_test18 c_runtime/_snwprintf_s/test19/paltest_snwprintf_test19 c_runtime/_snwprintf_s/test2/paltest_snwprintf_test2 c_runtime/_snwprintf_s/test3/paltest_snwprintf_test3 c_runtime/_snwprintf_s/test4/paltest_snwprintf_test4 c_runtime/_snwprintf_s/test6/paltest_snwprintf_test6 c_runtime/_snwprintf_s/test7/paltest_snwprintf_test7 c_runtime/_snwprintf_s/test8/paltest_snwprintf_test8 c_runtime/_snwprintf_s/test9/paltest_snwprintf_test9 c_runtime/_stricmp/test1/paltest_stricmp_test1 c_runtime/_strnicmp/test1/paltest_strnicmp_test1 c_runtime/_vsnprintf_s/test1/paltest_vsnprintf_test1 c_runtime/_vsnprintf_s/test10/paltest_vsnprintf_test10 c_runtime/_vsnprintf_s/test11/paltest_vsnprintf_test11 c_runtime/_vsnprintf_s/test12/paltest_vsnprintf_test12 c_runtime/_vsnprintf_s/test13/paltest_vsnprintf_test13 c_runtime/_vsnprintf_s/test14/paltest_vsnprintf_test14 c_runtime/_vsnprintf_s/test15/paltest_vsnprintf_test15 c_runtime/_vsnprintf_s/test16/paltest_vsnprintf_test16 c_runtime/_vsnprintf_s/test17/paltest_vsnprintf_test17 c_runtime/_vsnprintf_s/test18/paltest_vsnprintf_test18 c_runtime/_vsnprintf_s/test19/paltest_vsnprintf_test19 c_runtime/_vsnprintf_s/test2/paltest_vsnprintf_test2 c_runtime/_vsnprintf_s/test3/paltest_vsnprintf_test3 c_runtime/_vsnprintf_s/test4/paltest_vsnprintf_test4 c_runtime/_vsnprintf_s/test6/paltest_vsnprintf_test6 c_runtime/_vsnprintf_s/test7/paltest_vsnprintf_test7 c_runtime/_vsnprintf_s/test8/paltest_vsnprintf_test8 c_runtime/_vsnprintf_s/test9/paltest_vsnprintf_test9 c_runtime/_vsnwprintf_s/test1/paltest_vsnwprintf_test1 c_runtime/_vsnwprintf_s/test10/paltest_vsnwprintf_test10 c_runtime/_vsnwprintf_s/test11/paltest_vsnwprintf_test11 c_runtime/_vsnwprintf_s/test12/paltest_vsnwprintf_test12 c_runtime/_vsnwprintf_s/test13/paltest_vsnwprintf_test13 c_runtime/_vsnwprintf_s/test14/paltest_vsnwprintf_test14 c_runtime/_vsnwprintf_s/test15/paltest_vsnwprintf_test15 c_runtime/_vsnwprintf_s/test16/paltest_vsnwprintf_test16 c_runtime/_vsnwprintf_s/test17/paltest_vsnwprintf_test17 c_runtime/_vsnwprintf_s/test18/paltest_vsnwprintf_test18 c_runtime/_vsnwprintf_s/test19/paltest_vsnwprintf_test19 c_runtime/_vsnwprintf_s/test2/paltest_vsnwprintf_test2 c_runtime/_vsnwprintf_s/test3/paltest_vsnwprintf_test3 c_runtime/_vsnwprintf_s/test4/paltest_vsnwprintf_test4 c_runtime/_vsnwprintf_s/test6/paltest_vsnwprintf_test6 c_runtime/_vsnwprintf_s/test7/paltest_vsnwprintf_test7 c_runtime/_vsnwprintf_s/test8/paltest_vsnwprintf_test8 c_runtime/_vsnwprintf_s/test9/paltest_vsnwprintf_test9 c_runtime/_wcsicmp/test1/paltest_wcsicmp_test1 c_runtime/_wcslwr_s/test1/paltest_wcslwr_s_test1 c_runtime/_wcsnicmp/test1/paltest_wcsnicmp_test1 c_runtime/_wfopen/test1/paltest_wfopen_test1 c_runtime/_wfopen/test2/paltest_wfopen_test2 c_runtime/_wfopen/test3/paltest_wfopen_test3 c_runtime/_wfopen/test4/paltest_wfopen_test4 c_runtime/_wfopen/test5/paltest_wfopen_test5 c_runtime/_wfopen/test6/paltest_wfopen_test6 c_runtime/_wfopen/test7/paltest_wfopen_test7 c_runtime/_wtoi/test1/paltest_wtoi_test1 c_runtime/__iscsym/test1/paltest_iscsym_test1 debug_api/OutputDebugStringA/test1/paltest_outputdebugstringa_test1 debug_api/OutputDebugStringW/test1/paltest_outputdebugstringw_test1 exception_handling/RaiseException/test1/paltest_raiseexception_test1 exception_handling/RaiseException/test2/paltest_raiseexception_test2 exception_handling/RaiseException/test3/paltest_raiseexception_test3 filemapping_memmgt/CreateFileMappingA/test1/paltest_createfilemappinga_test1 filemapping_memmgt/CreateFileMappingA/test3/paltest_createfilemappinga_test3 filemapping_memmgt/CreateFileMappingA/test4/paltest_createfilemappinga_test4 filemapping_memmgt/CreateFileMappingA/test5/paltest_createfilemappinga_test5 filemapping_memmgt/CreateFileMappingA/test6/paltest_createfilemappinga_test6 filemapping_memmgt/CreateFileMappingA/test7/paltest_createfilemappinga_test7 filemapping_memmgt/CreateFileMappingA/test8/paltest_createfilemappinga_test8 filemapping_memmgt/CreateFileMappingA/test9/paltest_createfilemappinga_test9 filemapping_memmgt/CreateFileMappingW/CreateFileMapping_neg1/paltest_createfilemappingw_createfilemapping_neg1 filemapping_memmgt/CreateFileMappingW/test1/paltest_createfilemappingw_test1 filemapping_memmgt/CreateFileMappingW/test3/paltest_createfilemappingw_test3 filemapping_memmgt/CreateFileMappingW/test4/paltest_createfilemappingw_test4 filemapping_memmgt/CreateFileMappingW/test5/paltest_createfilemappingw_test5 filemapping_memmgt/CreateFileMappingW/test6/paltest_createfilemappingw_test6 filemapping_memmgt/CreateFileMappingW/test7/paltest_createfilemappingw_test7 filemapping_memmgt/CreateFileMappingW/test8/paltest_createfilemappingw_test8 filemapping_memmgt/CreateFileMappingW/test9/paltest_createfilemappingw_test9 filemapping_memmgt/FreeLibrary/test1/paltest_freelibrary_test1 filemapping_memmgt/FreeLibrary/test2/paltest_freelibrary_test2 filemapping_memmgt/FreeLibraryAndExitThread/test1/paltest_freelibraryandexitthread_test1 filemapping_memmgt/GetModuleFileNameA/test1/paltest_getmodulefilenamea_test1 filemapping_memmgt/GetModuleFileNameA/test2/paltest_getmodulefilenamea_test2 filemapping_memmgt/GetModuleFileNameW/test1/paltest_getmodulefilenamew_test1 filemapping_memmgt/GetModuleFileNameW/test2/paltest_getmodulefilenamew_test2 filemapping_memmgt/GetProcAddress/test1/paltest_getprocaddress_test1 filemapping_memmgt/GetProcAddress/test2/paltest_getprocaddress_test2 filemapping_memmgt/MapViewOfFile/test1/paltest_mapviewoffile_test1 filemapping_memmgt/MapViewOfFile/test2/paltest_mapviewoffile_test2 filemapping_memmgt/MapViewOfFile/test3/paltest_mapviewoffile_test3 filemapping_memmgt/MapViewOfFile/test4/paltest_mapviewoffile_test4 filemapping_memmgt/MapViewOfFile/test5/paltest_mapviewoffile_test5 filemapping_memmgt/MapViewOfFile/test6/paltest_mapviewoffile_test6 filemapping_memmgt/OpenFileMappingA/test1/paltest_openfilemappinga_test1 filemapping_memmgt/OpenFileMappingA/test2/paltest_openfilemappinga_test2 filemapping_memmgt/OpenFileMappingA/test3/paltest_openfilemappinga_test3 filemapping_memmgt/OpenFileMappingW/test1/paltest_openfilemappingw_test1 filemapping_memmgt/OpenFileMappingW/test2/paltest_openfilemappingw_test2 filemapping_memmgt/OpenFileMappingW/test3/paltest_openfilemappingw_test3 filemapping_memmgt/ProbeMemory/ProbeMemory_neg1/paltest_probememory_probememory_neg1 filemapping_memmgt/ProbeMemory/test1/paltest_probememory_test1 filemapping_memmgt/UnmapViewOfFile/test1/paltest_unmapviewoffile_test1 filemapping_memmgt/UnmapViewOfFile/test2/paltest_unmapviewoffile_test2 filemapping_memmgt/VirtualAlloc/test1/paltest_virtualalloc_test1 filemapping_memmgt/VirtualAlloc/test10/paltest_virtualalloc_test10 filemapping_memmgt/VirtualAlloc/test11/paltest_virtualalloc_test11 filemapping_memmgt/VirtualAlloc/test12/paltest_virtualalloc_test12 filemapping_memmgt/VirtualAlloc/test13/paltest_virtualalloc_test13 filemapping_memmgt/VirtualAlloc/test14/paltest_virtualalloc_test14 filemapping_memmgt/VirtualAlloc/test15/paltest_virtualalloc_test15 filemapping_memmgt/VirtualAlloc/test16/paltest_virtualalloc_test16 filemapping_memmgt/VirtualAlloc/test17/paltest_virtualalloc_test17 filemapping_memmgt/VirtualAlloc/test18/paltest_virtualalloc_test18 filemapping_memmgt/VirtualAlloc/test19/paltest_virtualalloc_test19 filemapping_memmgt/VirtualAlloc/test2/paltest_virtualalloc_test2 filemapping_memmgt/VirtualAlloc/test20/paltest_virtualalloc_test20 filemapping_memmgt/VirtualAlloc/test21/paltest_virtualalloc_test21 filemapping_memmgt/VirtualAlloc/test22/paltest_virtualalloc_test22 filemapping_memmgt/VirtualAlloc/test3/paltest_virtualalloc_test3 filemapping_memmgt/VirtualAlloc/test4/paltest_virtualalloc_test4 filemapping_memmgt/VirtualAlloc/test5/paltest_virtualalloc_test5 filemapping_memmgt/VirtualAlloc/test6/paltest_virtualalloc_test6 filemapping_memmgt/VirtualAlloc/test7/paltest_virtualalloc_test7 filemapping_memmgt/VirtualAlloc/test8/paltest_virtualalloc_test8 filemapping_memmgt/VirtualAlloc/test9/paltest_virtualalloc_test9 filemapping_memmgt/VirtualFree/test1/paltest_virtualfree_test1 filemapping_memmgt/VirtualFree/test2/paltest_virtualfree_test2 filemapping_memmgt/VirtualFree/test3/paltest_virtualfree_test3 filemapping_memmgt/VirtualProtect/test1/paltest_virtualprotect_test1 filemapping_memmgt/VirtualProtect/test2/paltest_virtualprotect_test2 filemapping_memmgt/VirtualProtect/test3/paltest_virtualprotect_test3 filemapping_memmgt/VirtualProtect/test4/paltest_virtualprotect_test4 filemapping_memmgt/VirtualProtect/test6/paltest_virtualprotect_test6 filemapping_memmgt/VirtualProtect/test7/paltest_virtualprotect_test7 filemapping_memmgt/VirtualQuery/test1/paltest_virtualquery_test1 file_io/CopyFileA/test1/paltest_copyfilea_test1 file_io/CopyFileA/test2/paltest_copyfilea_test2 file_io/CopyFileA/test3/paltest_copyfilea_test3 file_io/CopyFileA/test4/paltest_copyfilea_test4 file_io/CopyFileW/test1/paltest_copyfilew_test1 file_io/CopyFileW/test2/paltest_copyfilew_test2 file_io/CopyFileW/test3/paltest_copyfilew_test3 file_io/CreateFileA/test1/paltest_createfilea_test1 file_io/CreateFileW/test1/paltest_createfilew_test1 file_io/DeleteFileA/test1/paltest_deletefilea_test1 file_io/DeleteFileW/test1/paltest_deletefilew_test1 file_io/errorpathnotfound/test1/paltest_errorpathnotfound_test1 file_io/errorpathnotfound/test2/paltest_errorpathnotfound_test2 file_io/FILECanonicalizePath/paltest_filecanonicalizepath_test1 file_io/FindClose/test1/paltest_findclose_test1 file_io/FindFirstFileA/test1/paltest_findfirstfilea_test1 file_io/FindFirstFileW/test1/paltest_findfirstfilew_test1 file_io/FindNextFileA/test1/paltest_findnextfilea_test1 file_io/FindNextFileA/test2/paltest_findnextfilea_test2 file_io/FindNextFileW/test1/paltest_findnextfilew_test1 file_io/FindNextFileW/test2/paltest_findnextfilew_test2 file_io/FlushFileBuffers/test1/paltest_flushfilebuffers_test1 file_io/GetConsoleOutputCP/test1/paltest_getconsoleoutputcp_test1 file_io/GetCurrentDirectoryA/test1/paltest_getcurrentdirectorya_test1 file_io/GetCurrentDirectoryW/test1/paltest_getcurrentdirectoryw_test1 file_io/GetFileAttributesA/test1/paltest_getfileattributesa_test1 file_io/GetFileAttributesExW/test1/paltest_getfileattributesexw_test1 file_io/GetFileAttributesExW/test2/paltest_getfileattributesexw_test2 file_io/GetFileAttributesW/test1/paltest_getfileattributesw_test1 file_io/GetFileSize/test1/paltest_getfilesize_test1 file_io/GetFileSizeEx/test1/paltest_getfilesizeex_test1 file_io/GetFullPathNameA/test1/paltest_getfullpathnamea_test1 file_io/GetFullPathNameA/test2/paltest_getfullpathnamea_test2 file_io/GetFullPathNameA/test3/paltest_getfullpathnamea_test3 file_io/GetFullPathNameA/test4/paltest_getfullpathnamea_test4 file_io/GetFullPathNameW/test1/paltest_getfullpathnamew_test1 file_io/GetFullPathNameW/test2/paltest_getfullpathnamew_test2 file_io/GetFullPathNameW/test3/paltest_getfullpathnamew_test3 file_io/GetFullPathNameW/test4/paltest_getfullpathnamew_test4 file_io/GetStdHandle/test1/paltest_getstdhandle_test1 file_io/GetStdHandle/test2/paltest_getstdhandle_test2 file_io/GetSystemTime/test1/paltest_getsystemtime_test1 file_io/GetSystemTimeAsFileTime/test1/paltest_getsystemtimeasfiletime_test1 file_io/GetTempFileNameA/test1/paltest_gettempfilenamea_test1 file_io/GetTempFileNameA/test2/paltest_gettempfilenamea_test2 file_io/GetTempFileNameA/test3/paltest_gettempfilenamea_test3 file_io/GetTempFileNameW/test1/paltest_gettempfilenamew_test1 file_io/GetTempFileNameW/test2/paltest_gettempfilenamew_test2 file_io/GetTempFileNameW/test3/paltest_gettempfilenamew_test3 file_io/gettemppatha/test1/paltest_gettemppatha_test1 file_io/GetTempPathW/test1/paltest_gettemppathw_test1 file_io/MoveFileExA/test1/paltest_movefileexa_test1 file_io/MoveFileExW/test1/paltest_movefileexw_test1 file_io/ReadFile/test1/paltest_readfile_test1 file_io/ReadFile/test2/paltest_readfile_test2 file_io/ReadFile/test3/paltest_readfile_test3 file_io/ReadFile/test4/paltest_readfile_test4 file_io/SearchPathW/test1/paltest_searchpathw_test1 file_io/SetEndOfFile/test1/paltest_setendoffile_test1 file_io/SetEndOfFile/test2/paltest_setendoffile_test2 file_io/SetEndOfFile/test3/paltest_setendoffile_test3 file_io/SetEndOfFile/test4/paltest_setendoffile_test4 file_io/SetEndOfFile/test5/paltest_setendoffile_test5 file_io/SetFilePointer/test1/paltest_setfilepointer_test1 file_io/SetFilePointer/test2/paltest_setfilepointer_test2 file_io/SetFilePointer/test3/paltest_setfilepointer_test3 file_io/SetFilePointer/test4/paltest_setfilepointer_test4 file_io/SetFilePointer/test5/paltest_setfilepointer_test5 file_io/SetFilePointer/test6/paltest_setfilepointer_test6 file_io/SetFilePointer/test7/paltest_setfilepointer_test7 file_io/WriteFile/test1/paltest_writefile_test1 file_io/WriteFile/test2/paltest_writefile_test2 file_io/WriteFile/test3/paltest_writefile_test3 file_io/WriteFile/test4/paltest_writefile_test4 file_io/WriteFile/test5/paltest_writefile_test5 loader/LoadLibraryA/test1/paltest_loadlibrarya_test1 loader/LoadLibraryA/test2/paltest_loadlibrarya_test2 loader/LoadLibraryA/test3/paltest_loadlibrarya_test3 loader/LoadLibraryA/test5/paltest_loadlibrarya_test5 loader/LoadLibraryA/test7/paltest_loadlibrarya_test7 loader/LoadLibraryW/test1/paltest_loadlibraryw_test1 loader/LoadLibraryW/test2/paltest_loadlibraryw_test2 loader/LoadLibraryW/test3/paltest_loadlibraryw_test3 loader/LoadLibraryW/test5/paltest_loadlibraryw_test5 locale_info/GetACP/test1/paltest_getacp_test1 locale_info/MultiByteToWideChar/test1/paltest_multibytetowidechar_test1 locale_info/MultiByteToWideChar/test2/paltest_multibytetowidechar_test2 locale_info/MultiByteToWideChar/test3/paltest_multibytetowidechar_test3 locale_info/MultiByteToWideChar/test4/paltest_multibytetowidechar_test4 locale_info/WideCharToMultiByte/test1/paltest_widechartomultibyte_test1 locale_info/WideCharToMultiByte/test2/paltest_widechartomultibyte_test2 locale_info/WideCharToMultiByte/test3/paltest_widechartomultibyte_test3 locale_info/WideCharToMultiByte/test4/paltest_widechartomultibyte_test4 locale_info/WideCharToMultiByte/test5/paltest_widechartomultibyte_test5 miscellaneous/CGroup/test1/paltest_cgroup_test1 miscellaneous/CloseHandle/test1/paltest_closehandle_test1 miscellaneous/CloseHandle/test2/paltest_closehandle_test2 miscellaneous/CreatePipe/test1/paltest_createpipe_test1 miscellaneous/FlushInstructionCache/test1/paltest_flushinstructioncache_test1 miscellaneous/FormatMessageW/test1/paltest_formatmessagew_test1 miscellaneous/FormatMessageW/test2/paltest_formatmessagew_test2 miscellaneous/FormatMessageW/test3/paltest_formatmessagew_test3 miscellaneous/FormatMessageW/test4/paltest_formatmessagew_test4 miscellaneous/FormatMessageW/test5/paltest_formatmessagew_test5 miscellaneous/FormatMessageW/test6/paltest_formatmessagew_test6 miscellaneous/FreeEnvironmentStringsW/test1/paltest_freeenvironmentstringsw_test1 miscellaneous/FreeEnvironmentStringsW/test2/paltest_freeenvironmentstringsw_test2 miscellaneous/GetCommandLineW/test1/paltest_getcommandlinew_test1 miscellaneous/GetEnvironmentStringsW/test1/paltest_getenvironmentstringsw_test1 miscellaneous/GetEnvironmentVariableA/test1/paltest_getenvironmentvariablea_test1 miscellaneous/GetEnvironmentVariableA/test2/paltest_getenvironmentvariablea_test2 miscellaneous/GetEnvironmentVariableA/test3/paltest_getenvironmentvariablea_test3 miscellaneous/GetEnvironmentVariableA/test4/paltest_getenvironmentvariablea_test4 miscellaneous/GetEnvironmentVariableA/test5/paltest_getenvironmentvariablea_test5 miscellaneous/GetEnvironmentVariableA/test6/paltest_getenvironmentvariablea_test6 miscellaneous/GetEnvironmentVariableW/test1/paltest_getenvironmentvariablew_test1 miscellaneous/GetEnvironmentVariableW/test2/paltest_getenvironmentvariablew_test2 miscellaneous/GetEnvironmentVariableW/test3/paltest_getenvironmentvariablew_test3 miscellaneous/GetEnvironmentVariableW/test4/paltest_getenvironmentvariablew_test4 miscellaneous/GetEnvironmentVariableW/test5/paltest_getenvironmentvariablew_test5 miscellaneous/GetEnvironmentVariableW/test6/paltest_getenvironmentvariablew_test6 miscellaneous/GetLastError/test1/paltest_getlasterror_test1 miscellaneous/GetSystemInfo/test1/paltest_getsysteminfo_test1 miscellaneous/GetTickCount/test1/paltest_gettickcount_test1 miscellaneous/GlobalMemoryStatusEx/test1/paltest_globalmemorystatusex_test1 miscellaneous/InterlockedBit/test1/paltest_interlockedbit_test1 miscellaneous/InterlockedBit/test2/paltest_interlockedbit_test2 miscellaneous/InterlockedCompareExchange/test1/paltest_interlockedcompareexchange_test1 miscellaneous/InterlockedCompareExchange/test2/paltest_interlockedcompareexchange_test2 miscellaneous/InterlockedCompareExchange64/test1/paltest_interlockedcompareexchange64_test1 miscellaneous/InterlockedCompareExchange64/test2/paltest_interlockedcompareexchange64_test2 miscellaneous/InterlockedCompareExchangePointer/test1/paltest_interlockedcompareexchangepointer_test1 miscellaneous/InterlockedDecrement/test1/paltest_interlockeddecrement_test1 miscellaneous/InterlockedDecrement/test2/paltest_interlockeddecrement_test2 miscellaneous/InterlockedDecrement64/test1/paltest_interlockeddecrement64_test1 miscellaneous/InterlockedDecrement64/test2/paltest_interlockeddecrement64_test2 miscellaneous/InterlockedExchange/test1/paltest_interlockedexchange_test1 miscellaneous/InterlockedExchange64/test1/paltest_interlockedexchange64_test1 miscellaneous/InterLockedExchangeAdd/test1/paltest_interlockedexchangeadd_test1 miscellaneous/InterlockedExchangePointer/test1/paltest_interlockedexchangepointer_test1 miscellaneous/InterlockedIncrement/test1/paltest_interlockedincrement_test1 miscellaneous/InterlockedIncrement/test2/paltest_interlockedincrement_test2 miscellaneous/InterlockedIncrement64/test1/paltest_interlockedincrement64_test1 miscellaneous/InterlockedIncrement64/test2/paltest_interlockedincrement64_test2 miscellaneous/queryperformancecounter/test1/paltest_queryperformancecounter_test1 miscellaneous/queryperformancefrequency/test1/paltest_queryperformancefrequency_test1 miscellaneous/SetEnvironmentVariableA/test1/paltest_setenvironmentvariablea_test1 miscellaneous/SetEnvironmentVariableA/test2/paltest_setenvironmentvariablea_test2 miscellaneous/SetEnvironmentVariableA/test3/paltest_setenvironmentvariablea_test3 miscellaneous/SetEnvironmentVariableA/test4/paltest_setenvironmentvariablea_test4 miscellaneous/SetEnvironmentVariableW/test1/paltest_setenvironmentvariablew_test1 miscellaneous/SetEnvironmentVariableW/test2/paltest_setenvironmentvariablew_test2 miscellaneous/SetEnvironmentVariableW/test3/paltest_setenvironmentvariablew_test3 miscellaneous/SetEnvironmentVariableW/test4/paltest_setenvironmentvariablew_test4 miscellaneous/SetLastError/test1/paltest_setlasterror_test1 miscellaneous/_i64tow/test1/paltest_i64tow_test1 pal_specific/PAL_errno/test1/paltest_pal_errno_test1 pal_specific/PAL_GetUserTempDirectoryW/test1/paltest_pal_getusertempdirectoryw_test1 pal_specific/PAL_Initialize_Terminate/test1/paltest_pal_initialize_terminate_test1 pal_specific/PAL_Initialize_Terminate/test2/paltest_pal_initialize_terminate_test2 pal_specific/PAL_RegisterLibraryW_UnregisterLibraryW/test1/paltest_pal_registerlibraryw_unregisterlibraryw_test1 pal_specific/PAL_RegisterLibraryW_UnregisterLibraryW/test2_neg/paltest_reg_unreg_libraryw_neg samples/test1/paltest_samples_test1 samples/test2/paltest_samples_test2 threading/CreateEventW/test1/paltest_createeventw_test1 threading/CreateEventW/test2/paltest_createeventw_test2 threading/CreateEventW/test3/paltest_createeventw_test3 threading/CreateMutexW_ReleaseMutex/test1/paltest_createmutexw_releasemutex_test1 threading/CreateMutexW_ReleaseMutex/test2/paltest_createmutexw_releasemutex_test2 threading/CreateProcessA/test1/paltest_createprocessa_test1 threading/CreateProcessA/test2/paltest_createprocessa_test2 threading/CreateProcessW/test1/paltest_createprocessw_test1 threading/CreateProcessW/test2/paltest_createprocessw_test2 threading/CreateSemaphoreW_ReleaseSemaphore/test1/paltest_createsemaphorew_releasesemaphore_test1 threading/CreateSemaphoreW_ReleaseSemaphore/test2/paltest_createsemaphorew_releasesemaphore_test2 threading/CreateSemaphoreW_ReleaseSemaphore/test3/paltest_createsemaphorew_releasesemaphore_test3 threading/CreateThread/test1/paltest_createthread_test1 threading/CreateThread/test2/paltest_createthread_test2 threading/CreateThread/test3/paltest_createthread_test3 threading/CriticalSectionFunctions/test1/paltest_criticalsectionfunctions_test1 threading/CriticalSectionFunctions/test2/paltest_criticalsectionfunctions_test2 threading/CriticalSectionFunctions/test3/paltest_criticalsectionfunctions_test3 threading/CriticalSectionFunctions/test4/paltest_criticalsectionfunctions_test4 threading/CriticalSectionFunctions/test5/paltest_criticalsectionfunctions_test5 threading/CriticalSectionFunctions/test6/paltest_criticalsectionfunctions_test6 threading/CriticalSectionFunctions/test7/paltest_criticalsectionfunctions_test7 threading/CriticalSectionFunctions/test8/paltest_criticalsectionfunctions_test8 threading/DuplicateHandle/test1/paltest_duplicatehandle_test1 threading/DuplicateHandle/test10/paltest_duplicatehandle_test10 threading/DuplicateHandle/test11/paltest_duplicatehandle_test11 threading/DuplicateHandle/test12/paltest_duplicatehandle_test12 threading/DuplicateHandle/test2/paltest_duplicatehandle_test2 threading/DuplicateHandle/test3/paltest_duplicatehandle_test3 threading/DuplicateHandle/test4/paltest_duplicatehandle_test4 threading/DuplicateHandle/test5/paltest_duplicatehandle_test5 threading/DuplicateHandle/test6/paltest_duplicatehandle_test6 threading/DuplicateHandle/test7/paltest_duplicatehandle_test7 threading/DuplicateHandle/test8/paltest_duplicatehandle_test8 threading/DuplicateHandle/test9/paltest_duplicatehandle_test9 threading/ExitProcess/test1/paltest_exitprocess_test1 threading/ExitProcess/test2/paltest_exitprocess_test2 threading/ExitProcess/test3/paltest_exitprocess_test3 threading/ExitThread/test1/paltest_exitthread_test1 threading/ExitThread/test2/paltest_exitthread_test2 threading/GetCurrentProcess/test1/paltest_getcurrentprocess_test1 threading/GetCurrentProcessId/test1/paltest_getcurrentprocessid_test1 threading/GetCurrentThread/test1/paltest_getcurrentthread_test1 threading/GetCurrentThread/test2/paltest_getcurrentthread_test2 threading/GetCurrentThreadId/test1/paltest_getcurrentthreadid_test1 threading/GetExitCodeProcess/test1/paltest_getexitcodeprocess_test1 threading/GetProcessTimes/test2/paltest_getprocesstimes_test2 threading/GetThreadTimes/test1/paltest_getthreadtimes_test1 threading/NamedMutex/test1/paltest_namedmutex_test1 threading/OpenEventW/test1/paltest_openeventw_test1 threading/OpenEventW/test2/paltest_openeventw_test2 threading/OpenEventW/test3/paltest_openeventw_test3 threading/OpenEventW/test4/paltest_openeventw_test4 threading/OpenEventW/test5/paltest_openeventw_test5 threading/OpenProcess/test1/paltest_openprocess_test1 threading/QueryThreadCycleTime/test1/paltest_querythreadcycletime_test1 threading/QueueUserAPC/test1/paltest_queueuserapc_test1 threading/QueueUserAPC/test2/paltest_queueuserapc_test2 threading/QueueUserAPC/test3/paltest_queueuserapc_test3 threading/QueueUserAPC/test4/paltest_queueuserapc_test4 threading/QueueUserAPC/test5/paltest_queueuserapc_test5 threading/QueueUserAPC/test6/paltest_queueuserapc_test6 threading/QueueUserAPC/test7/paltest_queueuserapc_test7 threading/ReleaseMutex/test3/paltest_releasemutex_test3 threading/releasesemaphore/test1/paltest_releasesemaphore_test1 threading/ResetEvent/test1/paltest_resetevent_test1 threading/ResetEvent/test2/paltest_resetevent_test2 threading/ResetEvent/test3/paltest_resetevent_test3 threading/ResetEvent/test4/paltest_resetevent_test4 threading/ResumeThread/test1/paltest_resumethread_test1 threading/SetErrorMode/test1/paltest_seterrormode_test1 threading/SetEvent/test1/paltest_setevent_test1 threading/SetEvent/test2/paltest_setevent_test2 threading/SetEvent/test3/paltest_setevent_test3 threading/SetEvent/test4/paltest_setevent_test4 threading/SignalObjectAndWait/paltest_signalobjectandwaittest threading/Sleep/test1/paltest_sleep_test1 threading/Sleep/test2/paltest_sleep_test2 threading/SleepEx/test1/paltest_sleepex_test1 threading/SleepEx/test2/paltest_sleepex_test2 threading/SwitchToThread/test1/paltest_switchtothread_test1 threading/TerminateProcess/test1/paltest_terminateprocess_test1 threading/ThreadPriority/test1/paltest_threadpriority_test1 threading/WaitForMultipleObjects/test1/paltest_waitformultipleobjects_test1 threading/WaitForMultipleObjectsEx/test1/paltest_waitformultipleobjectsex_test1 threading/WaitForMultipleObjectsEx/test2/paltest_waitformultipleobjectsex_test2 threading/WaitForMultipleObjectsEx/test3/paltest_waitformultipleobjectsex_test3 threading/WaitForMultipleObjectsEx/test4/paltest_waitformultipleobjectsex_test4 threading/WaitForMultipleObjectsEx/test5/paltest_waitformultipleobjectsex_test5 threading/WaitForMultipleObjectsEx/test6/paltest_waitformultipleobjectsex_test6 threading/WaitForSingleObject/test1/paltest_waitforsingleobject_test1 threading/WaitForSingleObject/WFSOExMutexTest/paltest_waitforsingleobject_wfsoexmutextest threading/WaitForSingleObject/WFSOExSemaphoreTest/paltest_waitforsingleobject_wfsoexsemaphoretest threading/WaitForSingleObject/WFSOExThreadTest/paltest_waitforsingleobject_wfsoexthreadtest threading/WaitForSingleObject/WFSOMutexTest/paltest_waitforsingleobject_wfsomutextest threading/WaitForSingleObject/WFSOProcessTest/paltest_waitforsingleobject_wfsoprocesstest threading/WaitForSingleObject/WFSOSemaphoreTest/paltest_waitforsingleobject_wfsosemaphoretest threading/WaitForSingleObject/WFSOThreadTest/paltest_waitforsingleobject_wfsothreadtest threading/YieldProcessor/test1/paltest_yieldprocessor_test1
c_runtime/abs/test1/paltest_abs_test1 c_runtime/acos/test1/paltest_acos_test1 c_runtime/acosf/test1/paltest_acosf_test1 c_runtime/acosh/test1/paltest_acosh_test1 c_runtime/acoshf/test1/paltest_acoshf_test1 c_runtime/asin/test1/paltest_asin_test1 c_runtime/asinf/test1/paltest_asinf_test1 c_runtime/asinh/test1/paltest_asinh_test1 c_runtime/asinhf/test1/paltest_asinhf_test1 c_runtime/atan/test1/paltest_atan_test1 c_runtime/atan2/test1/paltest_atan2_test1 c_runtime/atan2f/test1/paltest_atan2f_test1 c_runtime/atanf/test1/paltest_atanf_test1 c_runtime/atanh/test1/paltest_atanh_test1 c_runtime/atanhf/test1/paltest_atanhf_test1 c_runtime/atof/test1/paltest_atof_test1 c_runtime/atoi/test1/paltest_atoi_test1 c_runtime/bsearch/test1/paltest_bsearch_test1 c_runtime/bsearch/test2/paltest_bsearch_test2 c_runtime/cbrt/test1/paltest_cbrt_test1 c_runtime/cbrtf/test1/paltest_cbrtf_test1 c_runtime/ceil/test1/paltest_ceil_test1 c_runtime/ceilf/test1/paltest_ceilf_test1 c_runtime/cos/test1/paltest_cos_test1 c_runtime/cosf/test1/paltest_cosf_test1 c_runtime/cosh/test1/paltest_cosh_test1 c_runtime/coshf/test1/paltest_coshf_test1 c_runtime/errno/test1/paltest_errno_test1 c_runtime/errno/test2/paltest_errno_test2 c_runtime/exit/test1/paltest_exit_test1 c_runtime/exit/test2/paltest_exit_test2 c_runtime/exp/test1/paltest_exp_test1 c_runtime/expf/test1/paltest_expf_test1 c_runtime/fabs/test1/paltest_fabs_test1 c_runtime/fabsf/test1/paltest_fabsf_test1 c_runtime/fclose/test1/paltest_fclose_test1 c_runtime/fclose/test2/paltest_fclose_test2 c_runtime/ferror/test1/paltest_ferror_test1 c_runtime/ferror/test2/paltest_ferror_test2 c_runtime/fflush/test1/paltest_fflush_test1 c_runtime/fgets/test1/paltest_fgets_test1 c_runtime/fgets/test2/paltest_fgets_test2 c_runtime/fgets/test3/paltest_fgets_test3 c_runtime/floor/test1/paltest_floor_test1 c_runtime/floorf/test1/paltest_floorf_test1 c_runtime/fma/test1/paltest_fma_test1 c_runtime/fmaf/test1/paltest_fmaf_test1 c_runtime/fmod/test1/paltest_fmod_test1 c_runtime/fmodf/test1/paltest_fmodf_test1 c_runtime/fopen/test1/paltest_fopen_test1 c_runtime/fopen/test2/paltest_fopen_test2 c_runtime/fopen/test3/paltest_fopen_test3 c_runtime/fopen/test4/paltest_fopen_test4 c_runtime/fopen/test5/paltest_fopen_test5 c_runtime/fopen/test6/paltest_fopen_test6 c_runtime/fopen/test7/paltest_fopen_test7 c_runtime/fprintf/test1/paltest_fprintf_test1 c_runtime/fprintf/test10/paltest_fprintf_test10 c_runtime/fprintf/test11/paltest_fprintf_test11 c_runtime/fprintf/test12/paltest_fprintf_test12 c_runtime/fprintf/test13/paltest_fprintf_test13 c_runtime/fprintf/test14/paltest_fprintf_test14 c_runtime/fprintf/test15/paltest_fprintf_test15 c_runtime/fprintf/test16/paltest_fprintf_test16 c_runtime/fprintf/test17/paltest_fprintf_test17 c_runtime/fprintf/test18/paltest_fprintf_test18 c_runtime/fprintf/test19/paltest_fprintf_test19 c_runtime/fprintf/test2/paltest_fprintf_test2 c_runtime/fprintf/test3/paltest_fprintf_test3 c_runtime/fprintf/test4/paltest_fprintf_test4 c_runtime/fprintf/test5/paltest_fprintf_test5 c_runtime/fprintf/test6/paltest_fprintf_test6 c_runtime/fprintf/test7/paltest_fprintf_test7 c_runtime/fprintf/test8/paltest_fprintf_test8 c_runtime/fprintf/test9/paltest_fprintf_test9 c_runtime/fputs/test1/paltest_fputs_test1 c_runtime/fputs/test2/paltest_fputs_test2 c_runtime/fread/test1/paltest_fread_test1 c_runtime/fread/test2/paltest_fread_test2 c_runtime/fread/test3/paltest_fread_test3 c_runtime/free/test1/paltest_free_test1 c_runtime/fseek/test1/paltest_fseek_test1 c_runtime/ftell/test1/paltest_ftell_test1 c_runtime/fwprintf/test1/paltest_fwprintf_test1 c_runtime/fwprintf/test10/paltest_fwprintf_test10 c_runtime/fwprintf/test11/paltest_fwprintf_test11 c_runtime/fwprintf/test12/paltest_fwprintf_test12 c_runtime/fwprintf/test13/paltest_fwprintf_test13 c_runtime/fwprintf/test14/paltest_fwprintf_test14 c_runtime/fwprintf/test15/paltest_fwprintf_test15 c_runtime/fwprintf/test16/paltest_fwprintf_test16 c_runtime/fwprintf/test17/paltest_fwprintf_test17 c_runtime/fwprintf/test18/paltest_fwprintf_test18 c_runtime/fwprintf/test19/paltest_fwprintf_test19 c_runtime/fwprintf/test2/paltest_fwprintf_test2 c_runtime/fwprintf/test3/paltest_fwprintf_test3 c_runtime/fwprintf/test4/paltest_fwprintf_test4 c_runtime/fwprintf/test5/paltest_fwprintf_test5 c_runtime/fwprintf/test6/paltest_fwprintf_test6 c_runtime/fwprintf/test7/paltest_fwprintf_test7 c_runtime/fwprintf/test8/paltest_fwprintf_test8 c_runtime/fwprintf/test9/paltest_fwprintf_test9 c_runtime/fwrite/test1/paltest_fwrite_test1 c_runtime/getenv/test1/paltest_getenv_test1 c_runtime/getenv/test2/paltest_getenv_test2 c_runtime/getenv/test3/paltest_getenv_test3 c_runtime/ilogb/test1/paltest_ilogb_test1 c_runtime/ilogbf/test1/paltest_ilogbf_test1 c_runtime/isalnum/test1/paltest_isalnum_test1 c_runtime/isalpha/test1/paltest_isalpha_test1 c_runtime/isdigit/test1/paltest_isdigit_test1 c_runtime/islower/test1/paltest_islower_test1 c_runtime/isprint/test1/paltest_isprint_test1 c_runtime/isprint/test2/paltest_isprint_test2 c_runtime/isspace/test1/paltest_isspace_test1 c_runtime/isupper/test1/paltest_isupper_test1 c_runtime/iswdigit/test1/paltest_iswdigit_test1 c_runtime/iswspace/test1/paltest_iswspace_test1 c_runtime/iswupper/test1/paltest_iswupper_test1 c_runtime/isxdigit/test1/paltest_isxdigit_test1 c_runtime/llabs/test1/paltest_llabs_test1 c_runtime/log/test1/paltest_log_test1 c_runtime/log10/test1/paltest_log10_test1 c_runtime/log10f/test1/paltest_log10f_test1 c_runtime/log2/test1/paltest_log2_test1 c_runtime/log2f/test1/paltest_log2f_test1 c_runtime/logf/test1/paltest_logf_test1 c_runtime/malloc/test1/paltest_malloc_test1 c_runtime/malloc/test2/paltest_malloc_test2 c_runtime/memchr/test1/paltest_memchr_test1 c_runtime/memcmp/test1/paltest_memcmp_test1 c_runtime/memcpy/test1/paltest_memcpy_test1 c_runtime/memmove/test1/paltest_memmove_test1 c_runtime/memset/test1/paltest_memset_test1 c_runtime/modf/test1/paltest_modf_test1 c_runtime/modff/test1/paltest_modff_test1 c_runtime/pow/test1/paltest_pow_test1 c_runtime/powf/test1/paltest_powf_test1 c_runtime/printf/test1/paltest_printf_test1 c_runtime/printf/test10/paltest_printf_test10 c_runtime/printf/test11/paltest_printf_test11 c_runtime/printf/test12/paltest_printf_test12 c_runtime/printf/test13/paltest_printf_test13 c_runtime/printf/test14/paltest_printf_test14 c_runtime/printf/test15/paltest_printf_test15 c_runtime/printf/test16/paltest_printf_test16 c_runtime/printf/test17/paltest_printf_test17 c_runtime/printf/test18/paltest_printf_test18 c_runtime/printf/test19/paltest_printf_test19 c_runtime/printf/test2/paltest_printf_test2 c_runtime/printf/test3/paltest_printf_test3 c_runtime/printf/test4/paltest_printf_test4 c_runtime/printf/test5/paltest_printf_test5 c_runtime/printf/test6/paltest_printf_test6 c_runtime/printf/test7/paltest_printf_test7 c_runtime/printf/test8/paltest_printf_test8 c_runtime/printf/test9/paltest_printf_test9 c_runtime/qsort/test1/paltest_qsort_test1 c_runtime/qsort/test2/paltest_qsort_test2 c_runtime/rand_srand/test1/paltest_rand_srand_test1 c_runtime/realloc/test1/paltest_realloc_test1 c_runtime/sin/test1/paltest_sin_test1 c_runtime/sincos/test1/paltest_sincos_test1 c_runtime/sincosf/test1/paltest_sincosf_test1 c_runtime/sinf/test1/paltest_sinf_test1 c_runtime/sinh/test1/paltest_sinh_test1 c_runtime/sinhf/test1/paltest_sinhf_test1 c_runtime/sprintf_s/test1/paltest_sprintf_test1 c_runtime/sprintf_s/test10/paltest_sprintf_test10 c_runtime/sprintf_s/test11/paltest_sprintf_test11 c_runtime/sprintf_s/test12/paltest_sprintf_test12 c_runtime/sprintf_s/test13/paltest_sprintf_test13 c_runtime/sprintf_s/test14/paltest_sprintf_test14 c_runtime/sprintf_s/test15/paltest_sprintf_test15 c_runtime/sprintf_s/test16/paltest_sprintf_test16 c_runtime/sprintf_s/test17/paltest_sprintf_test17 c_runtime/sprintf_s/test18/paltest_sprintf_test18 c_runtime/sprintf_s/test19/paltest_sprintf_test19 c_runtime/sprintf_s/test2/paltest_sprintf_test2 c_runtime/sprintf_s/test3/paltest_sprintf_test3 c_runtime/sprintf_s/test4/paltest_sprintf_test4 c_runtime/sprintf_s/test6/paltest_sprintf_test6 c_runtime/sprintf_s/test7/paltest_sprintf_test7 c_runtime/sprintf_s/test8/paltest_sprintf_test8 c_runtime/sprintf_s/test9/paltest_sprintf_test9 c_runtime/sqrt/test1/paltest_sqrt_test1 c_runtime/sqrtf/test1/paltest_sqrtf_test1 c_runtime/sscanf_s/test1/paltest_sscanf_test1 c_runtime/sscanf_s/test10/paltest_sscanf_test10 c_runtime/sscanf_s/test11/paltest_sscanf_test11 c_runtime/sscanf_s/test12/paltest_sscanf_test12 c_runtime/sscanf_s/test13/paltest_sscanf_test13 c_runtime/sscanf_s/test14/paltest_sscanf_test14 c_runtime/sscanf_s/test15/paltest_sscanf_test15 c_runtime/sscanf_s/test16/paltest_sscanf_test16 c_runtime/sscanf_s/test17/paltest_sscanf_test17 c_runtime/sscanf_s/test2/paltest_sscanf_test2 c_runtime/sscanf_s/test3/paltest_sscanf_test3 c_runtime/sscanf_s/test4/paltest_sscanf_test4 c_runtime/sscanf_s/test5/paltest_sscanf_test5 c_runtime/sscanf_s/test6/paltest_sscanf_test6 c_runtime/sscanf_s/test7/paltest_sscanf_test7 c_runtime/sscanf_s/test8/paltest_sscanf_test8 c_runtime/sscanf_s/test9/paltest_sscanf_test9 c_runtime/strcat/test1/paltest_strcat_test1 c_runtime/strchr/test1/paltest_strchr_test1 c_runtime/strcmp/test1/paltest_strcmp_test1 c_runtime/strcpy/test1/paltest_strcpy_test1 c_runtime/strcspn/test1/paltest_strcspn_test1 c_runtime/strlen/test1/paltest_strlen_test1 c_runtime/strncat/test1/paltest_strncat_test1 c_runtime/strncmp/test1/paltest_strncmp_test1 c_runtime/strncpy/test1/paltest_strncpy_test1 c_runtime/strpbrk/test1/paltest_strpbrk_test1 c_runtime/strrchr/test1/paltest_strrchr_test1 c_runtime/strspn/test1/paltest_strspn_test1 c_runtime/strstr/test1/paltest_strstr_test1 c_runtime/strtod/test1/paltest_strtod_test1 c_runtime/strtod/test2/paltest_strtod_test2 c_runtime/strtok/test1/paltest_strtok_test1 c_runtime/strtoul/test1/paltest_strtoul_test1 c_runtime/swprintf/test1/paltest_swprintf_test1 c_runtime/swprintf/test10/paltest_swprintf_test10 c_runtime/swprintf/test11/paltest_swprintf_test11 c_runtime/swprintf/test12/paltest_swprintf_test12 c_runtime/swprintf/test13/paltest_swprintf_test13 c_runtime/swprintf/test14/paltest_swprintf_test14 c_runtime/swprintf/test15/paltest_swprintf_test15 c_runtime/swprintf/test16/paltest_swprintf_test16 c_runtime/swprintf/test17/paltest_swprintf_test17 c_runtime/swprintf/test18/paltest_swprintf_test18 c_runtime/swprintf/test19/paltest_swprintf_test19 c_runtime/swprintf/test2/paltest_swprintf_test2 c_runtime/swprintf/test3/paltest_swprintf_test3 c_runtime/swprintf/test4/paltest_swprintf_test4 c_runtime/swprintf/test6/paltest_swprintf_test6 c_runtime/swprintf/test7/paltest_swprintf_test7 c_runtime/swprintf/test8/paltest_swprintf_test8 c_runtime/swprintf/test9/paltest_swprintf_test9 c_runtime/swscanf/test1/paltest_swscanf_test1 c_runtime/swscanf/test10/paltest_swscanf_test10 c_runtime/swscanf/test11/paltest_swscanf_test11 c_runtime/swscanf/test12/paltest_swscanf_test12 c_runtime/swscanf/test13/paltest_swscanf_test13 c_runtime/swscanf/test14/paltest_swscanf_test14 c_runtime/swscanf/test15/paltest_swscanf_test15 c_runtime/swscanf/test16/paltest_swscanf_test16 c_runtime/swscanf/test17/paltest_swscanf_test17 c_runtime/swscanf/test2/paltest_swscanf_test2 c_runtime/swscanf/test3/paltest_swscanf_test3 c_runtime/swscanf/test4/paltest_swscanf_test4 c_runtime/swscanf/test5/paltest_swscanf_test5 c_runtime/swscanf/test6/paltest_swscanf_test6 c_runtime/swscanf/test7/paltest_swscanf_test7 c_runtime/swscanf/test8/paltest_swscanf_test8 c_runtime/swscanf/test9/paltest_swscanf_test9 c_runtime/tan/test1/paltest_tan_test1 c_runtime/tanf/test1/paltest_tanf_test1 c_runtime/tanh/test1/paltest_tanh_test1 c_runtime/tanhf/test1/paltest_tanhf_test1 c_runtime/time/test1/paltest_time_test1 c_runtime/tolower/test1/paltest_tolower_test1 c_runtime/toupper/test1/paltest_toupper_test1 c_runtime/towlower/test1/paltest_towlower_test1 c_runtime/towupper/test1/paltest_towupper_test1 c_runtime/vfprintf/test1/paltest_vfprintf_test1 c_runtime/vfprintf/test10/paltest_vfprintf_test10 c_runtime/vfprintf/test11/paltest_vfprintf_test11 c_runtime/vfprintf/test12/paltest_vfprintf_test12 c_runtime/vfprintf/test13/paltest_vfprintf_test13 c_runtime/vfprintf/test14/paltest_vfprintf_test14 c_runtime/vfprintf/test15/paltest_vfprintf_test15 c_runtime/vfprintf/test16/paltest_vfprintf_test16 c_runtime/vfprintf/test17/paltest_vfprintf_test17 c_runtime/vfprintf/test18/paltest_vfprintf_test18 c_runtime/vfprintf/test19/paltest_vfprintf_test19 c_runtime/vfprintf/test2/paltest_vfprintf_test2 c_runtime/vfprintf/test3/paltest_vfprintf_test3 c_runtime/vfprintf/test4/paltest_vfprintf_test4 c_runtime/vfprintf/test5/paltest_vfprintf_test5 c_runtime/vfprintf/test6/paltest_vfprintf_test6 c_runtime/vfprintf/test7/paltest_vfprintf_test7 c_runtime/vfprintf/test8/paltest_vfprintf_test8 c_runtime/vfprintf/test9/paltest_vfprintf_test9 c_runtime/vprintf/test10/paltest_vprintf_test10 c_runtime/vprintf/test11/paltest_vprintf_test11 c_runtime/vprintf/test12/paltest_vprintf_test12 c_runtime/vprintf/test13/paltest_vprintf_test13 c_runtime/vprintf/test14/paltest_vprintf_test14 c_runtime/vprintf/test15/paltest_vprintf_test15 c_runtime/vprintf/test16/paltest_vprintf_test16 c_runtime/vprintf/test17/paltest_vprintf_test17 c_runtime/vprintf/test18/paltest_vprintf_test18 c_runtime/vprintf/test19/paltest_vprintf_test19 c_runtime/vprintf/test2/paltest_vprintf_test2 c_runtime/vprintf/test3/paltest_vprintf_test3 c_runtime/vprintf/test4/paltest_vprintf_test4 c_runtime/vprintf/test5/paltest_vprintf_test5 c_runtime/vprintf/test6/paltest_vprintf_test6 c_runtime/vprintf/test7/paltest_vprintf_test7 c_runtime/vprintf/test8/paltest_vprintf_test8 c_runtime/vprintf/test9/paltest_vprintf_test9 c_runtime/vsprintf/test1/paltest_vsprintf_test1 c_runtime/vsprintf/test10/paltest_vsprintf_test10 c_runtime/vsprintf/test11/paltest_vsprintf_test11 c_runtime/vsprintf/test12/paltest_vsprintf_test12 c_runtime/vsprintf/test13/paltest_vsprintf_test13 c_runtime/vsprintf/test14/paltest_vsprintf_test14 c_runtime/vsprintf/test15/paltest_vsprintf_test15 c_runtime/vsprintf/test16/paltest_vsprintf_test16 c_runtime/vsprintf/test17/paltest_vsprintf_test17 c_runtime/vsprintf/test18/paltest_vsprintf_test18 c_runtime/vsprintf/test19/paltest_vsprintf_test19 c_runtime/vsprintf/test2/paltest_vsprintf_test2 c_runtime/vsprintf/test3/paltest_vsprintf_test3 c_runtime/vsprintf/test4/paltest_vsprintf_test4 c_runtime/vsprintf/test6/paltest_vsprintf_test6 c_runtime/vsprintf/test7/paltest_vsprintf_test7 c_runtime/vsprintf/test8/paltest_vsprintf_test8 c_runtime/vsprintf/test9/paltest_vsprintf_test9 c_runtime/vswprintf/test1/paltest_vswprintf_test1 c_runtime/vswprintf/test10/paltest_vswprintf_test10 c_runtime/vswprintf/test11/paltest_vswprintf_test11 c_runtime/vswprintf/test12/paltest_vswprintf_test12 c_runtime/vswprintf/test13/paltest_vswprintf_test13 c_runtime/vswprintf/test14/paltest_vswprintf_test14 c_runtime/vswprintf/test15/paltest_vswprintf_test15 c_runtime/vswprintf/test16/paltest_vswprintf_test16 c_runtime/vswprintf/test17/paltest_vswprintf_test17 c_runtime/vswprintf/test18/paltest_vswprintf_test18 c_runtime/vswprintf/test19/paltest_vswprintf_test19 c_runtime/vswprintf/test2/paltest_vswprintf_test2 c_runtime/vswprintf/test3/paltest_vswprintf_test3 c_runtime/vswprintf/test4/paltest_vswprintf_test4 c_runtime/vswprintf/test6/paltest_vswprintf_test6 c_runtime/vswprintf/test7/paltest_vswprintf_test7 c_runtime/vswprintf/test8/paltest_vswprintf_test8 c_runtime/vswprintf/test9/paltest_vswprintf_test9 c_runtime/wcscat/test1/paltest_wcscat_test1 c_runtime/wcschr/test1/paltest_wcschr_test1 c_runtime/wcscmp/test1/paltest_wcscmp_test1 c_runtime/wcscpy/test1/paltest_wcscpy_test1 c_runtime/wcslen/test1/paltest_wcslen_test1 c_runtime/wcsncmp/test1/paltest_wcsncmp_test1 c_runtime/wcsncpy/test1/paltest_wcsncpy_test1 c_runtime/wcspbrk/test1/paltest_wcspbrk_test1 c_runtime/wcsrchr/test1/paltest_wcsrchr_test1 c_runtime/wcsstr/test1/paltest_wcsstr_test1 c_runtime/wcstod/test1/paltest_wcstod_test1 c_runtime/wcstod/test2/paltest_wcstod_test2 c_runtime/wcstoul/test1/paltest_wcstoul_test1 c_runtime/wcstoul/test2/paltest_wcstoul_test2 c_runtime/wcstoul/test3/paltest_wcstoul_test3 c_runtime/wcstoul/test4/paltest_wcstoul_test4 c_runtime/wcstoul/test5/paltest_wcstoul_test5 c_runtime/wcstoul/test6/paltest_wcstoul_test6 c_runtime/wprintf/test1/paltest_wprintf_test1 c_runtime/wprintf/test2/paltest_wprintf_test2 c_runtime/_alloca/test1/paltest_alloca_test1 c_runtime/_fdopen/test1/paltest_fdopen_test1 c_runtime/_finite/test1/paltest_finite_test1 c_runtime/_finitef/test1/paltest_finitef_test1 c_runtime/_isnan/test1/paltest_isnan_test1 c_runtime/_isnanf/test1/paltest_isnanf_test1 c_runtime/_itow/test1/paltest_itow_test1 c_runtime/_putenv/test1/paltest_putenv_test1 c_runtime/_putenv/test2/paltest_putenv_test2 c_runtime/_putenv/test3/paltest_putenv_test3 c_runtime/_putenv/test4/paltest_putenv_test4 c_runtime/_rotl/test1/paltest_rotl_test1 c_runtime/_rotr/test1/paltest_rotr_test1 c_runtime/_snprintf_s/test1/paltest_snprintf_test1 c_runtime/_snprintf_s/test10/paltest_snprintf_test10 c_runtime/_snprintf_s/test11/paltest_snprintf_test11 c_runtime/_snprintf_s/test12/paltest_snprintf_test12 c_runtime/_snprintf_s/test13/paltest_snprintf_test13 c_runtime/_snprintf_s/test14/paltest_snprintf_test14 c_runtime/_snprintf_s/test15/paltest_snprintf_test15 c_runtime/_snprintf_s/test16/paltest_snprintf_test16 c_runtime/_snprintf_s/test17/paltest_snprintf_test17 c_runtime/_snprintf_s/test18/paltest_snprintf_test18 c_runtime/_snprintf_s/test19/paltest_snprintf_test19 c_runtime/_snprintf_s/test2/paltest_snprintf_test2 c_runtime/_snprintf_s/test3/paltest_snprintf_test3 c_runtime/_snprintf_s/test4/paltest_snprintf_test4 c_runtime/_snprintf_s/test6/paltest_snprintf_test6 c_runtime/_snprintf_s/test7/paltest_snprintf_test7 c_runtime/_snprintf_s/test8/paltest_snprintf_test8 c_runtime/_snprintf_s/test9/paltest_snprintf_test9 c_runtime/_snwprintf_s/test1/paltest_snwprintf_test1 c_runtime/_snwprintf_s/test10/paltest_snwprintf_test10 c_runtime/_snwprintf_s/test11/paltest_snwprintf_test11 c_runtime/_snwprintf_s/test12/paltest_snwprintf_test12 c_runtime/_snwprintf_s/test13/paltest_snwprintf_test13 c_runtime/_snwprintf_s/test14/paltest_snwprintf_test14 c_runtime/_snwprintf_s/test15/paltest_snwprintf_test15 c_runtime/_snwprintf_s/test16/paltest_snwprintf_test16 c_runtime/_snwprintf_s/test17/paltest_snwprintf_test17 c_runtime/_snwprintf_s/test18/paltest_snwprintf_test18 c_runtime/_snwprintf_s/test19/paltest_snwprintf_test19 c_runtime/_snwprintf_s/test2/paltest_snwprintf_test2 c_runtime/_snwprintf_s/test3/paltest_snwprintf_test3 c_runtime/_snwprintf_s/test4/paltest_snwprintf_test4 c_runtime/_snwprintf_s/test6/paltest_snwprintf_test6 c_runtime/_snwprintf_s/test7/paltest_snwprintf_test7 c_runtime/_snwprintf_s/test8/paltest_snwprintf_test8 c_runtime/_snwprintf_s/test9/paltest_snwprintf_test9 c_runtime/_stricmp/test1/paltest_stricmp_test1 c_runtime/_strnicmp/test1/paltest_strnicmp_test1 c_runtime/_vsnprintf_s/test1/paltest_vsnprintf_test1 c_runtime/_vsnprintf_s/test10/paltest_vsnprintf_test10 c_runtime/_vsnprintf_s/test11/paltest_vsnprintf_test11 c_runtime/_vsnprintf_s/test12/paltest_vsnprintf_test12 c_runtime/_vsnprintf_s/test13/paltest_vsnprintf_test13 c_runtime/_vsnprintf_s/test14/paltest_vsnprintf_test14 c_runtime/_vsnprintf_s/test15/paltest_vsnprintf_test15 c_runtime/_vsnprintf_s/test16/paltest_vsnprintf_test16 c_runtime/_vsnprintf_s/test17/paltest_vsnprintf_test17 c_runtime/_vsnprintf_s/test18/paltest_vsnprintf_test18 c_runtime/_vsnprintf_s/test19/paltest_vsnprintf_test19 c_runtime/_vsnprintf_s/test2/paltest_vsnprintf_test2 c_runtime/_vsnprintf_s/test3/paltest_vsnprintf_test3 c_runtime/_vsnprintf_s/test4/paltest_vsnprintf_test4 c_runtime/_vsnprintf_s/test6/paltest_vsnprintf_test6 c_runtime/_vsnprintf_s/test7/paltest_vsnprintf_test7 c_runtime/_vsnprintf_s/test8/paltest_vsnprintf_test8 c_runtime/_vsnprintf_s/test9/paltest_vsnprintf_test9 c_runtime/_vsnwprintf_s/test1/paltest_vsnwprintf_test1 c_runtime/_vsnwprintf_s/test10/paltest_vsnwprintf_test10 c_runtime/_vsnwprintf_s/test11/paltest_vsnwprintf_test11 c_runtime/_vsnwprintf_s/test12/paltest_vsnwprintf_test12 c_runtime/_vsnwprintf_s/test13/paltest_vsnwprintf_test13 c_runtime/_vsnwprintf_s/test14/paltest_vsnwprintf_test14 c_runtime/_vsnwprintf_s/test15/paltest_vsnwprintf_test15 c_runtime/_vsnwprintf_s/test16/paltest_vsnwprintf_test16 c_runtime/_vsnwprintf_s/test17/paltest_vsnwprintf_test17 c_runtime/_vsnwprintf_s/test18/paltest_vsnwprintf_test18 c_runtime/_vsnwprintf_s/test19/paltest_vsnwprintf_test19 c_runtime/_vsnwprintf_s/test2/paltest_vsnwprintf_test2 c_runtime/_vsnwprintf_s/test3/paltest_vsnwprintf_test3 c_runtime/_vsnwprintf_s/test4/paltest_vsnwprintf_test4 c_runtime/_vsnwprintf_s/test6/paltest_vsnwprintf_test6 c_runtime/_vsnwprintf_s/test7/paltest_vsnwprintf_test7 c_runtime/_vsnwprintf_s/test8/paltest_vsnwprintf_test8 c_runtime/_vsnwprintf_s/test9/paltest_vsnwprintf_test9 c_runtime/_wcsicmp/test1/paltest_wcsicmp_test1 c_runtime/_wcslwr_s/test1/paltest_wcslwr_s_test1 c_runtime/_wcsnicmp/test1/paltest_wcsnicmp_test1 c_runtime/_wfopen/test1/paltest_wfopen_test1 c_runtime/_wfopen/test2/paltest_wfopen_test2 c_runtime/_wfopen/test3/paltest_wfopen_test3 c_runtime/_wfopen/test4/paltest_wfopen_test4 c_runtime/_wfopen/test5/paltest_wfopen_test5 c_runtime/_wfopen/test6/paltest_wfopen_test6 c_runtime/_wfopen/test7/paltest_wfopen_test7 c_runtime/_wtoi/test1/paltest_wtoi_test1 c_runtime/__iscsym/test1/paltest_iscsym_test1 debug_api/OutputDebugStringA/test1/paltest_outputdebugstringa_test1 debug_api/OutputDebugStringW/test1/paltest_outputdebugstringw_test1 exception_handling/RaiseException/test1/paltest_raiseexception_test1 exception_handling/RaiseException/test2/paltest_raiseexception_test2 exception_handling/RaiseException/test3/paltest_raiseexception_test3 filemapping_memmgt/CreateFileMappingA/test1/paltest_createfilemappinga_test1 filemapping_memmgt/CreateFileMappingA/test3/paltest_createfilemappinga_test3 filemapping_memmgt/CreateFileMappingA/test4/paltest_createfilemappinga_test4 filemapping_memmgt/CreateFileMappingA/test5/paltest_createfilemappinga_test5 filemapping_memmgt/CreateFileMappingA/test6/paltest_createfilemappinga_test6 filemapping_memmgt/CreateFileMappingA/test7/paltest_createfilemappinga_test7 filemapping_memmgt/CreateFileMappingA/test8/paltest_createfilemappinga_test8 filemapping_memmgt/CreateFileMappingA/test9/paltest_createfilemappinga_test9 filemapping_memmgt/CreateFileMappingW/CreateFileMapping_neg1/paltest_createfilemappingw_createfilemapping_neg1 filemapping_memmgt/CreateFileMappingW/test1/paltest_createfilemappingw_test1 filemapping_memmgt/CreateFileMappingW/test3/paltest_createfilemappingw_test3 filemapping_memmgt/CreateFileMappingW/test4/paltest_createfilemappingw_test4 filemapping_memmgt/CreateFileMappingW/test5/paltest_createfilemappingw_test5 filemapping_memmgt/CreateFileMappingW/test6/paltest_createfilemappingw_test6 filemapping_memmgt/CreateFileMappingW/test7/paltest_createfilemappingw_test7 filemapping_memmgt/CreateFileMappingW/test8/paltest_createfilemappingw_test8 filemapping_memmgt/CreateFileMappingW/test9/paltest_createfilemappingw_test9 filemapping_memmgt/FreeLibrary/test1/paltest_freelibrary_test1 filemapping_memmgt/FreeLibrary/test2/paltest_freelibrary_test2 filemapping_memmgt/FreeLibraryAndExitThread/test1/paltest_freelibraryandexitthread_test1 filemapping_memmgt/GetModuleFileNameA/test1/paltest_getmodulefilenamea_test1 filemapping_memmgt/GetModuleFileNameA/test2/paltest_getmodulefilenamea_test2 filemapping_memmgt/GetModuleFileNameW/test1/paltest_getmodulefilenamew_test1 filemapping_memmgt/GetModuleFileNameW/test2/paltest_getmodulefilenamew_test2 filemapping_memmgt/GetProcAddress/test1/paltest_getprocaddress_test1 filemapping_memmgt/GetProcAddress/test2/paltest_getprocaddress_test2 filemapping_memmgt/MapViewOfFile/test1/paltest_mapviewoffile_test1 filemapping_memmgt/MapViewOfFile/test2/paltest_mapviewoffile_test2 filemapping_memmgt/MapViewOfFile/test3/paltest_mapviewoffile_test3 filemapping_memmgt/MapViewOfFile/test4/paltest_mapviewoffile_test4 filemapping_memmgt/MapViewOfFile/test5/paltest_mapviewoffile_test5 filemapping_memmgt/MapViewOfFile/test6/paltest_mapviewoffile_test6 filemapping_memmgt/OpenFileMappingA/test1/paltest_openfilemappinga_test1 filemapping_memmgt/OpenFileMappingA/test2/paltest_openfilemappinga_test2 filemapping_memmgt/OpenFileMappingA/test3/paltest_openfilemappinga_test3 filemapping_memmgt/OpenFileMappingW/test1/paltest_openfilemappingw_test1 filemapping_memmgt/OpenFileMappingW/test2/paltest_openfilemappingw_test2 filemapping_memmgt/OpenFileMappingW/test3/paltest_openfilemappingw_test3 filemapping_memmgt/ProbeMemory/ProbeMemory_neg1/paltest_probememory_probememory_neg1 filemapping_memmgt/ProbeMemory/test1/paltest_probememory_test1 filemapping_memmgt/UnmapViewOfFile/test1/paltest_unmapviewoffile_test1 filemapping_memmgt/UnmapViewOfFile/test2/paltest_unmapviewoffile_test2 filemapping_memmgt/VirtualAlloc/test1/paltest_virtualalloc_test1 filemapping_memmgt/VirtualAlloc/test10/paltest_virtualalloc_test10 filemapping_memmgt/VirtualAlloc/test11/paltest_virtualalloc_test11 filemapping_memmgt/VirtualAlloc/test12/paltest_virtualalloc_test12 filemapping_memmgt/VirtualAlloc/test13/paltest_virtualalloc_test13 filemapping_memmgt/VirtualAlloc/test14/paltest_virtualalloc_test14 filemapping_memmgt/VirtualAlloc/test15/paltest_virtualalloc_test15 filemapping_memmgt/VirtualAlloc/test16/paltest_virtualalloc_test16 filemapping_memmgt/VirtualAlloc/test17/paltest_virtualalloc_test17 filemapping_memmgt/VirtualAlloc/test18/paltest_virtualalloc_test18 filemapping_memmgt/VirtualAlloc/test19/paltest_virtualalloc_test19 filemapping_memmgt/VirtualAlloc/test2/paltest_virtualalloc_test2 filemapping_memmgt/VirtualAlloc/test20/paltest_virtualalloc_test20 filemapping_memmgt/VirtualAlloc/test21/paltest_virtualalloc_test21 filemapping_memmgt/VirtualAlloc/test22/paltest_virtualalloc_test22 filemapping_memmgt/VirtualAlloc/test3/paltest_virtualalloc_test3 filemapping_memmgt/VirtualAlloc/test4/paltest_virtualalloc_test4 filemapping_memmgt/VirtualAlloc/test5/paltest_virtualalloc_test5 filemapping_memmgt/VirtualAlloc/test6/paltest_virtualalloc_test6 filemapping_memmgt/VirtualAlloc/test7/paltest_virtualalloc_test7 filemapping_memmgt/VirtualAlloc/test8/paltest_virtualalloc_test8 filemapping_memmgt/VirtualAlloc/test9/paltest_virtualalloc_test9 filemapping_memmgt/VirtualFree/test1/paltest_virtualfree_test1 filemapping_memmgt/VirtualFree/test2/paltest_virtualfree_test2 filemapping_memmgt/VirtualFree/test3/paltest_virtualfree_test3 filemapping_memmgt/VirtualProtect/test1/paltest_virtualprotect_test1 filemapping_memmgt/VirtualProtect/test2/paltest_virtualprotect_test2 filemapping_memmgt/VirtualProtect/test3/paltest_virtualprotect_test3 filemapping_memmgt/VirtualProtect/test4/paltest_virtualprotect_test4 filemapping_memmgt/VirtualProtect/test6/paltest_virtualprotect_test6 filemapping_memmgt/VirtualProtect/test7/paltest_virtualprotect_test7 filemapping_memmgt/VirtualQuery/test1/paltest_virtualquery_test1 file_io/CopyFileA/test1/paltest_copyfilea_test1 file_io/CopyFileA/test2/paltest_copyfilea_test2 file_io/CopyFileA/test3/paltest_copyfilea_test3 file_io/CopyFileA/test4/paltest_copyfilea_test4 file_io/CopyFileW/test1/paltest_copyfilew_test1 file_io/CopyFileW/test2/paltest_copyfilew_test2 file_io/CopyFileW/test3/paltest_copyfilew_test3 file_io/CreateFileA/test1/paltest_createfilea_test1 file_io/CreateFileW/test1/paltest_createfilew_test1 file_io/DeleteFileA/test1/paltest_deletefilea_test1 file_io/DeleteFileW/test1/paltest_deletefilew_test1 file_io/errorpathnotfound/test1/paltest_errorpathnotfound_test1 file_io/errorpathnotfound/test2/paltest_errorpathnotfound_test2 file_io/FILECanonicalizePath/paltest_filecanonicalizepath_test1 file_io/FindClose/test1/paltest_findclose_test1 file_io/FindFirstFileA/test1/paltest_findfirstfilea_test1 file_io/FindFirstFileW/test1/paltest_findfirstfilew_test1 file_io/FindNextFileA/test1/paltest_findnextfilea_test1 file_io/FindNextFileA/test2/paltest_findnextfilea_test2 file_io/FindNextFileW/test1/paltest_findnextfilew_test1 file_io/FindNextFileW/test2/paltest_findnextfilew_test2 file_io/FlushFileBuffers/test1/paltest_flushfilebuffers_test1 file_io/GetConsoleOutputCP/test1/paltest_getconsoleoutputcp_test1 file_io/GetCurrentDirectoryA/test1/paltest_getcurrentdirectorya_test1 file_io/GetCurrentDirectoryW/test1/paltest_getcurrentdirectoryw_test1 file_io/GetFileAttributesA/test1/paltest_getfileattributesa_test1 file_io/GetFileAttributesExW/test1/paltest_getfileattributesexw_test1 file_io/GetFileAttributesExW/test2/paltest_getfileattributesexw_test2 file_io/GetFileAttributesW/test1/paltest_getfileattributesw_test1 file_io/GetFileSize/test1/paltest_getfilesize_test1 file_io/GetFileSizeEx/test1/paltest_getfilesizeex_test1 file_io/GetFullPathNameA/test1/paltest_getfullpathnamea_test1 file_io/GetFullPathNameA/test2/paltest_getfullpathnamea_test2 file_io/GetFullPathNameA/test3/paltest_getfullpathnamea_test3 file_io/GetFullPathNameA/test4/paltest_getfullpathnamea_test4 file_io/GetFullPathNameW/test1/paltest_getfullpathnamew_test1 file_io/GetFullPathNameW/test2/paltest_getfullpathnamew_test2 file_io/GetFullPathNameW/test3/paltest_getfullpathnamew_test3 file_io/GetFullPathNameW/test4/paltest_getfullpathnamew_test4 file_io/GetStdHandle/test1/paltest_getstdhandle_test1 file_io/GetStdHandle/test2/paltest_getstdhandle_test2 file_io/GetSystemTime/test1/paltest_getsystemtime_test1 file_io/GetSystemTimeAsFileTime/test1/paltest_getsystemtimeasfiletime_test1 file_io/GetTempFileNameA/test1/paltest_gettempfilenamea_test1 file_io/GetTempFileNameA/test2/paltest_gettempfilenamea_test2 file_io/GetTempFileNameA/test3/paltest_gettempfilenamea_test3 file_io/GetTempFileNameW/test1/paltest_gettempfilenamew_test1 file_io/GetTempFileNameW/test2/paltest_gettempfilenamew_test2 file_io/GetTempFileNameW/test3/paltest_gettempfilenamew_test3 file_io/gettemppatha/test1/paltest_gettemppatha_test1 file_io/GetTempPathW/test1/paltest_gettemppathw_test1 file_io/MoveFileExA/test1/paltest_movefileexa_test1 file_io/MoveFileExW/test1/paltest_movefileexw_test1 file_io/ReadFile/test1/paltest_readfile_test1 file_io/ReadFile/test2/paltest_readfile_test2 file_io/ReadFile/test3/paltest_readfile_test3 file_io/ReadFile/test4/paltest_readfile_test4 file_io/SearchPathW/test1/paltest_searchpathw_test1 file_io/SetEndOfFile/test1/paltest_setendoffile_test1 file_io/SetEndOfFile/test2/paltest_setendoffile_test2 file_io/SetEndOfFile/test3/paltest_setendoffile_test3 file_io/SetEndOfFile/test4/paltest_setendoffile_test4 file_io/SetEndOfFile/test5/paltest_setendoffile_test5 file_io/SetFilePointer/test1/paltest_setfilepointer_test1 file_io/SetFilePointer/test2/paltest_setfilepointer_test2 file_io/SetFilePointer/test3/paltest_setfilepointer_test3 file_io/SetFilePointer/test4/paltest_setfilepointer_test4 file_io/SetFilePointer/test5/paltest_setfilepointer_test5 file_io/SetFilePointer/test6/paltest_setfilepointer_test6 file_io/SetFilePointer/test7/paltest_setfilepointer_test7 file_io/WriteFile/test1/paltest_writefile_test1 file_io/WriteFile/test2/paltest_writefile_test2 file_io/WriteFile/test3/paltest_writefile_test3 file_io/WriteFile/test4/paltest_writefile_test4 file_io/WriteFile/test5/paltest_writefile_test5 loader/LoadLibraryA/test1/paltest_loadlibrarya_test1 loader/LoadLibraryA/test2/paltest_loadlibrarya_test2 loader/LoadLibraryA/test3/paltest_loadlibrarya_test3 loader/LoadLibraryA/test5/paltest_loadlibrarya_test5 loader/LoadLibraryA/test7/paltest_loadlibrarya_test7 loader/LoadLibraryW/test1/paltest_loadlibraryw_test1 loader/LoadLibraryW/test2/paltest_loadlibraryw_test2 loader/LoadLibraryW/test3/paltest_loadlibraryw_test3 loader/LoadLibraryW/test5/paltest_loadlibraryw_test5 locale_info/GetACP/test1/paltest_getacp_test1 locale_info/MultiByteToWideChar/test1/paltest_multibytetowidechar_test1 locale_info/MultiByteToWideChar/test2/paltest_multibytetowidechar_test2 locale_info/MultiByteToWideChar/test3/paltest_multibytetowidechar_test3 locale_info/MultiByteToWideChar/test4/paltest_multibytetowidechar_test4 locale_info/WideCharToMultiByte/test1/paltest_widechartomultibyte_test1 locale_info/WideCharToMultiByte/test2/paltest_widechartomultibyte_test2 locale_info/WideCharToMultiByte/test3/paltest_widechartomultibyte_test3 locale_info/WideCharToMultiByte/test4/paltest_widechartomultibyte_test4 locale_info/WideCharToMultiByte/test5/paltest_widechartomultibyte_test5 miscellaneous/CGroup/test1/paltest_cgroup_test1 miscellaneous/CloseHandle/test1/paltest_closehandle_test1 miscellaneous/CloseHandle/test2/paltest_closehandle_test2 miscellaneous/CreatePipe/test1/paltest_createpipe_test1 miscellaneous/FlushInstructionCache/test1/paltest_flushinstructioncache_test1 miscellaneous/FormatMessageW/test1/paltest_formatmessagew_test1 miscellaneous/FormatMessageW/test2/paltest_formatmessagew_test2 miscellaneous/FormatMessageW/test3/paltest_formatmessagew_test3 miscellaneous/FormatMessageW/test4/paltest_formatmessagew_test4 miscellaneous/FormatMessageW/test5/paltest_formatmessagew_test5 miscellaneous/FormatMessageW/test6/paltest_formatmessagew_test6 miscellaneous/FreeEnvironmentStringsW/test1/paltest_freeenvironmentstringsw_test1 miscellaneous/FreeEnvironmentStringsW/test2/paltest_freeenvironmentstringsw_test2 miscellaneous/GetCommandLineW/test1/paltest_getcommandlinew_test1 miscellaneous/GetEnvironmentStringsW/test1/paltest_getenvironmentstringsw_test1 miscellaneous/GetEnvironmentVariableA/test1/paltest_getenvironmentvariablea_test1 miscellaneous/GetEnvironmentVariableA/test2/paltest_getenvironmentvariablea_test2 miscellaneous/GetEnvironmentVariableA/test3/paltest_getenvironmentvariablea_test3 miscellaneous/GetEnvironmentVariableA/test4/paltest_getenvironmentvariablea_test4 miscellaneous/GetEnvironmentVariableA/test5/paltest_getenvironmentvariablea_test5 miscellaneous/GetEnvironmentVariableA/test6/paltest_getenvironmentvariablea_test6 miscellaneous/GetEnvironmentVariableW/test1/paltest_getenvironmentvariablew_test1 miscellaneous/GetEnvironmentVariableW/test2/paltest_getenvironmentvariablew_test2 miscellaneous/GetEnvironmentVariableW/test3/paltest_getenvironmentvariablew_test3 miscellaneous/GetEnvironmentVariableW/test4/paltest_getenvironmentvariablew_test4 miscellaneous/GetEnvironmentVariableW/test5/paltest_getenvironmentvariablew_test5 miscellaneous/GetEnvironmentVariableW/test6/paltest_getenvironmentvariablew_test6 miscellaneous/GetLastError/test1/paltest_getlasterror_test1 miscellaneous/GetSystemInfo/test1/paltest_getsysteminfo_test1 miscellaneous/GetTickCount/test1/paltest_gettickcount_test1 miscellaneous/GlobalMemoryStatusEx/test1/paltest_globalmemorystatusex_test1 miscellaneous/InterlockedBit/test1/paltest_interlockedbit_test1 miscellaneous/InterlockedBit/test2/paltest_interlockedbit_test2 miscellaneous/InterlockedCompareExchange/test1/paltest_interlockedcompareexchange_test1 miscellaneous/InterlockedCompareExchange/test2/paltest_interlockedcompareexchange_test2 miscellaneous/InterlockedCompareExchange64/test1/paltest_interlockedcompareexchange64_test1 miscellaneous/InterlockedCompareExchange64/test2/paltest_interlockedcompareexchange64_test2 miscellaneous/InterlockedCompareExchangePointer/test1/paltest_interlockedcompareexchangepointer_test1 miscellaneous/InterlockedDecrement/test1/paltest_interlockeddecrement_test1 miscellaneous/InterlockedDecrement/test2/paltest_interlockeddecrement_test2 miscellaneous/InterlockedDecrement64/test1/paltest_interlockeddecrement64_test1 miscellaneous/InterlockedDecrement64/test2/paltest_interlockeddecrement64_test2 miscellaneous/InterlockedExchange/test1/paltest_interlockedexchange_test1 miscellaneous/InterlockedExchange64/test1/paltest_interlockedexchange64_test1 miscellaneous/InterLockedExchangeAdd/test1/paltest_interlockedexchangeadd_test1 miscellaneous/InterlockedExchangePointer/test1/paltest_interlockedexchangepointer_test1 miscellaneous/InterlockedIncrement/test1/paltest_interlockedincrement_test1 miscellaneous/InterlockedIncrement/test2/paltest_interlockedincrement_test2 miscellaneous/InterlockedIncrement64/test1/paltest_interlockedincrement64_test1 miscellaneous/InterlockedIncrement64/test2/paltest_interlockedincrement64_test2 miscellaneous/queryperformancecounter/test1/paltest_queryperformancecounter_test1 miscellaneous/queryperformancefrequency/test1/paltest_queryperformancefrequency_test1 miscellaneous/SetEnvironmentVariableA/test1/paltest_setenvironmentvariablea_test1 miscellaneous/SetEnvironmentVariableA/test2/paltest_setenvironmentvariablea_test2 miscellaneous/SetEnvironmentVariableA/test3/paltest_setenvironmentvariablea_test3 miscellaneous/SetEnvironmentVariableA/test4/paltest_setenvironmentvariablea_test4 miscellaneous/SetEnvironmentVariableW/test1/paltest_setenvironmentvariablew_test1 miscellaneous/SetEnvironmentVariableW/test2/paltest_setenvironmentvariablew_test2 miscellaneous/SetEnvironmentVariableW/test3/paltest_setenvironmentvariablew_test3 miscellaneous/SetEnvironmentVariableW/test4/paltest_setenvironmentvariablew_test4 miscellaneous/SetLastError/test1/paltest_setlasterror_test1 miscellaneous/_i64tow/test1/paltest_i64tow_test1 pal_specific/PAL_errno/test1/paltest_pal_errno_test1 pal_specific/PAL_GetUserTempDirectoryW/test1/paltest_pal_getusertempdirectoryw_test1 pal_specific/PAL_Initialize_Terminate/test1/paltest_pal_initialize_terminate_test1 pal_specific/PAL_Initialize_Terminate/test2/paltest_pal_initialize_terminate_test2 pal_specific/PAL_RegisterLibraryW_UnregisterLibraryW/test1/paltest_pal_registerlibraryw_unregisterlibraryw_test1 pal_specific/PAL_RegisterLibraryW_UnregisterLibraryW/test2_neg/paltest_reg_unreg_libraryw_neg samples/test1/paltest_samples_test1 samples/test2/paltest_samples_test2 threading/CreateEventW/test1/paltest_createeventw_test1 threading/CreateEventW/test2/paltest_createeventw_test2 threading/CreateEventW/test3/paltest_createeventw_test3 threading/CreateMutexW_ReleaseMutex/test1/paltest_createmutexw_releasemutex_test1 threading/CreateMutexW_ReleaseMutex/test2/paltest_createmutexw_releasemutex_test2 threading/CreateProcessA/test1/paltest_createprocessa_test1 threading/CreateProcessA/test2/paltest_createprocessa_test2 threading/CreateProcessW/test1/paltest_createprocessw_test1 threading/CreateProcessW/test2/paltest_createprocessw_test2 threading/CreateSemaphoreW_ReleaseSemaphore/test1/paltest_createsemaphorew_releasesemaphore_test1 threading/CreateSemaphoreW_ReleaseSemaphore/test2/paltest_createsemaphorew_releasesemaphore_test2 threading/CreateSemaphoreW_ReleaseSemaphore/test3/paltest_createsemaphorew_releasesemaphore_test3 threading/CreateThread/test1/paltest_createthread_test1 threading/CreateThread/test2/paltest_createthread_test2 threading/CreateThread/test3/paltest_createthread_test3 threading/CriticalSectionFunctions/test1/paltest_criticalsectionfunctions_test1 threading/CriticalSectionFunctions/test2/paltest_criticalsectionfunctions_test2 threading/CriticalSectionFunctions/test3/paltest_criticalsectionfunctions_test3 threading/CriticalSectionFunctions/test4/paltest_criticalsectionfunctions_test4 threading/CriticalSectionFunctions/test5/paltest_criticalsectionfunctions_test5 threading/CriticalSectionFunctions/test6/paltest_criticalsectionfunctions_test6 threading/CriticalSectionFunctions/test7/paltest_criticalsectionfunctions_test7 threading/CriticalSectionFunctions/test8/paltest_criticalsectionfunctions_test8 threading/DuplicateHandle/test1/paltest_duplicatehandle_test1 threading/DuplicateHandle/test10/paltest_duplicatehandle_test10 threading/DuplicateHandle/test11/paltest_duplicatehandle_test11 threading/DuplicateHandle/test12/paltest_duplicatehandle_test12 threading/DuplicateHandle/test2/paltest_duplicatehandle_test2 threading/DuplicateHandle/test3/paltest_duplicatehandle_test3 threading/DuplicateHandle/test4/paltest_duplicatehandle_test4 threading/DuplicateHandle/test5/paltest_duplicatehandle_test5 threading/DuplicateHandle/test6/paltest_duplicatehandle_test6 threading/DuplicateHandle/test7/paltest_duplicatehandle_test7 threading/DuplicateHandle/test8/paltest_duplicatehandle_test8 threading/DuplicateHandle/test9/paltest_duplicatehandle_test9 threading/ExitProcess/test1/paltest_exitprocess_test1 threading/ExitProcess/test2/paltest_exitprocess_test2 threading/ExitProcess/test3/paltest_exitprocess_test3 threading/ExitThread/test1/paltest_exitthread_test1 threading/ExitThread/test2/paltest_exitthread_test2 threading/GetCurrentProcess/test1/paltest_getcurrentprocess_test1 threading/GetCurrentProcessId/test1/paltest_getcurrentprocessid_test1 threading/GetCurrentThread/test1/paltest_getcurrentthread_test1 threading/GetCurrentThread/test2/paltest_getcurrentthread_test2 threading/GetCurrentThreadId/test1/paltest_getcurrentthreadid_test1 threading/GetExitCodeProcess/test1/paltest_getexitcodeprocess_test1 threading/GetProcessTimes/test2/paltest_getprocesstimes_test2 threading/GetThreadTimes/test1/paltest_getthreadtimes_test1 threading/NamedMutex/test1/paltest_namedmutex_test1 threading/OpenEventW/test1/paltest_openeventw_test1 threading/OpenEventW/test2/paltest_openeventw_test2 threading/OpenEventW/test3/paltest_openeventw_test3 threading/OpenEventW/test4/paltest_openeventw_test4 threading/OpenEventW/test5/paltest_openeventw_test5 threading/OpenProcess/test1/paltest_openprocess_test1 threading/QueryThreadCycleTime/test1/paltest_querythreadcycletime_test1 threading/QueueUserAPC/test1/paltest_queueuserapc_test1 threading/QueueUserAPC/test2/paltest_queueuserapc_test2 threading/QueueUserAPC/test3/paltest_queueuserapc_test3 threading/QueueUserAPC/test4/paltest_queueuserapc_test4 threading/QueueUserAPC/test5/paltest_queueuserapc_test5 threading/QueueUserAPC/test6/paltest_queueuserapc_test6 threading/QueueUserAPC/test7/paltest_queueuserapc_test7 threading/ReleaseMutex/test3/paltest_releasemutex_test3 threading/releasesemaphore/test1/paltest_releasesemaphore_test1 threading/ResetEvent/test1/paltest_resetevent_test1 threading/ResetEvent/test2/paltest_resetevent_test2 threading/ResetEvent/test3/paltest_resetevent_test3 threading/ResetEvent/test4/paltest_resetevent_test4 threading/ResumeThread/test1/paltest_resumethread_test1 threading/SetErrorMode/test1/paltest_seterrormode_test1 threading/SetEvent/test1/paltest_setevent_test1 threading/SetEvent/test2/paltest_setevent_test2 threading/SetEvent/test3/paltest_setevent_test3 threading/SetEvent/test4/paltest_setevent_test4 threading/SignalObjectAndWait/paltest_signalobjectandwaittest threading/Sleep/test1/paltest_sleep_test1 threading/Sleep/test2/paltest_sleep_test2 threading/SleepEx/test1/paltest_sleepex_test1 threading/SleepEx/test2/paltest_sleepex_test2 threading/SwitchToThread/test1/paltest_switchtothread_test1 threading/TerminateProcess/test1/paltest_terminateprocess_test1 threading/ThreadPriority/test1/paltest_threadpriority_test1 threading/WaitForMultipleObjects/test1/paltest_waitformultipleobjects_test1 threading/WaitForMultipleObjectsEx/test1/paltest_waitformultipleobjectsex_test1 threading/WaitForMultipleObjectsEx/test2/paltest_waitformultipleobjectsex_test2 threading/WaitForMultipleObjectsEx/test3/paltest_waitformultipleobjectsex_test3 threading/WaitForMultipleObjectsEx/test4/paltest_waitformultipleobjectsex_test4 threading/WaitForMultipleObjectsEx/test5/paltest_waitformultipleobjectsex_test5 threading/WaitForMultipleObjectsEx/test6/paltest_waitformultipleobjectsex_test6 threading/WaitForSingleObject/test1/paltest_waitforsingleobject_test1 threading/WaitForSingleObject/WFSOExMutexTest/paltest_waitforsingleobject_wfsoexmutextest threading/WaitForSingleObject/WFSOExSemaphoreTest/paltest_waitforsingleobject_wfsoexsemaphoretest threading/WaitForSingleObject/WFSOExThreadTest/paltest_waitforsingleobject_wfsoexthreadtest threading/WaitForSingleObject/WFSOMutexTest/paltest_waitforsingleobject_wfsomutextest threading/WaitForSingleObject/WFSOProcessTest/paltest_waitforsingleobject_wfsoprocesstest threading/WaitForSingleObject/WFSOSemaphoreTest/paltest_waitforsingleobject_wfsosemaphoretest threading/WaitForSingleObject/WFSOThreadTest/paltest_waitforsingleobject_wfsothreadtest threading/YieldProcessor/test1/paltest_yieldprocessor_test1
-1
dotnet/runtime
66,474
Update repo CMake configuration to target /W4 by default
Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
AaronRobinsonMSFT
2022-03-10T20:20:31Z
2022-03-11T04:59:21Z
ba5207b0f4054fe8963fc3e87c2bd32907516961
5ce2b9f860f7a84c3059650bb67817d59d8f4953
Update repo CMake configuration to target /W4 by default. Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
./src/coreclr/tools/metainfo/mdobj.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include <stdio.h> #include <ctype.h> #include <crtdbg.h> #include "mdinfo.h" #ifndef STRING_BUFFER_LEN #define STRING_BUFFER_LEN 4096 #endif #define OBJ_EXT ".obj" #define OBJ_EXT_W W(".obj") #define OBJ_EXT_LEN 4 #define LIB_EXT ".lib" #define LIB_EXT_W W(".lib") #define LIB_EXT_LEN 4 extern IMetaDataDispenserEx *g_pDisp; extern DWORD g_ValModuleType; // This function is copied from peparse.c file. Making this static, so we won't end up with // duplicate definitions causing confusion. static const char g_szCORMETA[] = ".cormeta"; static HRESULT FindObjMetaData(PVOID pImage, PVOID *ppMetaData, long *pcbMetaData) { IMAGE_FILE_HEADER *pImageHdr; // Header for the .obj file. IMAGE_SECTION_HEADER *pSectionHdr; // Section header. WORD i; // Loop control. // Get a pointer to the header and the first section. pImageHdr = (IMAGE_FILE_HEADER *) pImage; pSectionHdr = (IMAGE_SECTION_HEADER *)(pImageHdr + 1); // Avoid confusion. *ppMetaData = NULL; *pcbMetaData = 0; // Walk each section looking for .cormeta. for (i=0; i<VAL16(pImageHdr->NumberOfSections); i++, pSectionHdr++) { // Simple comparison to section name. if (strcmp((const char *) pSectionHdr->Name, g_szCORMETA) == 0) { *pcbMetaData = VAL32(pSectionHdr->SizeOfRawData); *ppMetaData = (void *) ((UINT_PTR)pImage + VAL32(pSectionHdr->PointerToRawData)); break; } } // Check for errors. if (*ppMetaData == NULL || *pcbMetaData == 0) return (E_FAIL); return (S_OK); } // This function returns the address to the MapView of file and file size. void GetMapViewOfFile(_In_ WCHAR *szFile, PBYTE *ppbMap, DWORD *pdwFileSize) { HANDLE hMapFile; DWORD dwHighSize; HANDLE hFile = WszCreateFile(szFile, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL); if (hFile == INVALID_HANDLE_VALUE) MDInfo::Error("CreateFileA failed!"); *pdwFileSize = GetFileSize(hFile, &dwHighSize); if ((*pdwFileSize == 0xFFFFFFFF) && (GetLastError() != NO_ERROR)) { CloseHandle(hFile); MDInfo::Error("GetFileSize failed!"); } _ASSERTE(dwHighSize == 0); hMapFile = CreateFileMappingW(hFile, NULL, PAGE_READONLY, 0, 0, NULL); CloseHandle(hFile); if (!hMapFile) MDInfo::Error("CreateFileMappingW failed!"); *ppbMap = (PBYTE) MapViewOfFile(hMapFile, FILE_MAP_READ, 0, 0, 0); CloseHandle(hMapFile); if (!*ppbMap) MDInfo::Error("MapViewOfFile failed!"); } // void GetMapViewOfFile() // This function skips a member given the pointer to the member header // and returns a pointer to the next header. PBYTE SkipMember(PBYTE pbMapAddress) { PIMAGE_ARCHIVE_MEMBER_HEADER pMemHdr; ULONG ulMemSize; int j; pMemHdr = (PIMAGE_ARCHIVE_MEMBER_HEADER)pbMapAddress; // Get size of the member. ulMemSize = 0; for (j = 0; j < 10; j++) { if (pMemHdr->Size[j] < '0' || pMemHdr->Size[j] > '9') break; else ulMemSize = ulMemSize * 10 + pMemHdr->Size[j] - '0'; } // Skip past the header. pbMapAddress += IMAGE_SIZEOF_ARCHIVE_MEMBER_HDR + ulMemSize; // Find the next even address if the current one is not even. if ((ULONG_PTR)pbMapAddress % 2) pbMapAddress++; return pbMapAddress; } // void SkipMember() // This function returns the name of the given Obj. If the name fits in the header, // szBuf will be filled in and returned from the function. Else an offset into the long // names section will be returned. char *GetNameOfObj(PBYTE pbLongNames, PIMAGE_ARCHIVE_MEMBER_HEADER pMemHdr, char szBuf[17]) { if (pMemHdr->Name[0] == '/') { ULONG ulOffset = 0; // Long Names section must exist if the .obj file name starts with '/'. _ASSERTE(pbLongNames && "Corrupt archive file - .obj file name in the header starts with " "'/' but no long names section present in the archive file."); // Calculate the offset into the long names section. for (int j = 1; j < 16; j++) { if (pMemHdr->Name[j] < '0' || pMemHdr->Name[j] > '9') break; else ulOffset = ulOffset * 10 + pMemHdr->Name[j] - '0'; } return (char *)(pbLongNames + ulOffset); } else { int j; for (j = 0; j < 16; j++) if ((szBuf[j] = pMemHdr->Name[j]) == '/') break; szBuf[j] = '\0'; return szBuf; } } // char *GetNameOfObj() // DisplayArchive() function // // Opens the .LIB file, and displays the metadata in the specified object files. void DisplayArchive(_In_z_ WCHAR* szFile, ULONG DumpFilter, _In_opt_z_ WCHAR* szObjName, strPassBackFn pDisplayString) { PBYTE pbMapAddress; PBYTE pbStartAddress; PBYTE pbLongNameAddress; PIMAGE_ARCHIVE_MEMBER_HEADER pMemHdr; DWORD dwFileSize; PVOID pvMetaData; char *szName; WCHAR wzName[1024]; char szBuf[17]; long cbMetaData; int i; HRESULT hr; char szString[1024]; GetMapViewOfFile(szFile, &pbMapAddress, &dwFileSize); pbStartAddress = pbMapAddress; // Verify and skip archive signature. if (dwFileSize < IMAGE_ARCHIVE_START_SIZE || strncmp((char *)pbMapAddress, IMAGE_ARCHIVE_START, IMAGE_ARCHIVE_START_SIZE)) { MDInfo::Error("Bad file format - archive signature mis-match!"); } pbMapAddress += IMAGE_ARCHIVE_START_SIZE; // Skip linker member 1, linker member 2. for (i = 0; i < 2; i++) pbMapAddress = SkipMember(pbMapAddress); // Save address of the long name member and skip it if there exists one. pMemHdr = (PIMAGE_ARCHIVE_MEMBER_HEADER)pbMapAddress; if (pMemHdr->Name[0] == '/' && pMemHdr->Name[1] == '/') { pbLongNameAddress = pbMapAddress + IMAGE_SIZEOF_ARCHIVE_MEMBER_HDR; pbMapAddress = SkipMember(pbMapAddress); } else pbLongNameAddress = 0; pDisplayString ("\n"); // Get the MetaData for each object file and display it. while (DWORD(pbMapAddress - pbStartAddress) < dwFileSize) { if((szName = GetNameOfObj(pbLongNameAddress, (PIMAGE_ARCHIVE_MEMBER_HEADER)pbMapAddress, szBuf))!=NULL) { if (Wsz_mbstowcs(wzName, szName, 1024) == -1) MDInfo::Error("Conversion from Multi-Byte to Wide-Char failed."); // Display metadata only for object files. // If szObjName is specified, display metadata only for that one object file. if (!_stricmp(&szName[strlen(szName) - OBJ_EXT_LEN], OBJ_EXT) && (!szObjName || !_wcsicmp(szObjName, wzName))) { // Try to find the MetaData section in the current object file. hr = FindObjMetaData(pbMapAddress+IMAGE_SIZEOF_ARCHIVE_MEMBER_HDR, &pvMetaData, &cbMetaData); if (SUCCEEDED(hr)) { sprintf_s (szString,1024,"MetaData for object file %s:\n", szName); pDisplayString(szString); MDInfo archiveInfo(g_pDisp, (PBYTE)pvMetaData, cbMetaData, pDisplayString, DumpFilter); archiveInfo.DisplayMD(); } else { sprintf_s(szString,1024,"MetaData not found for object file %s!\n\n", szName); pDisplayString(szString); } } } // Skip past the object file. pbMapAddress = SkipMember(pbMapAddress); } UnmapViewOfFile(pbStartAddress); } // void DisplayArchive() // DisplayFile() function // // Opens the meta data content of a .EXE, .CLB, .CLASS, .TLB, .DLL or .LIB file, and // calls RawDisplay() void DisplayFile(_In_z_ WCHAR* szFile, BOOL isFile, ULONG DumpFilter, _In_opt_z_ WCHAR* szObjName, strPassBackFn pDisplayString) { // Open the emit scope // We need to make sure this file isn't too long. Checking _MAX_PATH is probably safe, but since we have a much // larger buffer, we might as well use it all. if (wcslen(szFile) > 1000) return; WCHAR szScope[1024]; char szString[1024]; if (isFile) { wcscpy_s(szScope, 1024, W("file:")); wcscat_s(szScope, 1024, szFile); } else wcscpy_s(szScope, 1024, szFile); // print bar that separates different files pDisplayString("////////////////////////////////////////////////////////////////\n"); WCHAR rcFname[_MAX_FNAME], rcExt[_MAX_EXT]; _wsplitpath_s(szFile, NULL, 0, NULL, 0, rcFname, _MAX_FNAME, rcExt, _MAX_EXT); sprintf_s(szString,1024,"\nFile %S%S: \n",rcFname, rcExt); pDisplayString(szString); if (DumpFilter & MDInfo::dumpValidate) { if (!_wcsicmp(rcExt, OBJ_EXT_W) || !_wcsicmp(rcExt, LIB_EXT_W)) g_ValModuleType = ValidatorModuleTypeObj; else g_ValModuleType = ValidatorModuleTypePE; } if (!_wcsicmp(rcExt, LIB_EXT_W)) DisplayArchive(szFile, DumpFilter, szObjName, pDisplayString); else { MDInfo metaDataInfo(g_pDisp, szScope, pDisplayString, DumpFilter); metaDataInfo.DisplayMD(); } } // void DisplayFile()
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include <stdio.h> #include <ctype.h> #include <crtdbg.h> #include "mdinfo.h" #ifndef STRING_BUFFER_LEN #define STRING_BUFFER_LEN 4096 #endif #define OBJ_EXT ".obj" #define OBJ_EXT_W W(".obj") #define OBJ_EXT_LEN 4 #define LIB_EXT ".lib" #define LIB_EXT_W W(".lib") #define LIB_EXT_LEN 4 extern IMetaDataDispenserEx *g_pDisp; extern DWORD g_ValModuleType; // This function is copied from peparse.c file. Making this static, so we won't end up with // duplicate definitions causing confusion. static const char g_szCORMETA[] = ".cormeta"; static HRESULT FindObjMetaData(PVOID pImage, PVOID *ppMetaData, long *pcbMetaData) { IMAGE_FILE_HEADER *pImageHdr; // Header for the .obj file. IMAGE_SECTION_HEADER *pSectionHdr; // Section header. WORD i; // Loop control. // Get a pointer to the header and the first section. pImageHdr = (IMAGE_FILE_HEADER *) pImage; pSectionHdr = (IMAGE_SECTION_HEADER *)(pImageHdr + 1); // Avoid confusion. *ppMetaData = NULL; *pcbMetaData = 0; // Walk each section looking for .cormeta. for (i=0; i<VAL16(pImageHdr->NumberOfSections); i++, pSectionHdr++) { // Simple comparison to section name. if (strcmp((const char *) pSectionHdr->Name, g_szCORMETA) == 0) { *pcbMetaData = VAL32(pSectionHdr->SizeOfRawData); *ppMetaData = (void *) ((UINT_PTR)pImage + VAL32(pSectionHdr->PointerToRawData)); break; } } // Check for errors. if (*ppMetaData == NULL || *pcbMetaData == 0) return (E_FAIL); return (S_OK); } // This function returns the address to the MapView of file and file size. void GetMapViewOfFile(_In_ WCHAR *szFile, PBYTE *ppbMap, DWORD *pdwFileSize) { HANDLE hMapFile; DWORD dwHighSize; HANDLE hFile = WszCreateFile(szFile, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL); if (hFile == INVALID_HANDLE_VALUE) MDInfo::Error("CreateFileA failed!"); *pdwFileSize = GetFileSize(hFile, &dwHighSize); if ((*pdwFileSize == 0xFFFFFFFF) && (GetLastError() != NO_ERROR)) { CloseHandle(hFile); MDInfo::Error("GetFileSize failed!"); } _ASSERTE(dwHighSize == 0); hMapFile = CreateFileMappingW(hFile, NULL, PAGE_READONLY, 0, 0, NULL); CloseHandle(hFile); if (!hMapFile) MDInfo::Error("CreateFileMappingW failed!"); *ppbMap = (PBYTE) MapViewOfFile(hMapFile, FILE_MAP_READ, 0, 0, 0); CloseHandle(hMapFile); if (!*ppbMap) MDInfo::Error("MapViewOfFile failed!"); } // void GetMapViewOfFile() // This function skips a member given the pointer to the member header // and returns a pointer to the next header. PBYTE SkipMember(PBYTE pbMapAddress) { PIMAGE_ARCHIVE_MEMBER_HEADER pMemHdr; ULONG ulMemSize; int j; pMemHdr = (PIMAGE_ARCHIVE_MEMBER_HEADER)pbMapAddress; // Get size of the member. ulMemSize = 0; for (j = 0; j < 10; j++) { if (pMemHdr->Size[j] < '0' || pMemHdr->Size[j] > '9') break; else ulMemSize = ulMemSize * 10 + pMemHdr->Size[j] - '0'; } // Skip past the header. pbMapAddress += IMAGE_SIZEOF_ARCHIVE_MEMBER_HDR + ulMemSize; // Find the next even address if the current one is not even. if ((ULONG_PTR)pbMapAddress % 2) pbMapAddress++; return pbMapAddress; } // void SkipMember() // This function returns the name of the given Obj. If the name fits in the header, // szBuf will be filled in and returned from the function. Else an offset into the long // names section will be returned. char *GetNameOfObj(PBYTE pbLongNames, PIMAGE_ARCHIVE_MEMBER_HEADER pMemHdr, char szBuf[17]) { if (pMemHdr->Name[0] == '/') { ULONG ulOffset = 0; // Long Names section must exist if the .obj file name starts with '/'. _ASSERTE(pbLongNames && "Corrupt archive file - .obj file name in the header starts with " "'/' but no long names section present in the archive file."); // Calculate the offset into the long names section. for (int j = 1; j < 16; j++) { if (pMemHdr->Name[j] < '0' || pMemHdr->Name[j] > '9') break; else ulOffset = ulOffset * 10 + pMemHdr->Name[j] - '0'; } return (char *)(pbLongNames + ulOffset); } else { int j; for (j = 0; j < 16; j++) if ((szBuf[j] = pMemHdr->Name[j]) == '/') break; szBuf[j] = '\0'; return szBuf; } } // char *GetNameOfObj() // DisplayArchive() function // // Opens the .LIB file, and displays the metadata in the specified object files. void DisplayArchive(_In_z_ WCHAR* szFile, ULONG DumpFilter, _In_opt_z_ WCHAR* szObjName, strPassBackFn pDisplayString) { PBYTE pbMapAddress; PBYTE pbStartAddress; PBYTE pbLongNameAddress; PIMAGE_ARCHIVE_MEMBER_HEADER pMemHdr; DWORD dwFileSize; PVOID pvMetaData; char *szName; WCHAR wzName[1024]; char szBuf[17]; long cbMetaData; int i; HRESULT hr; char szString[1024]; GetMapViewOfFile(szFile, &pbMapAddress, &dwFileSize); pbStartAddress = pbMapAddress; // Verify and skip archive signature. if (dwFileSize < IMAGE_ARCHIVE_START_SIZE || strncmp((char *)pbMapAddress, IMAGE_ARCHIVE_START, IMAGE_ARCHIVE_START_SIZE)) { MDInfo::Error("Bad file format - archive signature mis-match!"); } pbMapAddress += IMAGE_ARCHIVE_START_SIZE; // Skip linker member 1, linker member 2. for (i = 0; i < 2; i++) pbMapAddress = SkipMember(pbMapAddress); // Save address of the long name member and skip it if there exists one. pMemHdr = (PIMAGE_ARCHIVE_MEMBER_HEADER)pbMapAddress; if (pMemHdr->Name[0] == '/' && pMemHdr->Name[1] == '/') { pbLongNameAddress = pbMapAddress + IMAGE_SIZEOF_ARCHIVE_MEMBER_HDR; pbMapAddress = SkipMember(pbMapAddress); } else pbLongNameAddress = 0; pDisplayString ("\n"); // Get the MetaData for each object file and display it. while (DWORD(pbMapAddress - pbStartAddress) < dwFileSize) { if((szName = GetNameOfObj(pbLongNameAddress, (PIMAGE_ARCHIVE_MEMBER_HEADER)pbMapAddress, szBuf))!=NULL) { if (Wsz_mbstowcs(wzName, szName, 1024) == -1) MDInfo::Error("Conversion from Multi-Byte to Wide-Char failed."); // Display metadata only for object files. // If szObjName is specified, display metadata only for that one object file. if (!_stricmp(&szName[strlen(szName) - OBJ_EXT_LEN], OBJ_EXT) && (!szObjName || !_wcsicmp(szObjName, wzName))) { // Try to find the MetaData section in the current object file. hr = FindObjMetaData(pbMapAddress+IMAGE_SIZEOF_ARCHIVE_MEMBER_HDR, &pvMetaData, &cbMetaData); if (SUCCEEDED(hr)) { sprintf_s (szString,1024,"MetaData for object file %s:\n", szName); pDisplayString(szString); MDInfo archiveInfo(g_pDisp, (PBYTE)pvMetaData, cbMetaData, pDisplayString, DumpFilter); archiveInfo.DisplayMD(); } else { sprintf_s(szString,1024,"MetaData not found for object file %s!\n\n", szName); pDisplayString(szString); } } } // Skip past the object file. pbMapAddress = SkipMember(pbMapAddress); } UnmapViewOfFile(pbStartAddress); } // void DisplayArchive() // DisplayFile() function // // Opens the meta data content of a .EXE, .CLB, .CLASS, .TLB, .DLL or .LIB file, and // calls RawDisplay() void DisplayFile(_In_z_ WCHAR* szFile, BOOL isFile, ULONG DumpFilter, _In_opt_z_ WCHAR* szObjName, strPassBackFn pDisplayString) { // Open the emit scope // We need to make sure this file isn't too long. Checking _MAX_PATH is probably safe, but since we have a much // larger buffer, we might as well use it all. if (wcslen(szFile) > 1000) return; WCHAR szScope[1024]; char szString[1024]; if (isFile) { wcscpy_s(szScope, 1024, W("file:")); wcscat_s(szScope, 1024, szFile); } else wcscpy_s(szScope, 1024, szFile); // print bar that separates different files pDisplayString("////////////////////////////////////////////////////////////////\n"); WCHAR rcFname[_MAX_FNAME], rcExt[_MAX_EXT]; _wsplitpath_s(szFile, NULL, 0, NULL, 0, rcFname, _MAX_FNAME, rcExt, _MAX_EXT); sprintf_s(szString,1024,"\nFile %S%S: \n",rcFname, rcExt); pDisplayString(szString); if (DumpFilter & MDInfo::dumpValidate) { if (!_wcsicmp(rcExt, OBJ_EXT_W) || !_wcsicmp(rcExt, LIB_EXT_W)) g_ValModuleType = ValidatorModuleTypeObj; else g_ValModuleType = ValidatorModuleTypePE; } if (!_wcsicmp(rcExt, LIB_EXT_W)) DisplayArchive(szFile, DumpFilter, szObjName, pDisplayString); else { MDInfo metaDataInfo(g_pDisp, szScope, pDisplayString, DumpFilter); metaDataInfo.DisplayMD(); } } // void DisplayFile()
-1
dotnet/runtime
66,474
Update repo CMake configuration to target /W4 by default
Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
AaronRobinsonMSFT
2022-03-10T20:20:31Z
2022-03-11T04:59:21Z
ba5207b0f4054fe8963fc3e87c2bd32907516961
5ce2b9f860f7a84c3059650bb67817d59d8f4953
Update repo CMake configuration to target /W4 by default. Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
./src/libraries/System.Private.Xml/tests/Xslt/TestFiles/TestData/xsltc/baseline/cnt17.txt
<?xml version="1.0" encoding="utf-8"?>Hello, world!
<?xml version="1.0" encoding="utf-8"?>Hello, world!
-1
dotnet/runtime
66,474
Update repo CMake configuration to target /W4 by default
Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
AaronRobinsonMSFT
2022-03-10T20:20:31Z
2022-03-11T04:59:21Z
ba5207b0f4054fe8963fc3e87c2bd32907516961
5ce2b9f860f7a84c3059650bb67817d59d8f4953
Update repo CMake configuration to target /W4 by default. Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
./src/coreclr/pal/tests/palsuite/c_runtime/wcsstr/test1/test1.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*============================================================================ ** ** Source: test1.c ** ** Purpose: ** Tests that wcsstr correctly find substrings in wide stings, including ** returning NULL when the substring can't be found. ** ** **==========================================================================*/ #include <palsuite.h> PALTEST(c_runtime_wcsstr_test1_paltest_wcsstr_test1, "c_runtime/wcsstr/test1/paltest_wcsstr_test1") { WCHAR *string; WCHAR *key1; WCHAR *key2; WCHAR key3[] = { 0 }; WCHAR *key4; WCHAR *result; if (PAL_Initialize(argc, argv)) { return FAIL; } string = convert("foo bar baz bar"); key1 = convert("bar"); key2 = convert("Bar"); key4 = convert("arggggh!"); result = wcsstr(string, key1); if (result != string + 4) { Fail("ERROR: Got incorrect result in scanning \"%s\" for \"%s\".\n" "Expected to get pointer to %#p, got %#p\n", convertC(string), convertC(key1), string + 4, result); } result = wcsstr(string, key2); if (result != NULL) { Fail("ERROR: Got incorrect result in scanning \"%s\" for \"%s\".\n" "Expected to get pointer to %#p, got %#p\n", convertC(string), convertC(key2), NULL, result); } result = wcsstr(string, key3); if (result != string) { Fail("ERROR: Got incorrect result in scanning \"%s\" for \"%s\".\n" "Expected to get pointer to %#p, got %#p\n", convertC(string), convertC(key3), string, result); } result = wcsstr(string, key4); if (result != nullptr) { Fail("ERROR: Got incorrect result in scanning \"%s\" for \"%s\".\n" "Expected to get pointer to null, got %#p\n", convertC(string), convertC(key4), result); } PAL_Terminate(); return PASS; }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*============================================================================ ** ** Source: test1.c ** ** Purpose: ** Tests that wcsstr correctly find substrings in wide stings, including ** returning NULL when the substring can't be found. ** ** **==========================================================================*/ #include <palsuite.h> PALTEST(c_runtime_wcsstr_test1_paltest_wcsstr_test1, "c_runtime/wcsstr/test1/paltest_wcsstr_test1") { WCHAR *string; WCHAR *key1; WCHAR *key2; WCHAR key3[] = { 0 }; WCHAR *key4; WCHAR *result; if (PAL_Initialize(argc, argv)) { return FAIL; } string = convert("foo bar baz bar"); key1 = convert("bar"); key2 = convert("Bar"); key4 = convert("arggggh!"); result = wcsstr(string, key1); if (result != string + 4) { Fail("ERROR: Got incorrect result in scanning \"%s\" for \"%s\".\n" "Expected to get pointer to %#p, got %#p\n", convertC(string), convertC(key1), string + 4, result); } result = wcsstr(string, key2); if (result != NULL) { Fail("ERROR: Got incorrect result in scanning \"%s\" for \"%s\".\n" "Expected to get pointer to %#p, got %#p\n", convertC(string), convertC(key2), NULL, result); } result = wcsstr(string, key3); if (result != string) { Fail("ERROR: Got incorrect result in scanning \"%s\" for \"%s\".\n" "Expected to get pointer to %#p, got %#p\n", convertC(string), convertC(key3), string, result); } result = wcsstr(string, key4); if (result != nullptr) { Fail("ERROR: Got incorrect result in scanning \"%s\" for \"%s\".\n" "Expected to get pointer to null, got %#p\n", convertC(string), convertC(key4), result); } PAL_Terminate(); return PASS; }
-1
dotnet/runtime
66,474
Update repo CMake configuration to target /W4 by default
Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
AaronRobinsonMSFT
2022-03-10T20:20:31Z
2022-03-11T04:59:21Z
ba5207b0f4054fe8963fc3e87c2bd32907516961
5ce2b9f860f7a84c3059650bb67817d59d8f4953
Update repo CMake configuration to target /W4 by default. Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
./src/native/corehost/version_compatibility_range.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include "pal.h" #include "version_compatibility_range.h" namespace { const pal::char_t* OptionNameMapping[] = { _X("exact"), _X("patch"), _X("minor"), _X("major") }; static_assert((sizeof(OptionNameMapping) / sizeof(*OptionNameMapping)) == static_cast<size_t>(version_compatibility_range_t::__last), "Invalid option count"); } pal::string_t version_compatibility_range_to_string(version_compatibility_range_t value) { int idx = static_cast<int>(value); assert(0 <= idx && idx < static_cast<int>(version_compatibility_range_t::__last)); return OptionNameMapping[idx]; }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include "pal.h" #include "version_compatibility_range.h" namespace { const pal::char_t* OptionNameMapping[] = { _X("exact"), _X("patch"), _X("minor"), _X("major") }; static_assert((sizeof(OptionNameMapping) / sizeof(*OptionNameMapping)) == static_cast<size_t>(version_compatibility_range_t::__last), "Invalid option count"); } pal::string_t version_compatibility_range_to_string(version_compatibility_range_t value) { int idx = static_cast<int>(value); assert(0 <= idx && idx < static_cast<int>(version_compatibility_range_t::__last)); return OptionNameMapping[idx]; }
-1
dotnet/runtime
66,474
Update repo CMake configuration to target /W4 by default
Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
AaronRobinsonMSFT
2022-03-10T20:20:31Z
2022-03-11T04:59:21Z
ba5207b0f4054fe8963fc3e87c2bd32907516961
5ce2b9f860f7a84c3059650bb67817d59d8f4953
Update repo CMake configuration to target /W4 by default. Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
./src/coreclr/pal/tests/palsuite/file_io/GetTempFileNameA/test3/gettempfilenamea.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*===================================================================== ** ** Source: GetTempFileNameA.c (test 3) ** ** Purpose: Tests the PAL implementation of the GetTempFileNameA function. ** Checks the file attributes and ensures that getting a file name, ** deleting the file and getting another doesn't produce the same ** as the just deleted file. Also checks the file size is 0. ** ** Depends on: ** GetFileAttributesA ** CloseHandle ** DeleteFileA ** CreateFileA ** GetFileSize ** ** **===================================================================*/ #include <palsuite.h> PALTEST(file_io_GetTempFileNameA_test3_paltest_gettempfilenamea_test3, "file_io/GetTempFileNameA/test3/paltest_gettempfilenamea_test3") { const UINT uUnique = 0; UINT uiError; const char* szDot = {"."}; char szReturnedName[MAX_LONGPATH]; char szReturnedName_02[MAX_LONGPATH]; DWORD dwFileSize = 0; HANDLE hFile; if (0 != PAL_Initialize(argc, argv)) { return FAIL; } /* valid path with null prefix */ uiError = GetTempFileNameA(szDot, NULL, uUnique, szReturnedName); if (uiError == 0) { Fail("GetTempFileNameA: ERROR -> Call failed with a valid path " "with the error code: %u.\n", GetLastError()); } /* verify temp file was created */ if (GetFileAttributesA(szReturnedName) == -1) { Fail("GetTempFileNameA: ERROR -> GetFileAttributes failed on the " "returned temp file \"%s\" with error code: %u.\n", szReturnedName, GetLastError()); } /* ** verify that the file size is 0 bytes */ hFile = CreateFileA(szReturnedName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) { Trace("GetTempFileNameA: ERROR -> CreateFileA failed to open" " the created temp file with error code: %u.\n", GetLastError()); if (!DeleteFileA(szReturnedName)) { Trace("GetTempFileNameA: ERROR -> DeleteFileA failed to delete" " the created temp file with error code: %u.\n", GetLastError()); } Fail(""); } if ((dwFileSize = GetFileSize(hFile, NULL)) != (DWORD)0) { Trace("GetTempFileNameA: ERROR -> GetFileSize returned %u whereas" "it should have returned 0.\n", dwFileSize); if (!CloseHandle(hFile)) { Trace("GetTempFileNameA: ERROR -> CloseHandle failed. " "GetLastError returned: %u.\n", GetLastError()); } if (!DeleteFileA(szReturnedName)) { Trace("GetTempFileNameA: ERROR -> DeleteFileA failed to delete" " the created temp file with error code: %u.\n", GetLastError()); } Fail(""); } if (!CloseHandle(hFile)) { Fail("GetTempFileNameA: ERROR -> CloseHandle failed. " "GetLastError returned: %u.\n", GetLastError()); } if (DeleteFileA(szReturnedName) != TRUE) { Fail("GetTempFileNameA: ERROR -> DeleteFileA failed to delete" " the created temp file with error code: %u.\n", GetLastError()); } /* get another and make sure it's not the same as the last */ uiError = GetTempFileNameA(szDot, NULL, uUnique, szReturnedName_02); if (uiError == 0) { Fail("GetTempFileNameA: ERROR -> Call failed with a valid path " "with the error code: %u.\n", GetLastError()); } /* did we get different names? */ if (strcmp(szReturnedName, szReturnedName_02) == 0) { Trace("GetTempFileNameA: ERROR -> The first call returned \"%s\". " "The second call returned \"%s\" and the two should not be" " the same.\n", szReturnedName, szReturnedName_02); if (!DeleteFileA(szReturnedName_02)) { Trace("GetTempFileNameA: ERROR -> DeleteFileA failed to delete" " the created temp file with error code: %u.\n", GetLastError()); } Fail(""); } /* clean up */ if (!DeleteFileA(szReturnedName_02)) { Fail("GetTempFileNameA: ERROR -> DeleteFileA failed to delete" " the created temp file with error code: %u.\n", GetLastError()); } PAL_Terminate(); return PASS; }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*===================================================================== ** ** Source: GetTempFileNameA.c (test 3) ** ** Purpose: Tests the PAL implementation of the GetTempFileNameA function. ** Checks the file attributes and ensures that getting a file name, ** deleting the file and getting another doesn't produce the same ** as the just deleted file. Also checks the file size is 0. ** ** Depends on: ** GetFileAttributesA ** CloseHandle ** DeleteFileA ** CreateFileA ** GetFileSize ** ** **===================================================================*/ #include <palsuite.h> PALTEST(file_io_GetTempFileNameA_test3_paltest_gettempfilenamea_test3, "file_io/GetTempFileNameA/test3/paltest_gettempfilenamea_test3") { const UINT uUnique = 0; UINT uiError; const char* szDot = {"."}; char szReturnedName[MAX_LONGPATH]; char szReturnedName_02[MAX_LONGPATH]; DWORD dwFileSize = 0; HANDLE hFile; if (0 != PAL_Initialize(argc, argv)) { return FAIL; } /* valid path with null prefix */ uiError = GetTempFileNameA(szDot, NULL, uUnique, szReturnedName); if (uiError == 0) { Fail("GetTempFileNameA: ERROR -> Call failed with a valid path " "with the error code: %u.\n", GetLastError()); } /* verify temp file was created */ if (GetFileAttributesA(szReturnedName) == -1) { Fail("GetTempFileNameA: ERROR -> GetFileAttributes failed on the " "returned temp file \"%s\" with error code: %u.\n", szReturnedName, GetLastError()); } /* ** verify that the file size is 0 bytes */ hFile = CreateFileA(szReturnedName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) { Trace("GetTempFileNameA: ERROR -> CreateFileA failed to open" " the created temp file with error code: %u.\n", GetLastError()); if (!DeleteFileA(szReturnedName)) { Trace("GetTempFileNameA: ERROR -> DeleteFileA failed to delete" " the created temp file with error code: %u.\n", GetLastError()); } Fail(""); } if ((dwFileSize = GetFileSize(hFile, NULL)) != (DWORD)0) { Trace("GetTempFileNameA: ERROR -> GetFileSize returned %u whereas" "it should have returned 0.\n", dwFileSize); if (!CloseHandle(hFile)) { Trace("GetTempFileNameA: ERROR -> CloseHandle failed. " "GetLastError returned: %u.\n", GetLastError()); } if (!DeleteFileA(szReturnedName)) { Trace("GetTempFileNameA: ERROR -> DeleteFileA failed to delete" " the created temp file with error code: %u.\n", GetLastError()); } Fail(""); } if (!CloseHandle(hFile)) { Fail("GetTempFileNameA: ERROR -> CloseHandle failed. " "GetLastError returned: %u.\n", GetLastError()); } if (DeleteFileA(szReturnedName) != TRUE) { Fail("GetTempFileNameA: ERROR -> DeleteFileA failed to delete" " the created temp file with error code: %u.\n", GetLastError()); } /* get another and make sure it's not the same as the last */ uiError = GetTempFileNameA(szDot, NULL, uUnique, szReturnedName_02); if (uiError == 0) { Fail("GetTempFileNameA: ERROR -> Call failed with a valid path " "with the error code: %u.\n", GetLastError()); } /* did we get different names? */ if (strcmp(szReturnedName, szReturnedName_02) == 0) { Trace("GetTempFileNameA: ERROR -> The first call returned \"%s\". " "The second call returned \"%s\" and the two should not be" " the same.\n", szReturnedName, szReturnedName_02); if (!DeleteFileA(szReturnedName_02)) { Trace("GetTempFileNameA: ERROR -> DeleteFileA failed to delete" " the created temp file with error code: %u.\n", GetLastError()); } Fail(""); } /* clean up */ if (!DeleteFileA(szReturnedName_02)) { Fail("GetTempFileNameA: ERROR -> DeleteFileA failed to delete" " the created temp file with error code: %u.\n", GetLastError()); } PAL_Terminate(); return PASS; }
-1
dotnet/runtime
66,474
Update repo CMake configuration to target /W4 by default
Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
AaronRobinsonMSFT
2022-03-10T20:20:31Z
2022-03-11T04:59:21Z
ba5207b0f4054fe8963fc3e87c2bd32907516961
5ce2b9f860f7a84c3059650bb67817d59d8f4953
Update repo CMake configuration to target /W4 by default. Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
./src/coreclr/debug/di/symbolinfo.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // callbacks for diasymreader when using SymConverter #include "stdafx.h" #include "symbolinfo.h" #include "ex.h" SymbolInfo::SymbolInfo() { m_cRef=1; } SymbolInfo::~SymbolInfo() { for (COUNT_T i = 0;i < m_Documents.GetCount();i++) { if (m_Documents.Get(i) != NULL) ((ISymUnmanagedDocumentWriter*)m_Documents.Get(i))->Release(); } } HRESULT SymbolInfo::AddDocument(DWORD id, ISymUnmanagedDocumentWriter* pDocument) { CONTRACTL { NOTHROW; } CONTRACTL_END; HRESULT hr=S_OK; EX_TRY { while(m_Documents.GetCount()<=id) m_Documents.Append(NULL); _ASSERTE(m_Documents.Get(id) == NULL); m_Documents.Set(id,pDocument); pDocument->AddRef(); } EX_CATCH_HRESULT(hr); return hr; } HRESULT SymbolInfo::MapDocument(DWORD id, ISymUnmanagedDocumentWriter** pDocument) { CONTRACTL { NOTHROW; } CONTRACTL_END; HRESULT hr=E_FAIL; if(m_Documents.GetCount()>id) { *pDocument=(ISymUnmanagedDocumentWriter*)m_Documents.Get(id); if (*pDocument == NULL) return E_FAIL; (*pDocument)->AddRef(); hr=S_OK; } return hr; } HRESULT SymbolInfo::SetClassProps(mdToken cls, DWORD flags, LPCWSTR wszName, mdToken parent) { CONTRACTL { NOTHROW; } CONTRACTL_END; HRESULT hr=S_OK; EX_TRY { if(m_Classes.Lookup(cls) == NULL) { NewHolder<ClassProps> classProps (new ClassProps(cls,flags,wszName,parent)); m_Classes.Add(classProps); classProps.SuppressRelease(); } } EX_CATCH_HRESULT(hr); return hr; } HRESULT SymbolInfo::AddSignature(SBuffer& sig, mdSignature token) { CONTRACTL { NOTHROW; } CONTRACTL_END; HRESULT hr=S_OK; EX_TRY { if ( m_Signatures.Lookup(sig) == NULL) { NewHolder<SignatureProps> sigProps (new SignatureProps(sig,token)); m_Signatures.Add(sigProps); sigProps.SuppressRelease(); } } EX_CATCH_HRESULT(hr); return hr; } SymbolInfo::ClassProps* SymbolInfo::FindClass(mdToken cls) { WRAPPER_NO_CONTRACT; return m_Classes.Lookup(cls); } SymbolInfo::SignatureProps* SymbolInfo::FindSignature(SBuffer& sig) { WRAPPER_NO_CONTRACT; return m_Signatures.Lookup(sig); } HRESULT SymbolInfo::AddScope(ULONG32 left, ULONG32 right) { CONTRACTL { NOTHROW; } CONTRACTL_END; HRESULT hr=S_OK; EX_TRY { if (m_Scopes.Lookup(left) == NULL) { NewHolder<ScopeMap> map (new ScopeMap(left,right)); m_Scopes.Add(map); map.SuppressRelease(); } } EX_CATCH_HRESULT(hr); return hr; } HRESULT SymbolInfo::MapScope(ULONG32 left, ULONG32* pRight) { CONTRACTL { NOTHROW; } CONTRACTL_END; ScopeMap* props = m_Scopes.Lookup(left); if(props == NULL) { _ASSERTE(FALSE); return E_FAIL; } *pRight=props->right; return S_OK; } HRESULT SymbolInfo::SetMethodProps(mdToken method, mdToken cls, LPCWSTR wszName) { CONTRACTL { NOTHROW; } CONTRACTL_END; HRESULT hr=S_OK; EX_TRY { m_LastMethod.method=method; m_LastMethod.cls=cls; m_LastMethod.wszName=wszName; m_LastMethod.wszName.Normalize(); } EX_CATCH_HRESULT(hr) return hr; } // IUnknown methods STDMETHODIMP SymbolInfo::QueryInterface (REFIID riid, LPVOID * ppvObj) { CONTRACTL { NOTHROW; } CONTRACTL_END; if(ppvObj==NULL) return E_POINTER; if (riid == IID_IMetaDataEmit) *ppvObj=static_cast<IMetaDataEmit*>(this); else if (riid == IID_IMetaDataImport) *ppvObj=static_cast<IMetaDataImport*>(this); else if (riid == IID_IUnknown) *ppvObj=static_cast<IMetaDataImport*>(this); else return E_NOTIMPL; AddRef(); return S_OK; } STDMETHODIMP_(ULONG) SymbolInfo::AddRef () { LIMITED_METHOD_CONTRACT; return InterlockedIncrement(&m_cRef); } STDMETHODIMP_(ULONG) SymbolInfo::Release () { LIMITED_METHOD_CONTRACT; ULONG retval=InterlockedDecrement(&m_cRef); if(retval==0) delete this; return retval; } STDMETHODIMP SymbolInfo::GetTypeDefProps ( // S_OK or error. mdTypeDef td, // [IN] TypeDef token for inquiry. _Out_writes_to_opt_(cchTypeDef, pchTypeDef) LPWSTR szTypeDef, // [OUT] Put name here. ULONG cchTypeDef, // [IN] size of name buffer in wide chars. ULONG *pchTypeDef, // [OUT] put size of name (wide chars) here. DWORD *pdwTypeDefFlags, // [OUT] Put flags here. mdToken *ptkExtends) // [OUT] Put base class TypeDef/TypeRef here. { CONTRACTL { NOTHROW; PRECONDITION(ptkExtends==NULL); PRECONDITION(CheckPointer(szTypeDef)); } CONTRACTL_END; if (szTypeDef == NULL) return E_POINTER; ClassProps* classInfo=FindClass(td); _ASSERTE(classInfo); if(classInfo == NULL) return E_UNEXPECTED; if(pdwTypeDefFlags) *pdwTypeDefFlags=classInfo->flags; SIZE_T cch=wcslen(classInfo->wszName)+1; if (cch > UINT32_MAX) return E_UNEXPECTED; *pchTypeDef=(ULONG)cch; if (cchTypeDef < cch) return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); wcscpy_s(szTypeDef,cchTypeDef,classInfo->wszName); if(pdwTypeDefFlags) *pdwTypeDefFlags=classInfo->flags; return S_OK; } STDMETHODIMP SymbolInfo::GetMethodProps ( mdMethodDef mb, // The method for which to get props. mdTypeDef *pClass, // Put method's class here. _Out_writes_to_opt_(cchMethod, *pchMethod) LPWSTR szMethod, // Put method's name here. ULONG cchMethod, // Size of szMethod buffer in wide chars. ULONG *pchMethod, // Put actual size here DWORD *pdwAttr, // Put flags here. PCCOR_SIGNATURE *ppvSigBlob, // [OUT] point to the blob value of meta data ULONG *pcbSigBlob, // [OUT] actual size of signature blob ULONG *pulCodeRVA, // [OUT] codeRVA DWORD *pdwImplFlags) // [OUT] Impl. Flags { CONTRACTL { NOTHROW; PRECONDITION(m_LastMethod.method==mb); PRECONDITION(pClass!=NULL); PRECONDITION(pchMethod!=NULL); PRECONDITION(pdwAttr == NULL); PRECONDITION(ppvSigBlob == NULL); PRECONDITION(pcbSigBlob == NULL); PRECONDITION(pulCodeRVA == NULL); PRECONDITION(pdwImplFlags == NULL); PRECONDITION(CheckPointer(szMethod)); } CONTRACTL_END; if (szMethod == NULL) return E_POINTER; *pClass=m_LastMethod.cls; SIZE_T cch=wcslen(m_LastMethod.wszName)+1; if(cch > UINT32_MAX) return E_UNEXPECTED; *pchMethod=(ULONG)cch; if (cchMethod < cch) return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); wcscpy_s(szMethod,cchMethod,m_LastMethod.wszName); return S_OK; } STDMETHODIMP SymbolInfo::GetNestedClassProps ( // S_OK or error. mdTypeDef tdNestedClass, // [IN] NestedClass token. mdTypeDef *ptdEnclosingClass) // [OUT] EnclosingClass token. { CONTRACTL { NOTHROW; PRECONDITION(CheckPointer(ptdEnclosingClass)); } CONTRACTL_END; if(ptdEnclosingClass == NULL) return E_POINTER; ClassProps* classInfo=FindClass(tdNestedClass); _ASSERTE(classInfo); if(classInfo == NULL) return E_UNEXPECTED; *ptdEnclosingClass=classInfo->tkEnclosing; return S_OK; } STDMETHODIMP SymbolInfo::GetTokenFromSig ( // S_OK or error. PCCOR_SIGNATURE pvSig, // [IN] Signature to define. ULONG cbSig, // [IN] Size of signature data. mdSignature *pmsig) // [OUT] returned signature token. { SBuffer sig; sig.SetImmutable(pvSig,cbSig); SignatureProps* sigProps=FindSignature(sig); _ASSERTE(sigProps); if(sigProps == NULL) return E_UNEXPECTED; *pmsig=sigProps->tkSig; return S_OK; } ////////////////////////////////////////////// // All the functions below are just stubs STDMETHODIMP_(void) SymbolInfo::CloseEnum (HCORENUM hEnum) { _ASSERTE(!"NYI"); } STDMETHODIMP SymbolInfo::CountEnum (HCORENUM hEnum, ULONG *pulCount) { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::ResetEnum (HCORENUM hEnum, ULONG ulPos) { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::EnumTypeDefs (HCORENUM *phEnum, mdTypeDef rTypeDefs[], ULONG cMax, ULONG *pcTypeDefs) { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::EnumInterfaceImpls (HCORENUM *phEnum, mdTypeDef td, mdInterfaceImpl rImpls[], ULONG cMax, ULONG* pcImpls) { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::EnumTypeRefs (HCORENUM *phEnum, mdTypeRef rTypeRefs[], ULONG cMax, ULONG* pcTypeRefs) { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::FindTypeDefByName ( // S_OK or error. LPCWSTR szTypeDef, // [IN] Name of the Type. mdToken tkEnclosingClass, // [IN] TypeDef/TypeRef for Enclosing class. mdTypeDef *ptd) // [OUT] Put the TypeDef token here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetScopeProps ( // S_OK or error. _Out_writes_to_opt_(cchName, *pchName) LPWSTR szName, // [OUT] Put the name here. ULONG cchName, // [IN] Size of name buffer in wide chars. ULONG *pchName, // [OUT] Put size of name (wide chars) here. GUID *pmvid) // [OUT, OPTIONAL] Put MVID here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetModuleFromScope ( // S_OK. mdModule *pmd) // [OUT] Put mdModule token here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetInterfaceImplProps ( // S_OK or error. mdInterfaceImpl iiImpl, // [IN] InterfaceImpl token. mdTypeDef *pClass, // [OUT] Put implementing class token here. mdToken *ptkIface) // [OUT] Put implemented interface token here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetTypeRefProps ( // S_OK or error. mdTypeRef tr, // [IN] TypeRef token. mdToken *ptkResolutionScope, // [OUT] Resolution scope, ModuleRef or AssemblyRef. _Out_writes_to_opt_(cchName, *pchName) LPWSTR szName, // [OUT] Name of the TypeRef. ULONG cchName, // [IN] Size of buffer. ULONG *pchName) // [OUT] Size of Name. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::ResolveTypeRef (mdTypeRef tr, REFIID riid, IUnknown **ppIScope, mdTypeDef *ptd) { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::EnumMembers ( // S_OK, S_FALSE, or error. HCORENUM *phEnum, // [IN|OUT] Pointer to the enum. mdTypeDef cl, // [IN] TypeDef to scope the enumeration. mdToken rMembers[], // [OUT] Put MemberDefs here. ULONG cMax, // [IN] Max MemberDefs to put. ULONG *pcTokens) // [OUT] Put # put here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::EnumMembersWithName ( // S_OK, S_FALSE, or error. HCORENUM *phEnum, // [IN|OUT] Pointer to the enum. mdTypeDef cl, // [IN] TypeDef to scope the enumeration. LPCWSTR szName, // [IN] Limit results to those with this name. mdToken rMembers[], // [OUT] Put MemberDefs here. ULONG cMax, // [IN] Max MemberDefs to put. ULONG *pcTokens) // [OUT] Put # put here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::EnumMethods ( // S_OK, S_FALSE, or error. HCORENUM *phEnum, // [IN|OUT] Pointer to the enum. mdTypeDef cl, // [IN] TypeDef to scope the enumeration. mdMethodDef rMethods[], // [OUT] Put MethodDefs here. ULONG cMax, // [IN] Max MethodDefs to put. ULONG *pcTokens) // [OUT] Put # put here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::EnumMethodsWithName ( // S_OK, S_FALSE, or error. HCORENUM *phEnum, // [IN|OUT] Pointer to the enum. mdTypeDef cl, // [IN] TypeDef to scope the enumeration. LPCWSTR szName, // [IN] Limit results to those with this name. mdMethodDef rMethods[], // [OU] Put MethodDefs here. ULONG cMax, // [IN] Max MethodDefs to put. ULONG *pcTokens) // [OUT] Put # put here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::EnumFields ( // S_OK, S_FALSE, or error. HCORENUM *phEnum, // [IN|OUT] Pointer to the enum. mdTypeDef cl, // [IN] TypeDef to scope the enumeration. mdFieldDef rFields[], // [OUT] Put FieldDefs here. ULONG cMax, // [IN] Max FieldDefs to put. ULONG *pcTokens) // [OUT] Put # put here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::EnumFieldsWithName ( // S_OK, S_FALSE, or error. HCORENUM *phEnum, // [IN|OUT] Pointer to the enum. mdTypeDef cl, // [IN] TypeDef to scope the enumeration. LPCWSTR szName, // [IN] Limit results to those with this name. mdFieldDef rFields[], // [OUT] Put MemberDefs here. ULONG cMax, // [IN] Max MemberDefs to put. ULONG *pcTokens) // [OUT] Put # put here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::EnumParams ( // S_OK, S_FALSE, or error. HCORENUM *phEnum, // [IN|OUT] Pointer to the enum. mdMethodDef mb, // [IN] MethodDef to scope the enumeration. mdParamDef rParams[], // [OUT] Put ParamDefs here. ULONG cMax, // [IN] Max ParamDefs to put. ULONG *pcTokens) // [OUT] Put # put here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::EnumMemberRefs ( // S_OK, S_FALSE, or error. HCORENUM *phEnum, // [IN|OUT] Pointer to the enum. mdToken tkParent, // [IN] Parent token to scope the enumeration. mdMemberRef rMemberRefs[], // [OUT] Put MemberRefs here. ULONG cMax, // [IN] Max MemberRefs to put. ULONG *pcTokens) // [OUT] Put # put here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::EnumMethodImpls ( // S_OK, S_FALSE, or error HCORENUM *phEnum, // [IN|OUT] Pointer to the enum. mdTypeDef td, // [IN] TypeDef to scope the enumeration. mdToken rMethodBody[], // [OUT] Put Method Body tokens here. mdToken rMethodDecl[], // [OUT] Put Method Declaration tokens here. ULONG cMax, // [IN] Max tokens to put. ULONG *pcTokens) // [OUT] Put # put here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::EnumPermissionSets ( // S_OK, S_FALSE, or error. HCORENUM *phEnum, // [IN|OUT] Pointer to the enum. mdToken tk, // [IN] if !NIL, token to scope the enumeration. DWORD dwActions, // [IN] if !0, return only these actions. mdPermission rPermission[], // [OUT] Put Permissions here. ULONG cMax, // [IN] Max Permissions to put. ULONG *pcTokens) // [OUT] Put # put here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::FindMember ( mdTypeDef td, // [IN] given typedef LPCWSTR szName, // [IN] member name PCCOR_SIGNATURE pvSigBlob, // [IN] point to a blob value of CLR signature ULONG cbSigBlob, // [IN] count of bytes in the signature blob mdToken *pmb) // [OUT] matching memberdef { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::FindMethod ( mdTypeDef td, // [IN] given typedef LPCWSTR szName, // [IN] member name PCCOR_SIGNATURE pvSigBlob, // [IN] point to a blob value of CLR signature ULONG cbSigBlob, // [IN] count of bytes in the signature blob mdMethodDef *pmb) // [OUT] matching memberdef { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::FindField ( mdTypeDef td, // [IN] given typedef LPCWSTR szName, // [IN] member name PCCOR_SIGNATURE pvSigBlob, // [IN] point to a blob value of CLR signature ULONG cbSigBlob, // [IN] count of bytes in the signature blob mdFieldDef *pmb) // [OUT] matching memberdef { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::FindMemberRef ( mdTypeRef td, // [IN] given typeRef LPCWSTR szName, // [IN] member name PCCOR_SIGNATURE pvSigBlob, // [IN] point to a blob value of CLR signature ULONG cbSigBlob, // [IN] count of bytes in the signature blob mdMemberRef *pmr) // [OUT] matching memberref { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetMemberRefProps ( // S_OK or error. mdMemberRef mr, // [IN] given memberref mdToken *ptk, // [OUT] Put classref or classdef here. _Out_writes_to_opt_(cchMember, *pchMember) LPWSTR szMember, // [OUT] buffer to fill for member's name ULONG cchMember, // [IN] the count of char of szMember ULONG *pchMember, // [OUT] actual count of char in member name PCCOR_SIGNATURE *ppvSigBlob, // [OUT] point to meta data blob value ULONG *pbSig) // [OUT] actual size of signature blob { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::EnumProperties ( // S_OK, S_FALSE, or error. HCORENUM *phEnum, // [IN|OUT] Pointer to the enum. mdTypeDef td, // [IN] TypeDef to scope the enumeration. mdProperty rProperties[], // [OUT] Put Properties here. ULONG cMax, // [IN] Max properties to put. ULONG *pcProperties) // [OUT] Put # put here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::EnumEvents ( // S_OK, S_FALSE, or error. HCORENUM *phEnum, // [IN|OUT] Pointer to the enum. mdTypeDef td, // [IN] TypeDef to scope the enumeration. mdEvent rEvents[], // [OUT] Put events here. ULONG cMax, // [IN] Max events to put. ULONG *pcEvents) // [OUT] Put # put here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetEventProps ( // S_OK, S_FALSE, or error. mdEvent ev, // [IN] event token mdTypeDef *pClass, // [OUT] typedef containing the event declarion. LPCWSTR szEvent, // [OUT] Event name ULONG cchEvent, // [IN] the count of wchar of szEvent ULONG *pchEvent, // [OUT] actual count of wchar for event's name DWORD *pdwEventFlags, // [OUT] Event flags. mdToken *ptkEventType, // [OUT] EventType class mdMethodDef *pmdAddOn, // [OUT] AddOn method of the event mdMethodDef *pmdRemoveOn, // [OUT] RemoveOn method of the event mdMethodDef *pmdFire, // [OUT] Fire method of the event mdMethodDef rmdOtherMethod[], // [OUT] other method of the event ULONG cMax, // [IN] size of rmdOtherMethod ULONG *pcOtherMethod) // [OUT] total number of other method of this event { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::EnumMethodSemantics ( // S_OK, S_FALSE, or error. HCORENUM *phEnum, // [IN|OUT] Pointer to the enum. mdMethodDef mb, // [IN] MethodDef to scope the enumeration. mdToken rEventProp[], // [OUT] Put Event/Property here. ULONG cMax, // [IN] Max properties to put. ULONG *pcEventProp) // [OUT] Put # put here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetMethodSemantics ( // S_OK, S_FALSE, or error. mdMethodDef mb, // [IN] method token mdToken tkEventProp, // [IN] event/property token. DWORD *pdwSemanticsFlags) // [OUT] the role flags for the method/propevent pair { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetClassLayout ( mdTypeDef td, // [IN] give typedef DWORD *pdwPackSize, // [OUT] 1, 2, 4, 8, or 16 COR_FIELD_OFFSET rFieldOffset[], // [OUT] field offset array ULONG cMax, // [IN] size of the array ULONG *pcFieldOffset, // [OUT] needed array size ULONG *pulClassSize) // [OUT] the size of the class { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetFieldMarshal ( mdToken tk, // [IN] given a field's memberdef PCCOR_SIGNATURE *ppvNativeType, // [OUT] native type of this field ULONG *pcbNativeType) // [OUT] the count of bytes of *ppvNativeType { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetRVA ( // S_OK or error. mdToken tk, // Member for which to set offset ULONG *pulCodeRVA, // The offset DWORD *pdwImplFlags) // the implementation flags { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetPermissionSetProps ( mdPermission pm, // [IN] the permission token. DWORD *pdwAction, // [OUT] CorDeclSecurity. void const **ppvPermission, // [OUT] permission blob. ULONG *pcbPermission) // [OUT] count of bytes of pvPermission. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetSigFromToken ( // S_OK or error. mdSignature mdSig, // [IN] Signature token. PCCOR_SIGNATURE *ppvSig, // [OUT] return pointer to token. ULONG *pcbSig) // [OUT] return size of signature. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetModuleRefProps ( // S_OK or error. mdModuleRef mur, // [IN] moduleref token. _Out_writes_to_opt_(cchName, *pchName) LPWSTR szName, // [OUT] buffer to fill with the moduleref name. ULONG cchName, // [IN] size of szName in wide characters. ULONG *pchName) // [OUT] actual count of characters in the name. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::EnumModuleRefs ( // S_OK or error. HCORENUM *phEnum, // [IN|OUT] pointer to the enum. mdModuleRef rModuleRefs[], // [OUT] put modulerefs here. ULONG cmax, // [IN] max memberrefs to put. ULONG *pcModuleRefs) // [OUT] put # put here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetTypeSpecFromToken ( // S_OK or error. mdTypeSpec typespec, // [IN] TypeSpec token. PCCOR_SIGNATURE *ppvSig, // [OUT] return pointer to TypeSpec signature ULONG *pcbSig) // [OUT] return size of signature. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetNameFromToken ( // Not Recommended! May be removed! mdToken tk, // [IN] Token to get name from. Must have a name. MDUTF8CSTR *pszUtf8NamePtr) // [OUT] Return pointer to UTF8 name in heap. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::EnumUnresolvedMethods ( // S_OK, S_FALSE, or error. HCORENUM *phEnum, // [IN|OUT] Pointer to the enum. mdToken rMethods[], // [OUT] Put MemberDefs here. ULONG cMax, // [IN] Max MemberDefs to put. ULONG *pcTokens) // [OUT] Put # put here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetUserString ( // S_OK or error. mdString stk, // [IN] String token. _Out_writes_to_opt_(cchString, *pchString) LPWSTR szString, // [OUT] Copy of string. ULONG cchString, // [IN] Max chars of room in szString. ULONG *pchString) // [OUT] How many chars in actual string. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetPinvokeMap ( // S_OK or error. mdToken tk, // [IN] FieldDef or MethodDef. DWORD *pdwMappingFlags, // [OUT] Flags used for mapping. _Out_writes_to_opt_(cchImportName, *pchImportName) LPWSTR szImportName, // [OUT] Import name. ULONG cchImportName, // [IN] Size of the name buffer. ULONG *pchImportName, // [OUT] Actual number of characters stored. mdModuleRef *pmrImportDLL) // [OUT] ModuleRef token for the target DLL. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::EnumSignatures ( // S_OK or error. HCORENUM *phEnum, // [IN|OUT] pointer to the enum. mdSignature rSignatures[], // [OUT] put signatures here. ULONG cmax, // [IN] max signatures to put. ULONG *pcSignatures) // [OUT] put # put here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::EnumTypeSpecs ( // S_OK or error. HCORENUM *phEnum, // [IN|OUT] pointer to the enum. mdTypeSpec rTypeSpecs[], // [OUT] put TypeSpecs here. ULONG cmax, // [IN] max TypeSpecs to put. ULONG *pcTypeSpecs) // [OUT] put # put here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::EnumUserStrings ( // S_OK or error. HCORENUM *phEnum, // [IN/OUT] pointer to the enum. mdString rStrings[], // [OUT] put Strings here. ULONG cmax, // [IN] max Strings to put. ULONG *pcStrings) // [OUT] put # put here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetParamForMethodIndex ( // S_OK or error. mdMethodDef md, // [IN] Method token. ULONG ulParamSeq, // [IN] Parameter sequence. mdParamDef *ppd) // [IN] Put Param token here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::EnumCustomAttributes ( // S_OK or error. HCORENUM *phEnum, // [IN, OUT] COR enumerator. mdToken tk, // [IN] Token to scope the enumeration, 0 for all. mdToken tkType, // [IN] Type of interest, 0 for all. mdCustomAttribute rCustomAttributes[], // [OUT] Put custom attribute tokens here. ULONG cMax, // [IN] Size of rCustomAttributes. ULONG *pcCustomAttributes) // [OUT, OPTIONAL] Put count of token values here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetCustomAttributeProps ( // S_OK or error. mdCustomAttribute cv, // [IN] CustomAttribute token. mdToken *ptkObj, // [OUT, OPTIONAL] Put object token here. mdToken *ptkType, // [OUT, OPTIONAL] Put AttrType token here. void const **ppBlob, // [OUT, OPTIONAL] Put pointer to data here. ULONG *pcbSize) // [OUT, OPTIONAL] Put size of date here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::FindTypeRef ( mdToken tkResolutionScope, // [IN] ModuleRef, AssemblyRef or TypeRef. LPCWSTR szName, // [IN] TypeRef Name. mdTypeRef *ptr) // [OUT] matching TypeRef. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetMemberProps ( mdToken mb, // The member for which to get props. mdTypeDef *pClass, // Put member's class here. _Out_writes_to_opt_(cchMember, *pchMember) LPWSTR szMember, // Put member's name here. ULONG cchMember, // Size of szMember buffer in wide chars. ULONG *pchMember, // Put actual size here DWORD *pdwAttr, // Put flags here. PCCOR_SIGNATURE *ppvSigBlob, // [OUT] point to the blob value of meta data ULONG *pcbSigBlob, // [OUT] actual size of signature blob ULONG *pulCodeRVA, // [OUT] codeRVA DWORD *pdwImplFlags, // [OUT] Impl. Flags DWORD *pdwCPlusTypeFlag, // [OUT] flag for value type. selected ELEMENT_TYPE_* UVCP_CONSTANT *ppValue, // [OUT] constant value ULONG *pcchValue) // [OUT] size of constant string in chars, 0 for non-strings. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetFieldProps ( mdFieldDef mb, // The field for which to get props. mdTypeDef *pClass, // Put field's class here. _Out_writes_to_opt_(cchField, *pchField) LPWSTR szField, // Put field's name here. ULONG cchField, // Size of szField buffer in wide chars. ULONG *pchField, // Put actual size here DWORD *pdwAttr, // Put flags here. PCCOR_SIGNATURE *ppvSigBlob, // [OUT] point to the blob value of meta data ULONG *pcbSigBlob, // [OUT] actual size of signature blob DWORD *pdwCPlusTypeFlag, // [OUT] flag for value type. selected ELEMENT_TYPE_* UVCP_CONSTANT *ppValue, // [OUT] constant value ULONG *pcchValue) // [OUT] size of constant string in chars, 0 for non-strings. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetPropertyProps ( // S_OK, S_FALSE, or error. mdProperty prop, // [IN] property token mdTypeDef *pClass, // [OUT] typedef containing the property declarion. LPCWSTR szProperty, // [OUT] Property name ULONG cchProperty, // [IN] the count of wchar of szProperty ULONG *pchProperty, // [OUT] actual count of wchar for property name DWORD *pdwPropFlags, // [OUT] property flags. PCCOR_SIGNATURE *ppvSig, // [OUT] property type. pointing to meta data internal blob ULONG *pbSig, // [OUT] count of bytes in *ppvSig DWORD *pdwCPlusTypeFlag, // [OUT] flag for value type. selected ELEMENT_TYPE_* UVCP_CONSTANT *ppDefaultValue, // [OUT] constant value ULONG *pcchDefaultValue, // [OUT] size of constant string in chars, 0 for non-strings. mdMethodDef *pmdSetter, // [OUT] setter method of the property mdMethodDef *pmdGetter, // [OUT] getter method of the property mdMethodDef rmdOtherMethod[], // [OUT] other method of the property ULONG cMax, // [IN] size of rmdOtherMethod ULONG *pcOtherMethod) // [OUT] total number of other method of this property { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetParamProps ( // S_OK or error. mdParamDef tk, // [IN]The Parameter. mdMethodDef *pmd, // [OUT] Parent Method token. ULONG *pulSequence, // [OUT] Parameter sequence. _Out_writes_to_opt_(cchName, *pchName) LPWSTR szName, // [OUT] Put name here. ULONG cchName, // [OUT] Size of name buffer. ULONG *pchName, // [OUT] Put actual size of name here. DWORD *pdwAttr, // [OUT] Put flags here. DWORD *pdwCPlusTypeFlag, // [OUT] Flag for value type. selected ELEMENT_TYPE_*. UVCP_CONSTANT *ppValue, // [OUT] Constant value. ULONG *pcchValue) // [OUT] size of constant string in chars, 0 for non-strings. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetCustomAttributeByName ( // S_OK or error. mdToken tkObj, // [IN] Object with Custom Attribute. LPCWSTR szName, // [IN] Name of desired Custom Attribute. const void **ppData, // [OUT] Put pointer to data here. ULONG *pcbData) // [OUT] Put size of data here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP_(BOOL) SymbolInfo::IsValidToken ( // True or False. mdToken tk) // [IN] Given token. { _ASSERTE(!"NYI"); return FALSE; } STDMETHODIMP SymbolInfo::GetNativeCallConvFromSig ( // S_OK or error. void const *pvSig, // [IN] Pointer to signature. ULONG cbSig, // [IN] Count of signature bytes. ULONG *pCallConv) // [OUT] Put calling conv here (see CorPinvokemap). { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::IsGlobal ( // S_OK or error. mdToken pd, // [IN] Type, Field, or Method token. int *pbGlobal) // [OUT] Put 1 if global, 0 otherwise. { _ASSERTE(!"NYI"); return E_NOTIMPL; } // IMetaDataEmit functions STDMETHODIMP SymbolInfo::SetModuleProps ( // S_OK or error. LPCWSTR szName) // [IN] If not NULL, the name of the module to set. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::Save ( // S_OK or error. LPCWSTR szFile, // [IN] The filename to save to. DWORD dwSaveFlags) // [IN] Flags for the save. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::SaveToStream ( // S_OK or error. IStream *pIStream, // [IN] A writable stream to save to. DWORD dwSaveFlags) // [IN] Flags for the save. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetSaveSize ( // S_OK or error. CorSaveSize fSave, // [IN] cssAccurate or cssQuick. DWORD *pdwSaveSize) // [OUT] Put the size here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::DefineTypeDef ( // S_OK or error. LPCWSTR szTypeDef, // [IN] Name of TypeDef DWORD dwTypeDefFlags, // [IN] CustomAttribute flags mdToken tkExtends, // [IN] extends this TypeDef or typeref mdToken rtkImplements[], // [IN] Implements interfaces mdTypeDef *ptd) // [OUT] Put TypeDef token here { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::DefineNestedType ( // S_OK or error. LPCWSTR szTypeDef, // [IN] Name of TypeDef DWORD dwTypeDefFlags, // [IN] CustomAttribute flags mdToken tkExtends, // [IN] extends this TypeDef or typeref mdToken rtkImplements[], // [IN] Implements interfaces mdTypeDef tdEncloser, // [IN] TypeDef token of the enclosing type. mdTypeDef *ptd) // [OUT] Put TypeDef token here { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::SetHandler ( // S_OK. IUnknown *pUnk) // [IN] The new error handler. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::DefineMethod ( // S_OK or error. mdTypeDef td, // Parent TypeDef LPCWSTR szName, // Name of member DWORD dwMethodFlags, // Member attributes PCCOR_SIGNATURE pvSigBlob, // [IN] point to a blob value of CLR signature ULONG cbSigBlob, // [IN] count of bytes in the signature blob ULONG ulCodeRVA, DWORD dwImplFlags, mdMethodDef *pmd) // Put member token here { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::DefineMethodImpl ( // S_OK or error. mdTypeDef td, // [IN] The class implementing the method mdToken tkBody, // [IN] Method body - MethodDef or MethodRef mdToken tkDecl) // [IN] Method declaration - MethodDef or MethodRef { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::DefineTypeRefByName ( // S_OK or error. mdToken tkResolutionScope, // [IN] ModuleRef, AssemblyRef or TypeRef. LPCWSTR szName, // [IN] Name of the TypeRef. mdTypeRef *ptr) // [OUT] Put TypeRef token here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::DefineImportType ( // S_OK or error. IMetaDataAssemblyImport *pAssemImport, // [IN] Assembly containing the TypeDef. const void *pbHashValue, // [IN] Hash Blob for Assembly. ULONG cbHashValue, // [IN] Count of bytes. IMetaDataImport *pImport, // [IN] Scope containing the TypeDef. mdTypeDef tdImport, // [IN] The imported TypeDef. IMetaDataAssemblyEmit *pAssemEmit, // [IN] Assembly into which the TypeDef is imported. mdTypeRef *ptr) // [OUT] Put TypeRef token here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::DefineMemberRef ( // S_OK or error mdToken tkImport, // [IN] ClassRef or ClassDef importing a member. LPCWSTR szName, // [IN] member's name PCCOR_SIGNATURE pvSigBlob, // [IN] point to a blob value of CLR signature ULONG cbSigBlob, // [IN] count of bytes in the signature blob mdMemberRef *pmr) // [OUT] memberref token { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::DefineImportMember ( // S_OK or error. IMetaDataAssemblyImport *pAssemImport, // [IN] Assembly containing the Member. const void *pbHashValue, // [IN] Hash Blob for Assembly. ULONG cbHashValue, // [IN] Count of bytes. IMetaDataImport *pImport, // [IN] Import scope, with member. mdToken mbMember, // [IN] Member in import scope. IMetaDataAssemblyEmit *pAssemEmit, // [IN] Assembly into which the Member is imported. mdToken tkParent, // [IN] Classref or classdef in emit scope. mdMemberRef *pmr) // [OUT] Put member ref here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::DefineEvent( mdTypeDef td, // [IN] the class/interface on which the event is being defined LPCWSTR szEvent, // [IN] Name of the event DWORD dwEventFlags, // [IN] CorEventAttr mdToken tkEventType, // [IN] a reference (mdTypeRef or mdTypeRef) to the Event class mdMethodDef mdAddOn, // [IN] required add method mdMethodDef mdRemoveOn, // [IN] required remove method mdMethodDef mdFire, // [IN] optional fire method mdMethodDef rmdOtherMethods[], // [IN] optional array of other methods associate with the event mdEvent *pmdEvent) // [OUT] output event token { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::SetClassLayout( mdTypeDef td, // [IN] typedef DWORD dwPackSize, // [IN] packing size specified as 1, 2, 4, 8, or 16 COR_FIELD_OFFSET rFieldOffsets[], // [IN] array of layout specification ULONG ulClassSize) // [IN] size of the class { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::DeleteClassLayout( mdTypeDef td) // [IN] typedef whose layout is to be deleted. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::SetFieldMarshal( mdToken tk, // [IN] given a fieldDef or paramDef token PCCOR_SIGNATURE pvNativeType, // [IN] native type specification ULONG cbNativeType) // [IN] count of bytes of pvNativeType { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::DeleteFieldMarshal( mdToken tk) // [IN] given a fieldDef or paramDef token { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::DefinePermissionSet( mdToken tk, // [IN] the object to be decorated. DWORD dwAction, // [IN] CorDeclSecurity. void const *pvPermission, // [IN] permission blob. ULONG cbPermission, // [IN] count of bytes of pvPermission. mdPermission *ppm) // [OUT] returned permission token. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::SetRVA ( // S_OK or error. mdMethodDef md, // [IN] Method for which to set offset ULONG ulRVA) // [IN] The offset { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::DefineModuleRef ( // S_OK or error. LPCWSTR szName, // [IN] DLL name mdModuleRef *pmur) // [OUT] returned { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::SetParent ( // S_OK or error. mdMemberRef mr, // [IN] Token for the ref to be fixed up. mdToken tk) // [IN] The ref parent. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetTokenFromTypeSpec ( // S_OK or error. PCCOR_SIGNATURE pvSig, // [IN] TypeSpec Signature to define. ULONG cbSig, // [IN] Size of signature data. mdTypeSpec *ptypespec) // [OUT] returned TypeSpec token. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::SaveToMemory ( // S_OK or error. void *pbData, // [OUT] Location to write data. ULONG cbData) // [IN] Max size of data buffer. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::DefineUserString ( // Return code. LPCWSTR szString, // [IN] User literal string. ULONG cchString, // [IN] Length of string. mdString *pstk) // [OUT] String token. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::DeleteToken ( // Return code. mdToken tkObj) // [IN] The token to be deleted { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::SetMethodProps ( // S_OK or error. mdMethodDef md, // [IN] The MethodDef. DWORD dwMethodFlags, // [IN] Method attributes. ULONG ulCodeRVA, // [IN] Code RVA. DWORD dwImplFlags) // [IN] Impl flags. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::SetTypeDefProps ( // S_OK or error. mdTypeDef td, // [IN] The TypeDef. DWORD dwTypeDefFlags, // [IN] TypeDef flags. mdToken tkExtends, // [IN] Base TypeDef or TypeRef. mdToken rtkImplements[]) // [IN] Implemented interfaces. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::SetEventProps ( // S_OK or error. mdEvent ev, // [IN] The event token. DWORD dwEventFlags, // [IN] CorEventAttr. mdToken tkEventType, // [IN] A reference (mdTypeRef or mdTypeRef) to the Event class. mdMethodDef mdAddOn, // [IN] Add method. mdMethodDef mdRemoveOn, // [IN] Remove method. mdMethodDef mdFire, // [IN] Fire method. mdMethodDef rmdOtherMethods[])// [IN] Array of other methods associate with the event. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::SetPermissionSetProps ( // S_OK or error. mdToken tk, // [IN] The object to be decorated. DWORD dwAction, // [IN] CorDeclSecurity. void const *pvPermission, // [IN] Permission blob. ULONG cbPermission, // [IN] Count of bytes of pvPermission. mdPermission *ppm) // [OUT] Permission token. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::DefinePinvokeMap ( // Return code. mdToken tk, // [IN] FieldDef or MethodDef. DWORD dwMappingFlags, // [IN] Flags used for mapping. LPCWSTR szImportName, // [IN] Import name. mdModuleRef mrImportDLL) // [IN] ModuleRef token for the target DLL. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::SetPinvokeMap ( // Return code. mdToken tk, // [IN] FieldDef or MethodDef. DWORD dwMappingFlags, // [IN] Flags used for mapping. LPCWSTR szImportName, // [IN] Import name. mdModuleRef mrImportDLL) // [IN] ModuleRef token for the target DLL. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::DeletePinvokeMap ( // Return code. mdToken tk) // [IN] FieldDef or MethodDef. { _ASSERTE(!"NYI"); return E_NOTIMPL; } // New CustomAttribute functions. STDMETHODIMP SymbolInfo::DefineCustomAttribute ( // Return code. mdToken tkObj, // [IN] The object to put the value on. mdToken tkType, // [IN] Type of the CustomAttribute (TypeRef/TypeDef). void const *pCustomAttribute, // [IN] The custom value data. ULONG cbCustomAttribute, // [IN] The custom value data length. mdCustomAttribute *pcv) // [OUT] The custom value token value on return. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::SetCustomAttributeValue ( // Return code. mdCustomAttribute pcv, // [IN] The custom value token whose value to replace. void const *pCustomAttribute, // [IN] The custom value data. ULONG cbCustomAttribute)// [IN] The custom value data length. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::DefineField ( // S_OK or error. mdTypeDef td, // Parent TypeDef LPCWSTR szName, // Name of member DWORD dwFieldFlags, // Member attributes PCCOR_SIGNATURE pvSigBlob, // [IN] point to a blob value of CLR signature ULONG cbSigBlob, // [IN] count of bytes in the signature blob DWORD dwCPlusTypeFlag, // [IN] flag for value type. selected ELEMENT_TYPE_* void const *pValue, // [IN] constant value ULONG cchValue, // [IN] size of constant value (string, in wide chars). mdFieldDef *pmd) // [OUT] Put member token here { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::DefineProperty ( mdTypeDef td, // [IN] the class/interface on which the property is being defined LPCWSTR szProperty, // [IN] Name of the property DWORD dwPropFlags, // [IN] CorPropertyAttr PCCOR_SIGNATURE pvSig, // [IN] the required type signature ULONG cbSig, // [IN] the size of the type signature blob DWORD dwCPlusTypeFlag, // [IN] flag for value type. selected ELEMENT_TYPE_* void const *pValue, // [IN] constant value ULONG cchValue, // [IN] size of constant value (string, in wide chars). mdMethodDef mdSetter, // [IN] optional setter of the property mdMethodDef mdGetter, // [IN] optional getter of the property mdMethodDef rmdOtherMethods[], // [IN] an optional array of other methods mdProperty *pmdProp) // [OUT] output property token { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::DefineParam ( mdMethodDef md, // [IN] Owning method ULONG ulParamSeq, // [IN] Which param LPCWSTR szName, // [IN] Optional param name DWORD dwParamFlags, // [IN] Optional param flags DWORD dwCPlusTypeFlag, // [IN] flag for value type. selected ELEMENT_TYPE_* void const *pValue, // [IN] constant value ULONG cchValue, // [IN] size of constant value (string, in wide chars). mdParamDef *ppd) // [OUT] Put param token here { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::SetFieldProps ( // S_OK or error. mdFieldDef fd, // [IN] The FieldDef. DWORD dwFieldFlags, // [IN] Field attributes. DWORD dwCPlusTypeFlag, // [IN] Flag for the value type, selected ELEMENT_TYPE_* void const *pValue, // [IN] Constant value. ULONG cchValue) // [IN] size of constant value (string, in wide chars). { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::SetPropertyProps ( // S_OK or error. mdProperty pr, // [IN] Property token. DWORD dwPropFlags, // [IN] CorPropertyAttr. DWORD dwCPlusTypeFlag, // [IN] Flag for value type, selected ELEMENT_TYPE_* void const *pValue, // [IN] Constant value. ULONG cchValue, // [IN] size of constant value (string, in wide chars). mdMethodDef mdSetter, // [IN] Setter of the property. mdMethodDef mdGetter, // [IN] Getter of the property. mdMethodDef rmdOtherMethods[])// [IN] Array of other methods. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::SetParamProps ( // Return code. mdParamDef pd, // [IN] Param token. LPCWSTR szName, // [IN] Param name. DWORD dwParamFlags, // [IN] Param flags. DWORD dwCPlusTypeFlag, // [IN] Flag for value type. selected ELEMENT_TYPE_*. void const *pValue, // [OUT] Constant value. ULONG cchValue) // [IN] size of constant value (string, in wide chars). { _ASSERTE(!"NYI"); return E_NOTIMPL; } // Specialized Custom Attributes for security. STDMETHODIMP SymbolInfo::DefineSecurityAttributeSet ( // Return code. mdToken tkObj, // [IN] Class or method requiring security attributes. COR_SECATTR rSecAttrs[], // [IN] Array of security attribute descriptions. ULONG cSecAttrs, // [IN] Count of elements in above array. ULONG *pulErrorAttr) // [OUT] On error, index of attribute causing problem. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::ApplyEditAndContinue ( // S_OK or error. IUnknown *pImport) // [IN] Metadata from the delta PE. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::TranslateSigWithScope ( IMetaDataAssemblyImport *pAssemImport, // [IN] importing assembly interface const void *pbHashValue, // [IN] Hash Blob for Assembly. ULONG cbHashValue, // [IN] Count of bytes. IMetaDataImport *import, // [IN] importing interface PCCOR_SIGNATURE pbSigBlob, // [IN] signature in the importing scope ULONG cbSigBlob, // [IN] count of bytes of signature IMetaDataAssemblyEmit *pAssemEmit, // [IN] emit assembly interface IMetaDataEmit *emit, // [IN] emit interface PCOR_SIGNATURE pvTranslatedSig, // [OUT] buffer to hold translated signature ULONG cbTranslatedSigMax, ULONG *pcbTranslatedSig)// [OUT] count of bytes in the translated signature { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::SetMethodImplFlags ( // [IN] S_OK or error. mdMethodDef md, // [IN] Method for which to set ImplFlags DWORD dwImplFlags) { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::SetFieldRVA ( // [IN] S_OK or error. mdFieldDef fd, // [IN] Field for which to set offset ULONG ulRVA) // [IN] The offset { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::Merge ( // S_OK or error. IMetaDataImport *pImport, // [IN] The scope to be merged. IMapToken *pHostMapToken, // [IN] Host IMapToken interface to receive token remap notification IUnknown *pHandler) // [IN] An object to receive to receive error notification. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::MergeEnd () // S_OK or error. { _ASSERTE(!"NYI"); return E_NOTIMPL; }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // callbacks for diasymreader when using SymConverter #include "stdafx.h" #include "symbolinfo.h" #include "ex.h" SymbolInfo::SymbolInfo() { m_cRef=1; } SymbolInfo::~SymbolInfo() { for (COUNT_T i = 0;i < m_Documents.GetCount();i++) { if (m_Documents.Get(i) != NULL) ((ISymUnmanagedDocumentWriter*)m_Documents.Get(i))->Release(); } } HRESULT SymbolInfo::AddDocument(DWORD id, ISymUnmanagedDocumentWriter* pDocument) { CONTRACTL { NOTHROW; } CONTRACTL_END; HRESULT hr=S_OK; EX_TRY { while(m_Documents.GetCount()<=id) m_Documents.Append(NULL); _ASSERTE(m_Documents.Get(id) == NULL); m_Documents.Set(id,pDocument); pDocument->AddRef(); } EX_CATCH_HRESULT(hr); return hr; } HRESULT SymbolInfo::MapDocument(DWORD id, ISymUnmanagedDocumentWriter** pDocument) { CONTRACTL { NOTHROW; } CONTRACTL_END; HRESULT hr=E_FAIL; if(m_Documents.GetCount()>id) { *pDocument=(ISymUnmanagedDocumentWriter*)m_Documents.Get(id); if (*pDocument == NULL) return E_FAIL; (*pDocument)->AddRef(); hr=S_OK; } return hr; } HRESULT SymbolInfo::SetClassProps(mdToken cls, DWORD flags, LPCWSTR wszName, mdToken parent) { CONTRACTL { NOTHROW; } CONTRACTL_END; HRESULT hr=S_OK; EX_TRY { if(m_Classes.Lookup(cls) == NULL) { NewHolder<ClassProps> classProps (new ClassProps(cls,flags,wszName,parent)); m_Classes.Add(classProps); classProps.SuppressRelease(); } } EX_CATCH_HRESULT(hr); return hr; } HRESULT SymbolInfo::AddSignature(SBuffer& sig, mdSignature token) { CONTRACTL { NOTHROW; } CONTRACTL_END; HRESULT hr=S_OK; EX_TRY { if ( m_Signatures.Lookup(sig) == NULL) { NewHolder<SignatureProps> sigProps (new SignatureProps(sig,token)); m_Signatures.Add(sigProps); sigProps.SuppressRelease(); } } EX_CATCH_HRESULT(hr); return hr; } SymbolInfo::ClassProps* SymbolInfo::FindClass(mdToken cls) { WRAPPER_NO_CONTRACT; return m_Classes.Lookup(cls); } SymbolInfo::SignatureProps* SymbolInfo::FindSignature(SBuffer& sig) { WRAPPER_NO_CONTRACT; return m_Signatures.Lookup(sig); } HRESULT SymbolInfo::AddScope(ULONG32 left, ULONG32 right) { CONTRACTL { NOTHROW; } CONTRACTL_END; HRESULT hr=S_OK; EX_TRY { if (m_Scopes.Lookup(left) == NULL) { NewHolder<ScopeMap> map (new ScopeMap(left,right)); m_Scopes.Add(map); map.SuppressRelease(); } } EX_CATCH_HRESULT(hr); return hr; } HRESULT SymbolInfo::MapScope(ULONG32 left, ULONG32* pRight) { CONTRACTL { NOTHROW; } CONTRACTL_END; ScopeMap* props = m_Scopes.Lookup(left); if(props == NULL) { _ASSERTE(FALSE); return E_FAIL; } *pRight=props->right; return S_OK; } HRESULT SymbolInfo::SetMethodProps(mdToken method, mdToken cls, LPCWSTR wszName) { CONTRACTL { NOTHROW; } CONTRACTL_END; HRESULT hr=S_OK; EX_TRY { m_LastMethod.method=method; m_LastMethod.cls=cls; m_LastMethod.wszName=wszName; m_LastMethod.wszName.Normalize(); } EX_CATCH_HRESULT(hr) return hr; } // IUnknown methods STDMETHODIMP SymbolInfo::QueryInterface (REFIID riid, LPVOID * ppvObj) { CONTRACTL { NOTHROW; } CONTRACTL_END; if(ppvObj==NULL) return E_POINTER; if (riid == IID_IMetaDataEmit) *ppvObj=static_cast<IMetaDataEmit*>(this); else if (riid == IID_IMetaDataImport) *ppvObj=static_cast<IMetaDataImport*>(this); else if (riid == IID_IUnknown) *ppvObj=static_cast<IMetaDataImport*>(this); else return E_NOTIMPL; AddRef(); return S_OK; } STDMETHODIMP_(ULONG) SymbolInfo::AddRef () { LIMITED_METHOD_CONTRACT; return InterlockedIncrement(&m_cRef); } STDMETHODIMP_(ULONG) SymbolInfo::Release () { LIMITED_METHOD_CONTRACT; ULONG retval=InterlockedDecrement(&m_cRef); if(retval==0) delete this; return retval; } STDMETHODIMP SymbolInfo::GetTypeDefProps ( // S_OK or error. mdTypeDef td, // [IN] TypeDef token for inquiry. _Out_writes_to_opt_(cchTypeDef, pchTypeDef) LPWSTR szTypeDef, // [OUT] Put name here. ULONG cchTypeDef, // [IN] size of name buffer in wide chars. ULONG *pchTypeDef, // [OUT] put size of name (wide chars) here. DWORD *pdwTypeDefFlags, // [OUT] Put flags here. mdToken *ptkExtends) // [OUT] Put base class TypeDef/TypeRef here. { CONTRACTL { NOTHROW; PRECONDITION(ptkExtends==NULL); PRECONDITION(CheckPointer(szTypeDef)); } CONTRACTL_END; if (szTypeDef == NULL) return E_POINTER; ClassProps* classInfo=FindClass(td); _ASSERTE(classInfo); if(classInfo == NULL) return E_UNEXPECTED; if(pdwTypeDefFlags) *pdwTypeDefFlags=classInfo->flags; SIZE_T cch=wcslen(classInfo->wszName)+1; if (cch > UINT32_MAX) return E_UNEXPECTED; *pchTypeDef=(ULONG)cch; if (cchTypeDef < cch) return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); wcscpy_s(szTypeDef,cchTypeDef,classInfo->wszName); if(pdwTypeDefFlags) *pdwTypeDefFlags=classInfo->flags; return S_OK; } STDMETHODIMP SymbolInfo::GetMethodProps ( mdMethodDef mb, // The method for which to get props. mdTypeDef *pClass, // Put method's class here. _Out_writes_to_opt_(cchMethod, *pchMethod) LPWSTR szMethod, // Put method's name here. ULONG cchMethod, // Size of szMethod buffer in wide chars. ULONG *pchMethod, // Put actual size here DWORD *pdwAttr, // Put flags here. PCCOR_SIGNATURE *ppvSigBlob, // [OUT] point to the blob value of meta data ULONG *pcbSigBlob, // [OUT] actual size of signature blob ULONG *pulCodeRVA, // [OUT] codeRVA DWORD *pdwImplFlags) // [OUT] Impl. Flags { CONTRACTL { NOTHROW; PRECONDITION(m_LastMethod.method==mb); PRECONDITION(pClass!=NULL); PRECONDITION(pchMethod!=NULL); PRECONDITION(pdwAttr == NULL); PRECONDITION(ppvSigBlob == NULL); PRECONDITION(pcbSigBlob == NULL); PRECONDITION(pulCodeRVA == NULL); PRECONDITION(pdwImplFlags == NULL); PRECONDITION(CheckPointer(szMethod)); } CONTRACTL_END; if (szMethod == NULL) return E_POINTER; *pClass=m_LastMethod.cls; SIZE_T cch=wcslen(m_LastMethod.wszName)+1; if(cch > UINT32_MAX) return E_UNEXPECTED; *pchMethod=(ULONG)cch; if (cchMethod < cch) return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); wcscpy_s(szMethod,cchMethod,m_LastMethod.wszName); return S_OK; } STDMETHODIMP SymbolInfo::GetNestedClassProps ( // S_OK or error. mdTypeDef tdNestedClass, // [IN] NestedClass token. mdTypeDef *ptdEnclosingClass) // [OUT] EnclosingClass token. { CONTRACTL { NOTHROW; PRECONDITION(CheckPointer(ptdEnclosingClass)); } CONTRACTL_END; if(ptdEnclosingClass == NULL) return E_POINTER; ClassProps* classInfo=FindClass(tdNestedClass); _ASSERTE(classInfo); if(classInfo == NULL) return E_UNEXPECTED; *ptdEnclosingClass=classInfo->tkEnclosing; return S_OK; } STDMETHODIMP SymbolInfo::GetTokenFromSig ( // S_OK or error. PCCOR_SIGNATURE pvSig, // [IN] Signature to define. ULONG cbSig, // [IN] Size of signature data. mdSignature *pmsig) // [OUT] returned signature token. { SBuffer sig; sig.SetImmutable(pvSig,cbSig); SignatureProps* sigProps=FindSignature(sig); _ASSERTE(sigProps); if(sigProps == NULL) return E_UNEXPECTED; *pmsig=sigProps->tkSig; return S_OK; } ////////////////////////////////////////////// // All the functions below are just stubs STDMETHODIMP_(void) SymbolInfo::CloseEnum (HCORENUM hEnum) { _ASSERTE(!"NYI"); } STDMETHODIMP SymbolInfo::CountEnum (HCORENUM hEnum, ULONG *pulCount) { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::ResetEnum (HCORENUM hEnum, ULONG ulPos) { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::EnumTypeDefs (HCORENUM *phEnum, mdTypeDef rTypeDefs[], ULONG cMax, ULONG *pcTypeDefs) { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::EnumInterfaceImpls (HCORENUM *phEnum, mdTypeDef td, mdInterfaceImpl rImpls[], ULONG cMax, ULONG* pcImpls) { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::EnumTypeRefs (HCORENUM *phEnum, mdTypeRef rTypeRefs[], ULONG cMax, ULONG* pcTypeRefs) { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::FindTypeDefByName ( // S_OK or error. LPCWSTR szTypeDef, // [IN] Name of the Type. mdToken tkEnclosingClass, // [IN] TypeDef/TypeRef for Enclosing class. mdTypeDef *ptd) // [OUT] Put the TypeDef token here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetScopeProps ( // S_OK or error. _Out_writes_to_opt_(cchName, *pchName) LPWSTR szName, // [OUT] Put the name here. ULONG cchName, // [IN] Size of name buffer in wide chars. ULONG *pchName, // [OUT] Put size of name (wide chars) here. GUID *pmvid) // [OUT, OPTIONAL] Put MVID here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetModuleFromScope ( // S_OK. mdModule *pmd) // [OUT] Put mdModule token here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetInterfaceImplProps ( // S_OK or error. mdInterfaceImpl iiImpl, // [IN] InterfaceImpl token. mdTypeDef *pClass, // [OUT] Put implementing class token here. mdToken *ptkIface) // [OUT] Put implemented interface token here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetTypeRefProps ( // S_OK or error. mdTypeRef tr, // [IN] TypeRef token. mdToken *ptkResolutionScope, // [OUT] Resolution scope, ModuleRef or AssemblyRef. _Out_writes_to_opt_(cchName, *pchName) LPWSTR szName, // [OUT] Name of the TypeRef. ULONG cchName, // [IN] Size of buffer. ULONG *pchName) // [OUT] Size of Name. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::ResolveTypeRef (mdTypeRef tr, REFIID riid, IUnknown **ppIScope, mdTypeDef *ptd) { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::EnumMembers ( // S_OK, S_FALSE, or error. HCORENUM *phEnum, // [IN|OUT] Pointer to the enum. mdTypeDef cl, // [IN] TypeDef to scope the enumeration. mdToken rMembers[], // [OUT] Put MemberDefs here. ULONG cMax, // [IN] Max MemberDefs to put. ULONG *pcTokens) // [OUT] Put # put here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::EnumMembersWithName ( // S_OK, S_FALSE, or error. HCORENUM *phEnum, // [IN|OUT] Pointer to the enum. mdTypeDef cl, // [IN] TypeDef to scope the enumeration. LPCWSTR szName, // [IN] Limit results to those with this name. mdToken rMembers[], // [OUT] Put MemberDefs here. ULONG cMax, // [IN] Max MemberDefs to put. ULONG *pcTokens) // [OUT] Put # put here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::EnumMethods ( // S_OK, S_FALSE, or error. HCORENUM *phEnum, // [IN|OUT] Pointer to the enum. mdTypeDef cl, // [IN] TypeDef to scope the enumeration. mdMethodDef rMethods[], // [OUT] Put MethodDefs here. ULONG cMax, // [IN] Max MethodDefs to put. ULONG *pcTokens) // [OUT] Put # put here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::EnumMethodsWithName ( // S_OK, S_FALSE, or error. HCORENUM *phEnum, // [IN|OUT] Pointer to the enum. mdTypeDef cl, // [IN] TypeDef to scope the enumeration. LPCWSTR szName, // [IN] Limit results to those with this name. mdMethodDef rMethods[], // [OU] Put MethodDefs here. ULONG cMax, // [IN] Max MethodDefs to put. ULONG *pcTokens) // [OUT] Put # put here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::EnumFields ( // S_OK, S_FALSE, or error. HCORENUM *phEnum, // [IN|OUT] Pointer to the enum. mdTypeDef cl, // [IN] TypeDef to scope the enumeration. mdFieldDef rFields[], // [OUT] Put FieldDefs here. ULONG cMax, // [IN] Max FieldDefs to put. ULONG *pcTokens) // [OUT] Put # put here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::EnumFieldsWithName ( // S_OK, S_FALSE, or error. HCORENUM *phEnum, // [IN|OUT] Pointer to the enum. mdTypeDef cl, // [IN] TypeDef to scope the enumeration. LPCWSTR szName, // [IN] Limit results to those with this name. mdFieldDef rFields[], // [OUT] Put MemberDefs here. ULONG cMax, // [IN] Max MemberDefs to put. ULONG *pcTokens) // [OUT] Put # put here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::EnumParams ( // S_OK, S_FALSE, or error. HCORENUM *phEnum, // [IN|OUT] Pointer to the enum. mdMethodDef mb, // [IN] MethodDef to scope the enumeration. mdParamDef rParams[], // [OUT] Put ParamDefs here. ULONG cMax, // [IN] Max ParamDefs to put. ULONG *pcTokens) // [OUT] Put # put here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::EnumMemberRefs ( // S_OK, S_FALSE, or error. HCORENUM *phEnum, // [IN|OUT] Pointer to the enum. mdToken tkParent, // [IN] Parent token to scope the enumeration. mdMemberRef rMemberRefs[], // [OUT] Put MemberRefs here. ULONG cMax, // [IN] Max MemberRefs to put. ULONG *pcTokens) // [OUT] Put # put here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::EnumMethodImpls ( // S_OK, S_FALSE, or error HCORENUM *phEnum, // [IN|OUT] Pointer to the enum. mdTypeDef td, // [IN] TypeDef to scope the enumeration. mdToken rMethodBody[], // [OUT] Put Method Body tokens here. mdToken rMethodDecl[], // [OUT] Put Method Declaration tokens here. ULONG cMax, // [IN] Max tokens to put. ULONG *pcTokens) // [OUT] Put # put here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::EnumPermissionSets ( // S_OK, S_FALSE, or error. HCORENUM *phEnum, // [IN|OUT] Pointer to the enum. mdToken tk, // [IN] if !NIL, token to scope the enumeration. DWORD dwActions, // [IN] if !0, return only these actions. mdPermission rPermission[], // [OUT] Put Permissions here. ULONG cMax, // [IN] Max Permissions to put. ULONG *pcTokens) // [OUT] Put # put here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::FindMember ( mdTypeDef td, // [IN] given typedef LPCWSTR szName, // [IN] member name PCCOR_SIGNATURE pvSigBlob, // [IN] point to a blob value of CLR signature ULONG cbSigBlob, // [IN] count of bytes in the signature blob mdToken *pmb) // [OUT] matching memberdef { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::FindMethod ( mdTypeDef td, // [IN] given typedef LPCWSTR szName, // [IN] member name PCCOR_SIGNATURE pvSigBlob, // [IN] point to a blob value of CLR signature ULONG cbSigBlob, // [IN] count of bytes in the signature blob mdMethodDef *pmb) // [OUT] matching memberdef { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::FindField ( mdTypeDef td, // [IN] given typedef LPCWSTR szName, // [IN] member name PCCOR_SIGNATURE pvSigBlob, // [IN] point to a blob value of CLR signature ULONG cbSigBlob, // [IN] count of bytes in the signature blob mdFieldDef *pmb) // [OUT] matching memberdef { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::FindMemberRef ( mdTypeRef td, // [IN] given typeRef LPCWSTR szName, // [IN] member name PCCOR_SIGNATURE pvSigBlob, // [IN] point to a blob value of CLR signature ULONG cbSigBlob, // [IN] count of bytes in the signature blob mdMemberRef *pmr) // [OUT] matching memberref { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetMemberRefProps ( // S_OK or error. mdMemberRef mr, // [IN] given memberref mdToken *ptk, // [OUT] Put classref or classdef here. _Out_writes_to_opt_(cchMember, *pchMember) LPWSTR szMember, // [OUT] buffer to fill for member's name ULONG cchMember, // [IN] the count of char of szMember ULONG *pchMember, // [OUT] actual count of char in member name PCCOR_SIGNATURE *ppvSigBlob, // [OUT] point to meta data blob value ULONG *pbSig) // [OUT] actual size of signature blob { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::EnumProperties ( // S_OK, S_FALSE, or error. HCORENUM *phEnum, // [IN|OUT] Pointer to the enum. mdTypeDef td, // [IN] TypeDef to scope the enumeration. mdProperty rProperties[], // [OUT] Put Properties here. ULONG cMax, // [IN] Max properties to put. ULONG *pcProperties) // [OUT] Put # put here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::EnumEvents ( // S_OK, S_FALSE, or error. HCORENUM *phEnum, // [IN|OUT] Pointer to the enum. mdTypeDef td, // [IN] TypeDef to scope the enumeration. mdEvent rEvents[], // [OUT] Put events here. ULONG cMax, // [IN] Max events to put. ULONG *pcEvents) // [OUT] Put # put here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetEventProps ( // S_OK, S_FALSE, or error. mdEvent ev, // [IN] event token mdTypeDef *pClass, // [OUT] typedef containing the event declarion. LPCWSTR szEvent, // [OUT] Event name ULONG cchEvent, // [IN] the count of wchar of szEvent ULONG *pchEvent, // [OUT] actual count of wchar for event's name DWORD *pdwEventFlags, // [OUT] Event flags. mdToken *ptkEventType, // [OUT] EventType class mdMethodDef *pmdAddOn, // [OUT] AddOn method of the event mdMethodDef *pmdRemoveOn, // [OUT] RemoveOn method of the event mdMethodDef *pmdFire, // [OUT] Fire method of the event mdMethodDef rmdOtherMethod[], // [OUT] other method of the event ULONG cMax, // [IN] size of rmdOtherMethod ULONG *pcOtherMethod) // [OUT] total number of other method of this event { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::EnumMethodSemantics ( // S_OK, S_FALSE, or error. HCORENUM *phEnum, // [IN|OUT] Pointer to the enum. mdMethodDef mb, // [IN] MethodDef to scope the enumeration. mdToken rEventProp[], // [OUT] Put Event/Property here. ULONG cMax, // [IN] Max properties to put. ULONG *pcEventProp) // [OUT] Put # put here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetMethodSemantics ( // S_OK, S_FALSE, or error. mdMethodDef mb, // [IN] method token mdToken tkEventProp, // [IN] event/property token. DWORD *pdwSemanticsFlags) // [OUT] the role flags for the method/propevent pair { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetClassLayout ( mdTypeDef td, // [IN] give typedef DWORD *pdwPackSize, // [OUT] 1, 2, 4, 8, or 16 COR_FIELD_OFFSET rFieldOffset[], // [OUT] field offset array ULONG cMax, // [IN] size of the array ULONG *pcFieldOffset, // [OUT] needed array size ULONG *pulClassSize) // [OUT] the size of the class { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetFieldMarshal ( mdToken tk, // [IN] given a field's memberdef PCCOR_SIGNATURE *ppvNativeType, // [OUT] native type of this field ULONG *pcbNativeType) // [OUT] the count of bytes of *ppvNativeType { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetRVA ( // S_OK or error. mdToken tk, // Member for which to set offset ULONG *pulCodeRVA, // The offset DWORD *pdwImplFlags) // the implementation flags { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetPermissionSetProps ( mdPermission pm, // [IN] the permission token. DWORD *pdwAction, // [OUT] CorDeclSecurity. void const **ppvPermission, // [OUT] permission blob. ULONG *pcbPermission) // [OUT] count of bytes of pvPermission. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetSigFromToken ( // S_OK or error. mdSignature mdSig, // [IN] Signature token. PCCOR_SIGNATURE *ppvSig, // [OUT] return pointer to token. ULONG *pcbSig) // [OUT] return size of signature. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetModuleRefProps ( // S_OK or error. mdModuleRef mur, // [IN] moduleref token. _Out_writes_to_opt_(cchName, *pchName) LPWSTR szName, // [OUT] buffer to fill with the moduleref name. ULONG cchName, // [IN] size of szName in wide characters. ULONG *pchName) // [OUT] actual count of characters in the name. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::EnumModuleRefs ( // S_OK or error. HCORENUM *phEnum, // [IN|OUT] pointer to the enum. mdModuleRef rModuleRefs[], // [OUT] put modulerefs here. ULONG cmax, // [IN] max memberrefs to put. ULONG *pcModuleRefs) // [OUT] put # put here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetTypeSpecFromToken ( // S_OK or error. mdTypeSpec typespec, // [IN] TypeSpec token. PCCOR_SIGNATURE *ppvSig, // [OUT] return pointer to TypeSpec signature ULONG *pcbSig) // [OUT] return size of signature. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetNameFromToken ( // Not Recommended! May be removed! mdToken tk, // [IN] Token to get name from. Must have a name. MDUTF8CSTR *pszUtf8NamePtr) // [OUT] Return pointer to UTF8 name in heap. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::EnumUnresolvedMethods ( // S_OK, S_FALSE, or error. HCORENUM *phEnum, // [IN|OUT] Pointer to the enum. mdToken rMethods[], // [OUT] Put MemberDefs here. ULONG cMax, // [IN] Max MemberDefs to put. ULONG *pcTokens) // [OUT] Put # put here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetUserString ( // S_OK or error. mdString stk, // [IN] String token. _Out_writes_to_opt_(cchString, *pchString) LPWSTR szString, // [OUT] Copy of string. ULONG cchString, // [IN] Max chars of room in szString. ULONG *pchString) // [OUT] How many chars in actual string. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetPinvokeMap ( // S_OK or error. mdToken tk, // [IN] FieldDef or MethodDef. DWORD *pdwMappingFlags, // [OUT] Flags used for mapping. _Out_writes_to_opt_(cchImportName, *pchImportName) LPWSTR szImportName, // [OUT] Import name. ULONG cchImportName, // [IN] Size of the name buffer. ULONG *pchImportName, // [OUT] Actual number of characters stored. mdModuleRef *pmrImportDLL) // [OUT] ModuleRef token for the target DLL. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::EnumSignatures ( // S_OK or error. HCORENUM *phEnum, // [IN|OUT] pointer to the enum. mdSignature rSignatures[], // [OUT] put signatures here. ULONG cmax, // [IN] max signatures to put. ULONG *pcSignatures) // [OUT] put # put here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::EnumTypeSpecs ( // S_OK or error. HCORENUM *phEnum, // [IN|OUT] pointer to the enum. mdTypeSpec rTypeSpecs[], // [OUT] put TypeSpecs here. ULONG cmax, // [IN] max TypeSpecs to put. ULONG *pcTypeSpecs) // [OUT] put # put here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::EnumUserStrings ( // S_OK or error. HCORENUM *phEnum, // [IN/OUT] pointer to the enum. mdString rStrings[], // [OUT] put Strings here. ULONG cmax, // [IN] max Strings to put. ULONG *pcStrings) // [OUT] put # put here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetParamForMethodIndex ( // S_OK or error. mdMethodDef md, // [IN] Method token. ULONG ulParamSeq, // [IN] Parameter sequence. mdParamDef *ppd) // [IN] Put Param token here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::EnumCustomAttributes ( // S_OK or error. HCORENUM *phEnum, // [IN, OUT] COR enumerator. mdToken tk, // [IN] Token to scope the enumeration, 0 for all. mdToken tkType, // [IN] Type of interest, 0 for all. mdCustomAttribute rCustomAttributes[], // [OUT] Put custom attribute tokens here. ULONG cMax, // [IN] Size of rCustomAttributes. ULONG *pcCustomAttributes) // [OUT, OPTIONAL] Put count of token values here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetCustomAttributeProps ( // S_OK or error. mdCustomAttribute cv, // [IN] CustomAttribute token. mdToken *ptkObj, // [OUT, OPTIONAL] Put object token here. mdToken *ptkType, // [OUT, OPTIONAL] Put AttrType token here. void const **ppBlob, // [OUT, OPTIONAL] Put pointer to data here. ULONG *pcbSize) // [OUT, OPTIONAL] Put size of date here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::FindTypeRef ( mdToken tkResolutionScope, // [IN] ModuleRef, AssemblyRef or TypeRef. LPCWSTR szName, // [IN] TypeRef Name. mdTypeRef *ptr) // [OUT] matching TypeRef. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetMemberProps ( mdToken mb, // The member for which to get props. mdTypeDef *pClass, // Put member's class here. _Out_writes_to_opt_(cchMember, *pchMember) LPWSTR szMember, // Put member's name here. ULONG cchMember, // Size of szMember buffer in wide chars. ULONG *pchMember, // Put actual size here DWORD *pdwAttr, // Put flags here. PCCOR_SIGNATURE *ppvSigBlob, // [OUT] point to the blob value of meta data ULONG *pcbSigBlob, // [OUT] actual size of signature blob ULONG *pulCodeRVA, // [OUT] codeRVA DWORD *pdwImplFlags, // [OUT] Impl. Flags DWORD *pdwCPlusTypeFlag, // [OUT] flag for value type. selected ELEMENT_TYPE_* UVCP_CONSTANT *ppValue, // [OUT] constant value ULONG *pcchValue) // [OUT] size of constant string in chars, 0 for non-strings. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetFieldProps ( mdFieldDef mb, // The field for which to get props. mdTypeDef *pClass, // Put field's class here. _Out_writes_to_opt_(cchField, *pchField) LPWSTR szField, // Put field's name here. ULONG cchField, // Size of szField buffer in wide chars. ULONG *pchField, // Put actual size here DWORD *pdwAttr, // Put flags here. PCCOR_SIGNATURE *ppvSigBlob, // [OUT] point to the blob value of meta data ULONG *pcbSigBlob, // [OUT] actual size of signature blob DWORD *pdwCPlusTypeFlag, // [OUT] flag for value type. selected ELEMENT_TYPE_* UVCP_CONSTANT *ppValue, // [OUT] constant value ULONG *pcchValue) // [OUT] size of constant string in chars, 0 for non-strings. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetPropertyProps ( // S_OK, S_FALSE, or error. mdProperty prop, // [IN] property token mdTypeDef *pClass, // [OUT] typedef containing the property declarion. LPCWSTR szProperty, // [OUT] Property name ULONG cchProperty, // [IN] the count of wchar of szProperty ULONG *pchProperty, // [OUT] actual count of wchar for property name DWORD *pdwPropFlags, // [OUT] property flags. PCCOR_SIGNATURE *ppvSig, // [OUT] property type. pointing to meta data internal blob ULONG *pbSig, // [OUT] count of bytes in *ppvSig DWORD *pdwCPlusTypeFlag, // [OUT] flag for value type. selected ELEMENT_TYPE_* UVCP_CONSTANT *ppDefaultValue, // [OUT] constant value ULONG *pcchDefaultValue, // [OUT] size of constant string in chars, 0 for non-strings. mdMethodDef *pmdSetter, // [OUT] setter method of the property mdMethodDef *pmdGetter, // [OUT] getter method of the property mdMethodDef rmdOtherMethod[], // [OUT] other method of the property ULONG cMax, // [IN] size of rmdOtherMethod ULONG *pcOtherMethod) // [OUT] total number of other method of this property { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetParamProps ( // S_OK or error. mdParamDef tk, // [IN]The Parameter. mdMethodDef *pmd, // [OUT] Parent Method token. ULONG *pulSequence, // [OUT] Parameter sequence. _Out_writes_to_opt_(cchName, *pchName) LPWSTR szName, // [OUT] Put name here. ULONG cchName, // [OUT] Size of name buffer. ULONG *pchName, // [OUT] Put actual size of name here. DWORD *pdwAttr, // [OUT] Put flags here. DWORD *pdwCPlusTypeFlag, // [OUT] Flag for value type. selected ELEMENT_TYPE_*. UVCP_CONSTANT *ppValue, // [OUT] Constant value. ULONG *pcchValue) // [OUT] size of constant string in chars, 0 for non-strings. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetCustomAttributeByName ( // S_OK or error. mdToken tkObj, // [IN] Object with Custom Attribute. LPCWSTR szName, // [IN] Name of desired Custom Attribute. const void **ppData, // [OUT] Put pointer to data here. ULONG *pcbData) // [OUT] Put size of data here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP_(BOOL) SymbolInfo::IsValidToken ( // True or False. mdToken tk) // [IN] Given token. { _ASSERTE(!"NYI"); return FALSE; } STDMETHODIMP SymbolInfo::GetNativeCallConvFromSig ( // S_OK or error. void const *pvSig, // [IN] Pointer to signature. ULONG cbSig, // [IN] Count of signature bytes. ULONG *pCallConv) // [OUT] Put calling conv here (see CorPinvokemap). { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::IsGlobal ( // S_OK or error. mdToken pd, // [IN] Type, Field, or Method token. int *pbGlobal) // [OUT] Put 1 if global, 0 otherwise. { _ASSERTE(!"NYI"); return E_NOTIMPL; } // IMetaDataEmit functions STDMETHODIMP SymbolInfo::SetModuleProps ( // S_OK or error. LPCWSTR szName) // [IN] If not NULL, the name of the module to set. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::Save ( // S_OK or error. LPCWSTR szFile, // [IN] The filename to save to. DWORD dwSaveFlags) // [IN] Flags for the save. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::SaveToStream ( // S_OK or error. IStream *pIStream, // [IN] A writable stream to save to. DWORD dwSaveFlags) // [IN] Flags for the save. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetSaveSize ( // S_OK or error. CorSaveSize fSave, // [IN] cssAccurate or cssQuick. DWORD *pdwSaveSize) // [OUT] Put the size here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::DefineTypeDef ( // S_OK or error. LPCWSTR szTypeDef, // [IN] Name of TypeDef DWORD dwTypeDefFlags, // [IN] CustomAttribute flags mdToken tkExtends, // [IN] extends this TypeDef or typeref mdToken rtkImplements[], // [IN] Implements interfaces mdTypeDef *ptd) // [OUT] Put TypeDef token here { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::DefineNestedType ( // S_OK or error. LPCWSTR szTypeDef, // [IN] Name of TypeDef DWORD dwTypeDefFlags, // [IN] CustomAttribute flags mdToken tkExtends, // [IN] extends this TypeDef or typeref mdToken rtkImplements[], // [IN] Implements interfaces mdTypeDef tdEncloser, // [IN] TypeDef token of the enclosing type. mdTypeDef *ptd) // [OUT] Put TypeDef token here { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::SetHandler ( // S_OK. IUnknown *pUnk) // [IN] The new error handler. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::DefineMethod ( // S_OK or error. mdTypeDef td, // Parent TypeDef LPCWSTR szName, // Name of member DWORD dwMethodFlags, // Member attributes PCCOR_SIGNATURE pvSigBlob, // [IN] point to a blob value of CLR signature ULONG cbSigBlob, // [IN] count of bytes in the signature blob ULONG ulCodeRVA, DWORD dwImplFlags, mdMethodDef *pmd) // Put member token here { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::DefineMethodImpl ( // S_OK or error. mdTypeDef td, // [IN] The class implementing the method mdToken tkBody, // [IN] Method body - MethodDef or MethodRef mdToken tkDecl) // [IN] Method declaration - MethodDef or MethodRef { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::DefineTypeRefByName ( // S_OK or error. mdToken tkResolutionScope, // [IN] ModuleRef, AssemblyRef or TypeRef. LPCWSTR szName, // [IN] Name of the TypeRef. mdTypeRef *ptr) // [OUT] Put TypeRef token here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::DefineImportType ( // S_OK or error. IMetaDataAssemblyImport *pAssemImport, // [IN] Assembly containing the TypeDef. const void *pbHashValue, // [IN] Hash Blob for Assembly. ULONG cbHashValue, // [IN] Count of bytes. IMetaDataImport *pImport, // [IN] Scope containing the TypeDef. mdTypeDef tdImport, // [IN] The imported TypeDef. IMetaDataAssemblyEmit *pAssemEmit, // [IN] Assembly into which the TypeDef is imported. mdTypeRef *ptr) // [OUT] Put TypeRef token here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::DefineMemberRef ( // S_OK or error mdToken tkImport, // [IN] ClassRef or ClassDef importing a member. LPCWSTR szName, // [IN] member's name PCCOR_SIGNATURE pvSigBlob, // [IN] point to a blob value of CLR signature ULONG cbSigBlob, // [IN] count of bytes in the signature blob mdMemberRef *pmr) // [OUT] memberref token { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::DefineImportMember ( // S_OK or error. IMetaDataAssemblyImport *pAssemImport, // [IN] Assembly containing the Member. const void *pbHashValue, // [IN] Hash Blob for Assembly. ULONG cbHashValue, // [IN] Count of bytes. IMetaDataImport *pImport, // [IN] Import scope, with member. mdToken mbMember, // [IN] Member in import scope. IMetaDataAssemblyEmit *pAssemEmit, // [IN] Assembly into which the Member is imported. mdToken tkParent, // [IN] Classref or classdef in emit scope. mdMemberRef *pmr) // [OUT] Put member ref here. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::DefineEvent( mdTypeDef td, // [IN] the class/interface on which the event is being defined LPCWSTR szEvent, // [IN] Name of the event DWORD dwEventFlags, // [IN] CorEventAttr mdToken tkEventType, // [IN] a reference (mdTypeRef or mdTypeRef) to the Event class mdMethodDef mdAddOn, // [IN] required add method mdMethodDef mdRemoveOn, // [IN] required remove method mdMethodDef mdFire, // [IN] optional fire method mdMethodDef rmdOtherMethods[], // [IN] optional array of other methods associate with the event mdEvent *pmdEvent) // [OUT] output event token { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::SetClassLayout( mdTypeDef td, // [IN] typedef DWORD dwPackSize, // [IN] packing size specified as 1, 2, 4, 8, or 16 COR_FIELD_OFFSET rFieldOffsets[], // [IN] array of layout specification ULONG ulClassSize) // [IN] size of the class { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::DeleteClassLayout( mdTypeDef td) // [IN] typedef whose layout is to be deleted. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::SetFieldMarshal( mdToken tk, // [IN] given a fieldDef or paramDef token PCCOR_SIGNATURE pvNativeType, // [IN] native type specification ULONG cbNativeType) // [IN] count of bytes of pvNativeType { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::DeleteFieldMarshal( mdToken tk) // [IN] given a fieldDef or paramDef token { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::DefinePermissionSet( mdToken tk, // [IN] the object to be decorated. DWORD dwAction, // [IN] CorDeclSecurity. void const *pvPermission, // [IN] permission blob. ULONG cbPermission, // [IN] count of bytes of pvPermission. mdPermission *ppm) // [OUT] returned permission token. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::SetRVA ( // S_OK or error. mdMethodDef md, // [IN] Method for which to set offset ULONG ulRVA) // [IN] The offset { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::DefineModuleRef ( // S_OK or error. LPCWSTR szName, // [IN] DLL name mdModuleRef *pmur) // [OUT] returned { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::SetParent ( // S_OK or error. mdMemberRef mr, // [IN] Token for the ref to be fixed up. mdToken tk) // [IN] The ref parent. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::GetTokenFromTypeSpec ( // S_OK or error. PCCOR_SIGNATURE pvSig, // [IN] TypeSpec Signature to define. ULONG cbSig, // [IN] Size of signature data. mdTypeSpec *ptypespec) // [OUT] returned TypeSpec token. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::SaveToMemory ( // S_OK or error. void *pbData, // [OUT] Location to write data. ULONG cbData) // [IN] Max size of data buffer. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::DefineUserString ( // Return code. LPCWSTR szString, // [IN] User literal string. ULONG cchString, // [IN] Length of string. mdString *pstk) // [OUT] String token. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::DeleteToken ( // Return code. mdToken tkObj) // [IN] The token to be deleted { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::SetMethodProps ( // S_OK or error. mdMethodDef md, // [IN] The MethodDef. DWORD dwMethodFlags, // [IN] Method attributes. ULONG ulCodeRVA, // [IN] Code RVA. DWORD dwImplFlags) // [IN] Impl flags. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::SetTypeDefProps ( // S_OK or error. mdTypeDef td, // [IN] The TypeDef. DWORD dwTypeDefFlags, // [IN] TypeDef flags. mdToken tkExtends, // [IN] Base TypeDef or TypeRef. mdToken rtkImplements[]) // [IN] Implemented interfaces. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::SetEventProps ( // S_OK or error. mdEvent ev, // [IN] The event token. DWORD dwEventFlags, // [IN] CorEventAttr. mdToken tkEventType, // [IN] A reference (mdTypeRef or mdTypeRef) to the Event class. mdMethodDef mdAddOn, // [IN] Add method. mdMethodDef mdRemoveOn, // [IN] Remove method. mdMethodDef mdFire, // [IN] Fire method. mdMethodDef rmdOtherMethods[])// [IN] Array of other methods associate with the event. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::SetPermissionSetProps ( // S_OK or error. mdToken tk, // [IN] The object to be decorated. DWORD dwAction, // [IN] CorDeclSecurity. void const *pvPermission, // [IN] Permission blob. ULONG cbPermission, // [IN] Count of bytes of pvPermission. mdPermission *ppm) // [OUT] Permission token. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::DefinePinvokeMap ( // Return code. mdToken tk, // [IN] FieldDef or MethodDef. DWORD dwMappingFlags, // [IN] Flags used for mapping. LPCWSTR szImportName, // [IN] Import name. mdModuleRef mrImportDLL) // [IN] ModuleRef token for the target DLL. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::SetPinvokeMap ( // Return code. mdToken tk, // [IN] FieldDef or MethodDef. DWORD dwMappingFlags, // [IN] Flags used for mapping. LPCWSTR szImportName, // [IN] Import name. mdModuleRef mrImportDLL) // [IN] ModuleRef token for the target DLL. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::DeletePinvokeMap ( // Return code. mdToken tk) // [IN] FieldDef or MethodDef. { _ASSERTE(!"NYI"); return E_NOTIMPL; } // New CustomAttribute functions. STDMETHODIMP SymbolInfo::DefineCustomAttribute ( // Return code. mdToken tkObj, // [IN] The object to put the value on. mdToken tkType, // [IN] Type of the CustomAttribute (TypeRef/TypeDef). void const *pCustomAttribute, // [IN] The custom value data. ULONG cbCustomAttribute, // [IN] The custom value data length. mdCustomAttribute *pcv) // [OUT] The custom value token value on return. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::SetCustomAttributeValue ( // Return code. mdCustomAttribute pcv, // [IN] The custom value token whose value to replace. void const *pCustomAttribute, // [IN] The custom value data. ULONG cbCustomAttribute)// [IN] The custom value data length. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::DefineField ( // S_OK or error. mdTypeDef td, // Parent TypeDef LPCWSTR szName, // Name of member DWORD dwFieldFlags, // Member attributes PCCOR_SIGNATURE pvSigBlob, // [IN] point to a blob value of CLR signature ULONG cbSigBlob, // [IN] count of bytes in the signature blob DWORD dwCPlusTypeFlag, // [IN] flag for value type. selected ELEMENT_TYPE_* void const *pValue, // [IN] constant value ULONG cchValue, // [IN] size of constant value (string, in wide chars). mdFieldDef *pmd) // [OUT] Put member token here { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::DefineProperty ( mdTypeDef td, // [IN] the class/interface on which the property is being defined LPCWSTR szProperty, // [IN] Name of the property DWORD dwPropFlags, // [IN] CorPropertyAttr PCCOR_SIGNATURE pvSig, // [IN] the required type signature ULONG cbSig, // [IN] the size of the type signature blob DWORD dwCPlusTypeFlag, // [IN] flag for value type. selected ELEMENT_TYPE_* void const *pValue, // [IN] constant value ULONG cchValue, // [IN] size of constant value (string, in wide chars). mdMethodDef mdSetter, // [IN] optional setter of the property mdMethodDef mdGetter, // [IN] optional getter of the property mdMethodDef rmdOtherMethods[], // [IN] an optional array of other methods mdProperty *pmdProp) // [OUT] output property token { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::DefineParam ( mdMethodDef md, // [IN] Owning method ULONG ulParamSeq, // [IN] Which param LPCWSTR szName, // [IN] Optional param name DWORD dwParamFlags, // [IN] Optional param flags DWORD dwCPlusTypeFlag, // [IN] flag for value type. selected ELEMENT_TYPE_* void const *pValue, // [IN] constant value ULONG cchValue, // [IN] size of constant value (string, in wide chars). mdParamDef *ppd) // [OUT] Put param token here { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::SetFieldProps ( // S_OK or error. mdFieldDef fd, // [IN] The FieldDef. DWORD dwFieldFlags, // [IN] Field attributes. DWORD dwCPlusTypeFlag, // [IN] Flag for the value type, selected ELEMENT_TYPE_* void const *pValue, // [IN] Constant value. ULONG cchValue) // [IN] size of constant value (string, in wide chars). { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::SetPropertyProps ( // S_OK or error. mdProperty pr, // [IN] Property token. DWORD dwPropFlags, // [IN] CorPropertyAttr. DWORD dwCPlusTypeFlag, // [IN] Flag for value type, selected ELEMENT_TYPE_* void const *pValue, // [IN] Constant value. ULONG cchValue, // [IN] size of constant value (string, in wide chars). mdMethodDef mdSetter, // [IN] Setter of the property. mdMethodDef mdGetter, // [IN] Getter of the property. mdMethodDef rmdOtherMethods[])// [IN] Array of other methods. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::SetParamProps ( // Return code. mdParamDef pd, // [IN] Param token. LPCWSTR szName, // [IN] Param name. DWORD dwParamFlags, // [IN] Param flags. DWORD dwCPlusTypeFlag, // [IN] Flag for value type. selected ELEMENT_TYPE_*. void const *pValue, // [OUT] Constant value. ULONG cchValue) // [IN] size of constant value (string, in wide chars). { _ASSERTE(!"NYI"); return E_NOTIMPL; } // Specialized Custom Attributes for security. STDMETHODIMP SymbolInfo::DefineSecurityAttributeSet ( // Return code. mdToken tkObj, // [IN] Class or method requiring security attributes. COR_SECATTR rSecAttrs[], // [IN] Array of security attribute descriptions. ULONG cSecAttrs, // [IN] Count of elements in above array. ULONG *pulErrorAttr) // [OUT] On error, index of attribute causing problem. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::ApplyEditAndContinue ( // S_OK or error. IUnknown *pImport) // [IN] Metadata from the delta PE. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::TranslateSigWithScope ( IMetaDataAssemblyImport *pAssemImport, // [IN] importing assembly interface const void *pbHashValue, // [IN] Hash Blob for Assembly. ULONG cbHashValue, // [IN] Count of bytes. IMetaDataImport *import, // [IN] importing interface PCCOR_SIGNATURE pbSigBlob, // [IN] signature in the importing scope ULONG cbSigBlob, // [IN] count of bytes of signature IMetaDataAssemblyEmit *pAssemEmit, // [IN] emit assembly interface IMetaDataEmit *emit, // [IN] emit interface PCOR_SIGNATURE pvTranslatedSig, // [OUT] buffer to hold translated signature ULONG cbTranslatedSigMax, ULONG *pcbTranslatedSig)// [OUT] count of bytes in the translated signature { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::SetMethodImplFlags ( // [IN] S_OK or error. mdMethodDef md, // [IN] Method for which to set ImplFlags DWORD dwImplFlags) { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::SetFieldRVA ( // [IN] S_OK or error. mdFieldDef fd, // [IN] Field for which to set offset ULONG ulRVA) // [IN] The offset { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::Merge ( // S_OK or error. IMetaDataImport *pImport, // [IN] The scope to be merged. IMapToken *pHostMapToken, // [IN] Host IMapToken interface to receive token remap notification IUnknown *pHandler) // [IN] An object to receive to receive error notification. { _ASSERTE(!"NYI"); return E_NOTIMPL; } STDMETHODIMP SymbolInfo::MergeEnd () // S_OK or error. { _ASSERTE(!"NYI"); return E_NOTIMPL; }
-1
dotnet/runtime
66,474
Update repo CMake configuration to target /W4 by default
Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
AaronRobinsonMSFT
2022-03-10T20:20:31Z
2022-03-11T04:59:21Z
ba5207b0f4054fe8963fc3e87c2bd32907516961
5ce2b9f860f7a84c3059650bb67817d59d8f4953
Update repo CMake configuration to target /W4 by default. Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
./src/libraries/System.Private.Xml/tests/Xslt/TestFiles/TestData/xsltc/baseline/infft14b.txt
@.\infft14c.txt
@.\infft14c.txt
-1
dotnet/runtime
66,474
Update repo CMake configuration to target /W4 by default
Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
AaronRobinsonMSFT
2022-03-10T20:20:31Z
2022-03-11T04:59:21Z
ba5207b0f4054fe8963fc3e87c2bd32907516961
5ce2b9f860f7a84c3059650bb67817d59d8f4953
Update repo CMake configuration to target /W4 by default. Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
./src/coreclr/ilasm/prebuilt/asmparse.cpp
/* * Created by Microsoft VCBU Internal YACC from "asmparse.y" */ #line 2 "asmparse.y" // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // File asmparse.y // #include "ilasmpch.h" #include "grammar_before.cpp" #line 16 "asmparse.y" #define UNION 1 typedef union { CorRegTypeAttr classAttr; CorMethodAttr methAttr; CorFieldAttr fieldAttr; CorMethodImpl implAttr; CorEventAttr eventAttr; CorPropertyAttr propAttr; CorPinvokeMap pinvAttr; CorDeclSecurity secAct; CorFileFlags fileAttr; CorAssemblyFlags asmAttr; CorAssemblyFlags asmRefAttr; CorTypeAttr exptAttr; CorManifestResourceFlags manresAttr; double* float64; __int64* int64; __int32 int32; char* string; BinStr* binstr; Labels* labels; Instr* instr; // instruction opcode NVPair* pair; pTyParList typarlist; mdToken token; TypeDefDescr* tdd; CustomDescr* cad; unsigned short opcode; } YYSTYPE; # define ERROR_ 257 # define BAD_COMMENT_ 258 # define BAD_LITERAL_ 259 # define ID 260 # define DOTTEDNAME 261 # define QSTRING 262 # define SQSTRING 263 # define INT32 264 # define INT64 265 # define FLOAT64 266 # define HEXBYTE 267 # define TYPEDEF_T 268 # define TYPEDEF_M 269 # define TYPEDEF_F 270 # define TYPEDEF_TS 271 # define TYPEDEF_MR 272 # define TYPEDEF_CA 273 # define DCOLON 274 # define ELIPSIS 275 # define VOID_ 276 # define BOOL_ 277 # define CHAR_ 278 # define UNSIGNED_ 279 # define INT_ 280 # define INT8_ 281 # define INT16_ 282 # define INT32_ 283 # define INT64_ 284 # define FLOAT_ 285 # define FLOAT32_ 286 # define FLOAT64_ 287 # define BYTEARRAY_ 288 # define UINT_ 289 # define UINT8_ 290 # define UINT16_ 291 # define UINT32_ 292 # define UINT64_ 293 # define FLAGS_ 294 # define CALLCONV_ 295 # define MDTOKEN_ 296 # define OBJECT_ 297 # define STRING_ 298 # define NULLREF_ 299 # define DEFAULT_ 300 # define CDECL_ 301 # define VARARG_ 302 # define STDCALL_ 303 # define THISCALL_ 304 # define FASTCALL_ 305 # define CLASS_ 306 # define TYPEDREF_ 307 # define UNMANAGED_ 308 # define FINALLY_ 309 # define HANDLER_ 310 # define CATCH_ 311 # define FILTER_ 312 # define FAULT_ 313 # define EXTENDS_ 314 # define IMPLEMENTS_ 315 # define TO_ 316 # define AT_ 317 # define TLS_ 318 # define TRUE_ 319 # define FALSE_ 320 # define _INTERFACEIMPL 321 # define VALUE_ 322 # define VALUETYPE_ 323 # define NATIVE_ 324 # define INSTANCE_ 325 # define SPECIALNAME_ 326 # define FORWARDER_ 327 # define STATIC_ 328 # define PUBLIC_ 329 # define PRIVATE_ 330 # define FAMILY_ 331 # define FINAL_ 332 # define SYNCHRONIZED_ 333 # define INTERFACE_ 334 # define SEALED_ 335 # define NESTED_ 336 # define ABSTRACT_ 337 # define AUTO_ 338 # define SEQUENTIAL_ 339 # define EXPLICIT_ 340 # define ANSI_ 341 # define UNICODE_ 342 # define AUTOCHAR_ 343 # define IMPORT_ 344 # define ENUM_ 345 # define VIRTUAL_ 346 # define NOINLINING_ 347 # define AGGRESSIVEINLINING_ 348 # define NOOPTIMIZATION_ 349 # define AGGRESSIVEOPTIMIZATION_ 350 # define UNMANAGEDEXP_ 351 # define BEFOREFIELDINIT_ 352 # define STRICT_ 353 # define RETARGETABLE_ 354 # define WINDOWSRUNTIME_ 355 # define NOPLATFORM_ 356 # define METHOD_ 357 # define FIELD_ 358 # define PINNED_ 359 # define MODREQ_ 360 # define MODOPT_ 361 # define SERIALIZABLE_ 362 # define PROPERTY_ 363 # define TYPE_ 364 # define ASSEMBLY_ 365 # define FAMANDASSEM_ 366 # define FAMORASSEM_ 367 # define PRIVATESCOPE_ 368 # define HIDEBYSIG_ 369 # define NEWSLOT_ 370 # define RTSPECIALNAME_ 371 # define PINVOKEIMPL_ 372 # define _CTOR 373 # define _CCTOR 374 # define LITERAL_ 375 # define NOTSERIALIZED_ 376 # define INITONLY_ 377 # define REQSECOBJ_ 378 # define CIL_ 379 # define OPTIL_ 380 # define MANAGED_ 381 # define FORWARDREF_ 382 # define PRESERVESIG_ 383 # define RUNTIME_ 384 # define INTERNALCALL_ 385 # define _IMPORT 386 # define NOMANGLE_ 387 # define LASTERR_ 388 # define WINAPI_ 389 # define AS_ 390 # define BESTFIT_ 391 # define ON_ 392 # define OFF_ 393 # define CHARMAPERROR_ 394 # define INSTR_NONE 395 # define INSTR_VAR 396 # define INSTR_I 397 # define INSTR_I8 398 # define INSTR_R 399 # define INSTR_BRTARGET 400 # define INSTR_METHOD 401 # define INSTR_FIELD 402 # define INSTR_TYPE 403 # define INSTR_STRING 404 # define INSTR_SIG 405 # define INSTR_TOK 406 # define INSTR_SWITCH 407 # define _CLASS 408 # define _NAMESPACE 409 # define _METHOD 410 # define _FIELD 411 # define _DATA 412 # define _THIS 413 # define _BASE 414 # define _NESTER 415 # define _EMITBYTE 416 # define _TRY 417 # define _MAXSTACK 418 # define _LOCALS 419 # define _ENTRYPOINT 420 # define _ZEROINIT 421 # define _EVENT 422 # define _ADDON 423 # define _REMOVEON 424 # define _FIRE 425 # define _OTHER 426 # define _PROPERTY 427 # define _SET 428 # define _GET 429 # define _PERMISSION 430 # define _PERMISSIONSET 431 # define REQUEST_ 432 # define DEMAND_ 433 # define ASSERT_ 434 # define DENY_ 435 # define PERMITONLY_ 436 # define LINKCHECK_ 437 # define INHERITCHECK_ 438 # define REQMIN_ 439 # define REQOPT_ 440 # define REQREFUSE_ 441 # define PREJITGRANT_ 442 # define PREJITDENY_ 443 # define NONCASDEMAND_ 444 # define NONCASLINKDEMAND_ 445 # define NONCASINHERITANCE_ 446 # define _LINE 447 # define P_LINE 448 # define _LANGUAGE 449 # define _CUSTOM 450 # define INIT_ 451 # define _SIZE 452 # define _PACK 453 # define _VTABLE 454 # define _VTFIXUP 455 # define FROMUNMANAGED_ 456 # define CALLMOSTDERIVED_ 457 # define _VTENTRY 458 # define RETAINAPPDOMAIN_ 459 # define _FILE 460 # define NOMETADATA_ 461 # define _HASH 462 # define _ASSEMBLY 463 # define _PUBLICKEY 464 # define _PUBLICKEYTOKEN 465 # define ALGORITHM_ 466 # define _VER 467 # define _LOCALE 468 # define EXTERN_ 469 # define _MRESOURCE 470 # define _MODULE 471 # define _EXPORT 472 # define LEGACY_ 473 # define LIBRARY_ 474 # define X86_ 475 # define AMD64_ 476 # define ARM_ 477 # define ARM64_ 478 # define MARSHAL_ 479 # define CUSTOM_ 480 # define SYSSTRING_ 481 # define FIXED_ 482 # define VARIANT_ 483 # define CURRENCY_ 484 # define SYSCHAR_ 485 # define DECIMAL_ 486 # define DATE_ 487 # define BSTR_ 488 # define TBSTR_ 489 # define LPSTR_ 490 # define LPWSTR_ 491 # define LPTSTR_ 492 # define OBJECTREF_ 493 # define IUNKNOWN_ 494 # define IDISPATCH_ 495 # define STRUCT_ 496 # define SAFEARRAY_ 497 # define BYVALSTR_ 498 # define LPVOID_ 499 # define ANY_ 500 # define ARRAY_ 501 # define LPSTRUCT_ 502 # define IIDPARAM_ 503 # define IN_ 504 # define OUT_ 505 # define OPT_ 506 # define _PARAM 507 # define _OVERRIDE 508 # define WITH_ 509 # define NULL_ 510 # define HRESULT_ 511 # define CARRAY_ 512 # define USERDEFINED_ 513 # define RECORD_ 514 # define FILETIME_ 515 # define BLOB_ 516 # define STREAM_ 517 # define STORAGE_ 518 # define STREAMED_OBJECT_ 519 # define STORED_OBJECT_ 520 # define BLOB_OBJECT_ 521 # define CF_ 522 # define CLSID_ 523 # define VECTOR_ 524 # define _SUBSYSTEM 525 # define _CORFLAGS 526 # define ALIGNMENT_ 527 # define _IMAGEBASE 528 # define _STACKRESERVE 529 # define _TYPEDEF 530 # define _TEMPLATE 531 # define _TYPELIST 532 # define _MSCORLIB 533 # define P_DEFINE 534 # define P_UNDEF 535 # define P_IFDEF 536 # define P_IFNDEF 537 # define P_ELSE 538 # define P_ENDIF 539 # define P_INCLUDE 540 # define CONSTRAINT_ 541 #define yyclearin yychar = -1 #define yyerrok yyerrflag = 0 #ifndef YYMAXDEPTH #define YYMAXDEPTH 150 #endif YYSTYPE yylval, yyval; #ifndef YYFARDATA #define YYFARDATA /*nothing*/ #endif #if ! defined YYSTATIC #define YYSTATIC /*nothing*/ #endif #if ! defined YYCONST #define YYCONST /*nothing*/ #endif #ifndef YYACT #define YYACT yyact #endif #ifndef YYPACT #define YYPACT yypact #endif #ifndef YYPGO #define YYPGO yypgo #endif #ifndef YYR1 #define YYR1 yyr1 #endif #ifndef YYR2 #define YYR2 yyr2 #endif #ifndef YYCHK #define YYCHK yychk #endif #ifndef YYDEF #define YYDEF yydef #endif #ifndef YYV #define YYV yyv #endif #ifndef YYS #define YYS yys #endif #ifndef YYLOCAL #define YYLOCAL #endif #ifndef YYR_T #define YYR_T int #endif typedef YYR_T yyr_t; #ifndef YYEXIND_T #define YYEXIND_T unsigned int #endif typedef YYEXIND_T yyexind_t; #ifndef YYOPTTIME #define YYOPTTIME 0 #endif # define YYERRCODE 256 #line 2062 "asmparse.y" #include "grammar_after.cpp" YYSTATIC YYCONST short yyexca[] = { #if !(YYOPTTIME) -1, 1, #endif 0, -1, -2, 0, #if !(YYOPTTIME) -1, 452, #endif 41, 538, -2, 311, #if !(YYOPTTIME) -1, 622, #endif 274, 555, 47, 555, -2, 230, #if !(YYOPTTIME) -1, 643, #endif 40, 310, 60, 310, -2, 555, #if !(YYOPTTIME) -1, 665, #endif 41, 538, -2, 311, #if !(YYOPTTIME) -1, 690, #endif 274, 555, 47, 555, -2, 516, #if !(YYOPTTIME) -1, 809, #endif 123, 235, -2, 555, #if !(YYOPTTIME) -1, 836, #endif 41, 538, -2, 311, #if !(YYOPTTIME) -1, 961, #endif 41, 538, -2, 311, #if !(YYOPTTIME) -1, 994, #endif 41, 538, -2, 311, #if !(YYOPTTIME) -1, 995, #endif 41, 538, -2, 311, #if !(YYOPTTIME) -1, 1323, #endif 41, 538, -2, 311, #if !(YYOPTTIME) -1, 1324, #endif 41, 538, -2, 311, #if !(YYOPTTIME) -1, 1331, #endif 41, 538, -2, 311, #if !(YYOPTTIME) -1, 1339, #endif 41, 538, -2, 311, #if !(YYOPTTIME) -1, 1465, #endif 41, 538, -2, 311, #if !(YYOPTTIME) -1, 1497, #endif 41, 538, -2, 311, #if !(YYOPTTIME) -1, 1564, #endif 41, 538, -2, 311, #if !(YYOPTTIME) -1, 1581, #endif 41, 538, -2, 311, }; # define YYNPROD 844 #if YYOPTTIME YYSTATIC YYCONST yyexind_t yyexcaind[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 30, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 34, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 38, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 42, 46, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 50, 54, 0, 0, 0, 0, 0, 0, 58, 0, 0, 0, 0, 0, 0, 0, 62, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 70, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 74, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 78 }; #endif # define YYLAST 3922 YYSTATIC YYCONST short YYFARDATA YYACT[] = { 703, 1484, 414, 1416, 1133, 640, 660, 191, 1482, 1485, 886, 1036, 971, 1483, 702, 788, 779, 885, 974, 729, 73, 75, 150, 625, 1521, 536, 1417, 792, 755, 190, 760, 757, 478, 176, 107, 972, 1146, 110, 106, 694, 1077, 275, 860, 604, 662, 599, 273, 78, 81, 219, 44, 24, 780, 262, 516, 214, 204, 7, 301, 188, 654, 76, 6, 991, 85, 5, 1569, 3, 1206, 1253, 220, 1125, 18, 1257, 115, 677, 1069, 264, 153, 1254, 307, 133, 74, 178, 179, 180, 181, 272, 1123, 218, 136, 10, 221, 300, 26, 137, 1070, 98, 278, 139, 217, 1124, 17, 202, 203, 581, 269, 74, 719, 716, 322, 265, 461, 113, 112, 700, 520, 939, 940, 352, 343, 88, 87, 353, 89, 462, 1255, 452, 1025, 268, 676, 338, 56, 537, 68, 1243, 1244, 305, 591, 88, 87, 357, 89, 277, 225, 327, 277, 368, 339, 1031, 342, 938, 361, 366, 185, 154, 1241, 1242, 98, 360, 359, 358, 277, 56, 88, 87, 345, 89, 656, 1573, 192, 782, 351, 783, 348, 365, 1537, 277, 86, 1039, 369, 310, 312, 314, 316, 318, 374, 277, 362, 198, 1038, 364, 699, 373, 199, 271, 200, 698, 1432, 84, 105, 379, 201, 417, 418, 363, 376, 1138, 1139, 450, 387, 451, 615, 88, 87, 186, 89, 388, 480, 195, 814, 1071, 663, 1505, 456, 767, 1279, 457, 1578, 999, 258, 473, 475, 416, 196, 1496, 484, 655, 481, 482, 470, 491, 468, 472, 471, 501, 346, 216, 495, 1329, 597, 1214, 192, 493, 441, 24, 833, 476, 479, 375, 433, 7, 1278, 56, 801, 813, 486, 432, 664, 74, 428, 492, 429, 483, 541, 436, 18, 641, 642, 487, 586, 376, 585, 584, 544, 56, 1354, 1355, 1356, 587, 941, 942, 267, 943, 435, 10, 154, 442, 26, 1337, 1336, 1335, 1334, 494, 791, 434, 17, 777, 542, 572, 74, 545, 714, 668, 575, 268, 576, 1249, 577, 1517, 499, 600, 862, 863, 864, 579, 580, 371, 370, 1009, 116, 511, 511, 528, 534, 108, 574, 372, 258, 571, 266, 549, 573, 192, 488, 367, 88, 87, 154, 89, 321, 1559, 601, 512, 512, 529, 535, 80, 79, 480, 198, 505, 152, 410, 1435, 199, 74, 200, 613, 1560, 348, 582, 583, 201, 74, 1130, 480, 46, 498, 481, 482, 375, 621, 88, 596, 459, 89, 624, 80, 79, 195, 1563, 607, 608, 609, 610, 481, 482, 1562, 606, 420, 614, 421, 422, 423, 196, 745, 1368, 612, 474, 611, 619, 620, 622, 485, 340, 341, 678, 1352, 639, 644, 74, 1561, 500, 88, 87, 1248, 89, 1128, 955, 56, 1153, 600, 595, 784, 135, 1154, 759, 649, 650, 354, 355, 356, 652, 635, 1507, 1536, 348, 884, 182, 643, 785, 56, 704, 1138, 1139, 666, 1408, 855, 321, 177, 88, 674, 1140, 89, 74, 669, 1531, 970, 1514, 685, 682, 951, 347, 566, 88, 1246, 46, 89, 74, 538, 1506, 1267, 569, 1528, 867, 1362, 747, 88, 87, 689, 89, 74, 671, 673, 1192, 1358, 1142, 696, 88, 87, 786, 89, 990, 989, 988, 588, 983, 982, 981, 980, 758, 978, 979, 105, 706, 987, 986, 985, 984, 537, 690, 1468, 977, 975, 651, 715, 1001, 1002, 1003, 1004, 88, 87, 692, 954, 177, 376, 693, 453, 155, 648, 705, 80, 79, 480, 683, 701, 546, 727, 707, 805, 61, 62, 47, 63, 709, 803, 710, 713, 1256, 861, 539, 460, 645, 481, 482, 718, 177, 1520, 647, 56, 1530, 88, 87, 225, 89, 74, 723, 1191, 659, 728, 646, 967, 730, 277, 1529, 724, 597, 725, 675, 976, 720, 80, 79, 1129, 762, 679, 680, 681, 413, 734, 82, 506, 1526, 56, 768, 769, 49, 50, 51, 52, 53, 54, 55, 74, 639, 1262, 1258, 1259, 1260, 1261, 74, 754, 1524, 601, 744, 733, 748, 749, 750, 1013, 98, 1011, 1012, 787, 543, 502, 72, 49, 50, 51, 52, 53, 54, 55, 74, 643, 74, 684, 1522, 477, 61, 62, 47, 63, 88, 87, 542, 89, 807, 808, 802, 71, 751, 752, 753, 812, 793, 821, 74, 514, 825, 819, 826, 822, 74, 695, 216, 70, 830, 1184, 1183, 1182, 1181, 156, 157, 158, 831, 804, 806, 74, 809, 74, 815, 480, 773, 774, 775, 790, 325, 841, 842, 823, 797, 69, 800, 818, 80, 79, 67, 377, 824, 832, 324, 481, 482, 348, 348, 854, 88, 87, 225, 89, 834, 858, 88, 87, 865, 89, 1153, 375, 672, 66, 930, 1154, 627, 628, 629, 49, 50, 51, 52, 53, 54, 55, 192, 944, 945, 868, 56, 853, 1153, 277, 856, 88, 87, 1154, 89, 74, 857, 49, 50, 51, 52, 53, 54, 55, 601, 957, 600, 1457, 630, 631, 632, 950, 1076, 1072, 1073, 1074, 1075, 1455, 946, 152, 1344, 46, 382, 383, 384, 385, 111, 177, 80, 79, 852, 74, 88, 87, 993, 89, 859, 348, 773, 88, 87, 1021, 89, 1022, 1019, 74, 1453, 362, 963, 956, 960, 966, 1018, 1451, 932, 46, 933, 934, 935, 936, 937, 216, 823, 74, 1032, 1434, 593, 1035, 637, 276, 1343, 968, 823, 606, 766, 997, 696, 696, 496, 1026, 1044, 1020, 1425, 74, 441, 1007, 1016, 1424, 1422, 1407, 433, 1027, 962, 1049, 829, 1024, 1047, 432, 1029, 1028, 428, 517, 429, 1051, 1042, 436, 1006, 1014, 528, 74, 1405, 80, 79, 480, 840, 1045, 1046, 1395, 145, 973, 519, 1411, 670, 765, 435, 1005, 1015, 442, 1008, 1017, 529, 823, 1062, 481, 482, 434, 1057, 88, 87, 337, 89, 1393, 49, 50, 51, 52, 53, 54, 55, 592, 277, 636, 277, 1391, 326, 323, 56, 152, 1389, 1067, 1387, 1385, 277, 1383, 49, 50, 51, 52, 53, 54, 55, 1381, 1379, 1376, 1373, 962, 1371, 1367, 41, 43, 1351, 1327, 1209, 1208, 1056, 996, 1055, 1134, 88, 87, 1315, 89, 762, 1079, 1054, 1080, 155, 776, 63, 722, 46, 1053, 543, 1034, 1033, 1144, 828, 1150, 1252, 616, 504, 820, 513, 737, 1131, 508, 509, 618, 1136, 617, 1141, 578, 522, 527, 177, 565, 1065, 1251, 308, 455, 1313, 109, 63, 1137, 1197, 92, 1145, 1198, 1195, 1196, 964, 1316, 770, 1037, 520, 1311, 513, 521, 1349, 508, 509, 1309, 1187, 1143, 695, 695, 992, 1194, 1193, 145, 1207, 1190, 953, 1210, 1185, 1, 1418, 1189, 1199, 1200, 1201, 1202, 1179, 1177, 1175, 1066, 589, 1234, 1203, 1204, 1205, 1314, 49, 50, 51, 52, 53, 54, 55, 712, 348, 88, 87, 1217, 89, 626, 1312, 590, 1211, 1245, 1063, 1152, 1310, 1188, 1247, 152, 1218, 1239, 1173, 1171, 1169, 145, 1238, 1237, 1240, 1186, 49, 50, 51, 52, 53, 54, 55, 1180, 1178, 1176, 88, 87, 348, 89, 74, 1167, 1165, 205, 155, 525, 352, 1250, 711, 708, 353, 156, 157, 158, 1163, 192, 192, 192, 192, 1135, 634, 277, 1161, 277, 1127, 192, 192, 192, 357, 1174, 1172, 1170, 177, 591, 412, 378, 1433, 626, 1263, 192, 46, 1159, 187, 794, 97, 88, 87, 63, 89, 1157, 1430, 949, 1168, 1166, 1508, 1138, 1139, 524, 1155, 351, 526, 317, 1266, 527, 1280, 1164, 1284, 315, 1286, 1288, 1289, 1270, 1292, 1162, 1294, 1295, 1296, 1297, 1298, 1299, 1300, 1274, 1302, 1303, 1304, 1305, 1306, 1307, 1308, 1269, 1429, 313, 1160, 1317, 1318, 1291, 1320, 1293, 1428, 1319, 1158, 1287, 1285, 1290, 152, 1301, 311, 1419, 1236, 1156, 309, 1282, 308, 1060, 1322, 1212, 306, 1213, 308, 1059, 844, 1328, 746, 667, 1233, 1333, 352, 1332, 45, 94, 353, 49, 50, 51, 52, 53, 54, 55, 454, 328, 329, 330, 308, 415, 88, 87, 277, 89, 357, 156, 157, 158, 155, 591, 1558, 823, 1345, 308, 1338, 1347, 1348, 308, 352, 1331, 332, 1330, 353, 308, 56, 277, 152, 1272, 1353, 1357, 1147, 525, 277, 140, 1215, 351, 177, 952, 1360, 1283, 357, 948, 1023, 1359, 277, 827, 1281, 277, 138, 1350, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 1470, 839, 591, 1469, 838, 1361, 351, 817, 63, 1397, 1398, 1399, 1400, 1401, 1402, 1403, 591, 1346, 524, 771, 764, 526, 1364, 258, 721, 796, 567, 117, 1409, 1410, 349, 1414, 1396, 1413, 352, 1571, 1415, 591, 772, 1043, 591, 591, 56, 1421, 1420, 931, 1583, 591, 1426, 331, 303, 333, 334, 335, 336, 1574, 357, 1152, 1572, 1565, 1541, 823, 1504, 1503, 88, 87, 1502, 89, 1412, 1472, 1467, 134, 155, 1464, 1341, 96, 1423, 1461, 104, 103, 102, 101, 1460, 99, 100, 105, 1456, 351, 156, 157, 158, 1454, 49, 50, 51, 52, 53, 54, 55, 1452, 177, 1450, 1437, 1509, 1431, 1427, 258, 1581, 697, 1406, 1510, 1404, 1394, 1462, 1392, 1463, 1390, 1388, 354, 355, 356, 97, 352, 1386, 836, 56, 353, 1473, 1474, 1475, 88, 87, 1466, 89, 1471, 1384, 531, 1382, 155, 88, 87, 1380, 89, 1378, 357, 1377, 1375, 1374, 1488, 350, 1152, 1372, 1370, 1486, 56, 1369, 1366, 1489, 1494, 1487, 88, 1365, 1566, 89, 1342, 1340, 177, 1476, 1326, 1325, 1499, 1321, 1271, 46, 1498, 351, 1363, 1268, 1235, 1516, 56, 1126, 1523, 1525, 1527, 1064, 1523, 1525, 1527, 258, 1050, 206, 1534, 1525, 1048, 1041, 1040, 1532, 1538, 1501, 1539, 1535, 1540, 1533, 1519, 1030, 969, 959, 958, 947, 866, 1515, 1518, 1513, 849, 848, 846, 156, 157, 158, 449, 843, 193, 1511, 837, 194, 835, 816, 823, 795, 778, 742, 1523, 1525, 1527, 741, 740, 739, 354, 355, 356, 738, 736, 88, 735, 688, 89, 638, 198, 177, 570, 425, 424, 199, 344, 200, 46, 320, 1564, 1497, 1493, 201, 1492, 1491, 1490, 1570, 1465, 1459, 1458, 1568, 1449, 1448, 1447, 1446, 354, 355, 356, 1577, 195, 1575, 1445, 1580, 1579, 156, 157, 158, 1582, 1444, 1567, 1443, 1442, 1441, 1440, 196, 1439, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 1438, 1436, 823, 1315, 59, 523, 1313, 1576, 208, 259, 210, 228, 212, 213, 1311, 1309, 1339, 56, 88, 882, 1187, 89, 41, 43, 56, 1185, 876, 1179, 877, 878, 879, 46, 1177, 1175, 1173, 1171, 515, 1169, 1167, 61, 62, 47, 63, 1165, 1163, 1161, 1324, 354, 355, 356, 223, 1323, 1265, 96, 1264, 56, 104, 103, 102, 101, 46, 99, 100, 105, 222, 1078, 871, 872, 873, 1068, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 998, 1061, 1052, 46, 59, 995, 994, 426, 208, 259, 210, 228, 212, 213, 961, 851, 226, 224, 1058, 850, 847, 845, 41, 43, 732, 731, 717, 691, 687, 870, 874, 875, 686, 880, 665, 633, 881, 603, 530, 61, 62, 47, 63, 49, 50, 51, 52, 53, 54, 55, 223, 602, 354, 355, 356, 594, 568, 548, 547, 497, 419, 411, 386, 319, 222, 304, 518, 302, 510, 507, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 503, 36, 184, 93, 59, 33, 469, 467, 208, 259, 210, 228, 212, 213, 466, 465, 226, 224, 95, 464, 244, 463, 41, 43, 227, 243, 215, 209, 1098, 38, 30, 58, 32, 59, 207, 211, 887, 31, 1010, 61, 62, 47, 63, 49, 50, 51, 52, 53, 54, 55, 223, 41, 43, 1000, 439, 38, 30, 58, 32, 59, 869, 799, 431, 798, 222, 46, 430, 427, 61, 62, 47, 63, 46, 540, 270, 60, 35, 41, 43, 83, 29, 21, 57, 34, 37, 25, 16, 263, 15, 189, 14, 39, 40, 261, 61, 62, 47, 63, 13, 226, 224, 60, 35, 46, 260, 12, 11, 21, 9, 8, 37, 4, 2, 444, 234, 242, 241, 39, 40, 240, 444, 239, 238, 237, 236, 235, 49, 50, 51, 52, 53, 54, 55, 233, 232, 231, 230, 229, 114, 77, 42, 756, 658, 657, 1500, 299, 19, 20, 90, 22, 23, 48, 183, 27, 28, 49, 50, 51, 52, 53, 54, 55, 1151, 761, 789, 1273, 965, 1149, 1148, 605, 1479, 1478, 19, 20, 1477, 22, 23, 48, 1495, 27, 28, 49, 50, 51, 52, 53, 54, 55, 882, 1481, 1480, 1216, 1132, 598, 661, 876, 781, 877, 878, 879, 448, 91, 58, 32, 59, 1081, 743, 448, 65, 58, 32, 59, 64, 197, 445, 883, 0, 0, 0, 446, 0, 445, 41, 43, 929, 0, 446, 0, 0, 41, 43, 0, 0, 0, 0, 871, 872, 873, 0, 61, 62, 47, 63, 1109, 437, 438, 61, 62, 47, 63, 0, 437, 438, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1085, 1086, 447, 1093, 1107, 1087, 1088, 1089, 1090, 447, 1091, 1092, 0, 1108, 1094, 1095, 1096, 1097, 63, 870, 874, 875, 0, 880, 0, 0, 881, 0, 532, 0, 0, 533, 0, 0, 0, 0, 0, 443, 440, 0, 0, 0, 0, 0, 443, 440, 0, 0, 0, 0, 0, 882, 0, 0, 0, 0, 193, 0, 876, 194, 877, 878, 879, 0, 49, 50, 51, 52, 53, 54, 55, 49, 50, 51, 52, 53, 54, 55, 0, 0, 0, 0, 198, 177, 0, 0, 0, 199, 0, 200, 0, 0, 0, 0, 0, 201, 901, 0, 871, 872, 873, 0, 49, 50, 51, 52, 53, 54, 55, 146, 928, 0, 195, 0, 0, 893, 894, 0, 902, 919, 895, 896, 897, 898, 0, 899, 900, 196, 920, 903, 904, 905, 906, 0, 0, 0, 0, 348, 0, 0, 0, 0, 0, 0, 870, 874, 875, 0, 880, 0, 0, 881, 1232, 1231, 1226, 0, 1225, 1224, 1223, 1222, 0, 1220, 1221, 105, 0, 1230, 1229, 1228, 1227, 0, 0, 0, 0, 917, 1219, 921, 0, 990, 989, 988, 923, 983, 982, 981, 980, 0, 978, 979, 105, 0, 987, 986, 985, 984, 0, 0, 925, 977, 975, 0, 1542, 0, 0, 0, 0, 0, 0, 1083, 1084, 0, 1099, 1100, 1101, 0, 1102, 1103, 0, 0, 1104, 1105, 0, 1106, 0, 0, 0, 0, 0, 0, 0, 926, 0, 0, 0, 0, 1082, 1110, 1111, 1112, 1113, 1114, 1115, 1116, 1117, 1118, 1119, 1120, 1121, 1122, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 901, 0, 0, 976, 0, 0, 1512, 0, 0, 0, 0, 0, 0, 0, 928, 0, 0, 0, 0, 893, 894, 0, 902, 919, 895, 896, 897, 898, 0, 899, 900, 0, 920, 903, 904, 905, 906, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 146, 0, 0, 0, 0, 888, 0, 889, 890, 891, 892, 907, 908, 909, 924, 910, 911, 912, 913, 914, 915, 916, 918, 922, 917, 0, 921, 927, 0, 0, 0, 923, 0, 175, 0, 0, 0, 151, 148, 163, 161, 170, 0, 164, 165, 166, 167, 925, 168, 169, 0, 0, 171, 172, 173, 174, 564, 1557, 152, 142, 162, 0, 0, 0, 0, 0, 0, 0, 141, 147, 0, 1547, 0, 0, 0, 0, 0, 0, 0, 0, 926, 0, 0, 0, 143, 144, 149, 1543, 556, 0, 550, 551, 552, 553, 0, 0, 1552, 0, 0, 146, 0, 0, 0, 0, 352, 0, 0, 0, 772, 0, 1553, 1554, 1555, 1556, 0, 0, 0, 0, 0, 160, 0, 0, 0, 0, 0, 0, 357, 558, 559, 560, 561, 0, 0, 555, 0, 0, 0, 562, 563, 554, 0, 0, 1544, 1545, 1546, 1548, 1549, 1550, 1551, 0, 0, 0, 0, 0, 0, 0, 0, 623, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 888, 0, 889, 890, 891, 892, 907, 908, 909, 924, 910, 911, 912, 913, 914, 915, 916, 918, 922, 990, 989, 988, 927, 983, 982, 981, 980, 0, 978, 979, 105, 0, 987, 986, 985, 984, 0, 0, 0, 977, 975, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 88, 87, 0, 89, 0, 0, 0, 0, 155, 0, 0, 175, 0, 0, 557, 151, 148, 163, 161, 170, 0, 164, 165, 166, 167, 0, 168, 169, 0, 0, 171, 172, 173, 174, 146, 0, 177, 142, 162, 352, 0, 0, 0, 353, 0, 0, 141, 147, 0, 976, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 357, 143, 144, 149, 0, 0, 175, 0, 0, 0, 0, 0, 163, 161, 170, 0, 164, 165, 166, 167, 0, 168, 169, 0, 0, 171, 172, 173, 174, 0, 0, 623, 1276, 162, 0, 0, 160, 159, 88, 87, 0, 89, 0, 0, 0, 0, 155, 0, 0, 175, 0, 0, 0, 151, 148, 163, 161, 170, 0, 164, 165, 166, 167, 0, 168, 169, 0, 0, 171, 172, 173, 174, 0, 0, 177, 142, 162, 0, 0, 0, 1277, 0, 0, 0, 141, 147, 0, 0, 0, 0, 297, 198, 156, 157, 158, 0, 199, 0, 200, 1275, 143, 144, 149, 0, 201, 0, 0, 0, 0, 0, 0, 0, 0, 0, 146, 0, 0, 0, 0, 352, 0, 195, 284, 353, 279, 280, 281, 282, 283, 63, 0, 0, 0, 287, 0, 160, 196, 354, 355, 356, 0, 357, 285, 0, 0, 0, 0, 295, 0, 286, 0, 641, 642, 0, 0, 0, 0, 0, 0, 0, 0, 288, 289, 290, 291, 292, 293, 294, 298, 0, 0, 0, 623, 0, 296, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 156, 157, 158, 0, 0, 0, 0, 0, 0, 88, 87, 0, 89, 0, 0, 0, 0, 155, 146, 0, 175, 0, 0, 0, 151, 148, 163, 161, 170, 0, 164, 165, 166, 167, 0, 168, 169, 0, 0, 171, 172, 173, 174, 0, 0, 177, 142, 162, 0, 0, 0, 0, 0, 0, 0, 141, 147, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 143, 144, 149, 0, 0, 274, 0, 0, 0, 0, 0, 0, 0, 0, 0, 146, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 160, 0, 354, 355, 356, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 641, 642, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 274, 0, 0, 0, 0, 0, 88, 87, 0, 89, 0, 0, 0, 0, 155, 0, 0, 175, 156, 157, 158, 151, 148, 163, 161, 170, 0, 164, 165, 166, 167, 0, 168, 169, 0, 0, 171, 172, 173, 174, 0, 146, 177, 142, 162, 0, 0, 0, 0, 0, 0, 0, 141, 147, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 143, 144, 149, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 274, 0, 88, 87, 160, 89, 354, 355, 356, 0, 155, 146, 0, 175, 0, 0, 0, 151, 148, 163, 161, 170, 0, 164, 165, 166, 167, 0, 168, 169, 0, 0, 171, 172, 173, 174, 0, 0, 177, 142, 162, 0, 0, 0, 0, 0, 0, 0, 141, 147, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 156, 157, 158, 0, 143, 144, 149, 0, 811, 274, 88, 87, 0, 89, 0, 0, 0, 0, 155, 0, 0, 175, 0, 146, 0, 151, 148, 163, 161, 170, 0, 164, 165, 166, 167, 0, 168, 169, 0, 160, 171, 172, 173, 174, 0, 0, 177, 142, 162, 0, 0, 0, 0, 810, 0, 0, 141, 147, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 143, 144, 149, 0, 0, 0, 0, 0, 0, 274, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 146, 0, 0, 156, 157, 158, 0, 0, 0, 0, 0, 0, 0, 0, 0, 160, 159, 88, 87, 0, 89, 0, 0, 0, 0, 155, 0, 0, 175, 0, 0, 0, 151, 148, 163, 161, 170, 0, 164, 165, 166, 167, 0, 168, 169, 0, 0, 171, 172, 173, 174, 0, 0, 177, 142, 162, 0, 0, 274, 0, 0, 0, 0, 141, 147, 0, 0, 0, 0, 0, 0, 156, 157, 158, 0, 0, 0, 0, 0, 143, 144, 149, 0, 0, 0, 0, 88, 87, 0, 89, 0, 0, 0, 0, 155, 0, 0, 175, 0, 0, 0, 151, 148, 163, 161, 170, 0, 164, 165, 166, 167, 0, 168, 169, 160, 0, 171, 172, 173, 174, 0, 0, 177, 142, 162, 0, 0, 0, 0, 0, 0, 0, 763, 147, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 146, 0, 143, 144, 149, 0, 0, 0, 0, 0, 0, 0, 88, 87, 0, 89, 0, 0, 0, 0, 155, 0, 0, 175, 156, 157, 158, 151, 148, 163, 161, 170, 0, 164, 165, 166, 167, 160, 168, 169, 0, 0, 171, 172, 173, 174, 0, 0, 177, 142, 162, 0, 0, 0, 0, 146, 0, 0, 141, 147, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 143, 144, 149, 0, 0, 0, 0, 88, 87, 0, 89, 0, 0, 0, 0, 155, 0, 0, 175, 156, 157, 158, 151, 148, 163, 161, 170, 0, 164, 165, 166, 167, 0, 168, 169, 653, 146, 171, 172, 173, 174, 0, 0, 177, 142, 162, 88, 87, 0, 89, 0, 0, 0, 141, 147, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 143, 144, 149, 0, 0, 0, 0, 0, 0, 0, 0, 409, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 156, 157, 158, 996, 0, 0, 146, 0, 0, 0, 0, 0, 0, 458, 0, 0, 0, 391, 0, 0, 0, 407, 0, 0, 389, 390, 0, 0, 0, 393, 394, 405, 395, 396, 397, 398, 399, 400, 401, 402, 392, 0, 0, 0, 0, 0, 0, 406, 0, 0, 404, 0, 0, 0, 0, 0, 0, 403, 0, 0, 146, 0, 0, 0, 726, 0, 408, 0, 0, 156, 157, 158, 489, 175, 490, 0, 0, 151, 148, 163, 161, 170, 0, 164, 165, 166, 167, 0, 168, 169, 0, 0, 171, 172, 173, 174, 0, 0, 177, 142, 162, 0, 0, 0, 0, 0, 0, 0, 141, 147, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 143, 144, 149, 380, 175, 381, 0, 0, 151, 148, 163, 161, 170, 0, 164, 165, 166, 167, 0, 168, 169, 0, 0, 171, 172, 173, 174, 0, 0, 0, 142, 162, 0, 0, 0, 160, 0, 0, 0, 141, 147, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 143, 144, 149, 0, 175, 0, 0, 0, 151, 148, 163, 161, 170, 0, 164, 165, 166, 167, 0, 168, 169, 0, 0, 171, 172, 173, 174, 0, 0, 0, 142, 162, 0, 0, 0, 160, 0, 0, 0, 141, 147, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 143, 144, 149, 0, 0, 0, 0, 0, 0, 0, 175, 0, 0, 0, 151, 148, 163, 161, 170, 0, 164, 165, 166, 167, 0, 168, 169, 0, 0, 171, 172, 173, 174, 0, 0, 160, 142, 162, 0, 0, 0, 0, 0, 0, 0, 141, 147, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 143, 144, 149, 175, 0, 0, 0, 151, 148, 163, 161, 170, 0, 164, 165, 166, 167, 0, 168, 169, 0, 0, 171, 172, 173, 174, 0, 0, 0, 142, 162, 0, 0, 0, 0, 160, 0, 0, 141, 147, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 143, 144, 149, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 160 }; YYSTATIC YYCONST short YYFARDATA YYPACT[] = { -1000, 1423,-1000, 609, 586,-1000,-1000,-1000,-1000,-1000, -1000,-1000, 581, 555, 539, 514,-1000,-1000,-1000, 102, 102, -466, 124, 124,-1000,-1000,-1000, 478,-1000, -115, 535,-1000, 907, 1099, 68, 903, 102, -355, -356,-1000, -139, 855, 68, 855,-1000,-1000,-1000, 172, 2319, 535, 535, 535, 535,-1000,-1000, 187,-1000,-1000,-1000, -164, 1074,-1000,-1000, 1825, 68, 68,-1000,-1000, 1368,-1000, -1000,-1000,-1000,-1000,-1000,-1000, 102, -121,-1000,-1000, -1000,-1000, 691, -120, 2983, 1193,-1000,-1000,-1000,-1000, 2436,-1000, 102,-1000, 1385,-1000, 1310, 1718, 68, 1169, 1163, 1159, 1144, 1120, 1114, 1716, 1518, 83,-1000, 102, 655, 878,-1000,-1000, 86, 1193, 535, 2983,-1000,-1000, -1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000, -1000,-1000,-1000, 1515, 185, 1288, 1061, -229, -230, -231, -238, 691,-1000, -101, 691, 1255, 312,-1000,-1000, 48, -1000, 3564, 239, 1081,-1000,-1000,-1000,-1000,-1000, 3394, -1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000, 504,-1000,-1000,-1000,-1000,-1000, 1193, 1715, 538, 1193, 1193, 1193,-1000, 3232, 123,-1000,-1000, 1714, 1066, 2884, -1000, 3564,-1000,-1000,-1000, 65, 65,-1000, 1713,-1000, -1000, 99, 1513, 1512, 1575, 1397,-1000,-1000, 102,-1000, 102, 87,-1000,-1000,-1000,-1000, 1173,-1000,-1000,-1000, -1000,-1000, 901, 102, 3193,-1000, 21, -69,-1000,-1000, 201, 102, 124, 610, 68, 201, 1255, 3339, 2983, -88, 65, 2884, 1712,-1000, 215,-1000,-1000,-1000,-1000,-1000, -1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000, 511, 545, 860, 1606,-1000, 100,-1000, 355, 691,-1000, -1000, 2983,-1000,-1000, 164, 1217, 65, 535,-1000,-1000, -1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000, -1000,-1000,-1000,-1000,-1000,-1000,-1000, 1711, 1710, 2114, 895, 349, 1284, 1709, 123, 1511, -48,-1000, 102, -48, -1000, 124,-1000, 102,-1000, 102,-1000, 102,-1000,-1000, -1000,-1000, 891,-1000, 102, 102,-1000, 1193,-1000,-1000, -1000, -369,-1000,-1000,-1000,-1000,-1000, 878, -47, 116, -1000,-1000, 1193, 999,-1000, 1299, 789, 1708,-1000, 170, 535, 157,-1000,-1000,-1000, 1704, 1690, 3564, 535, 535, 535, 535,-1000, 691,-1000,-1000, 3564, 228,-1000, 1193, -1000, -68,-1000, 1217, 879, 889, 887, 535, 535, 2721, -1000,-1000,-1000,-1000,-1000,-1000, 102, 1299, 1070,-1000, -1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000, -1000,-1000,-1000,-1000,-1000, 406,-1000,-1000,-1000, 1688, 1052,-1000, 791, 1508,-1000,-1000, 2580,-1000,-1000, 102, -1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000, 458, 446, 417,-1000,-1000,-1000,-1000,-1000, 102, 102, 402, 3124,-1000,-1000, -304, -196,-1000,-1000,-1000,-1000,-1000, -1000,-1000, -53, 1687,-1000, 102, 1158, 39, 65, 794, 640, 102,-1000, -69, 107, 107, 107, 107, 2983, 215, -1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000, -1000, 1685, 1681, 1506,-1000,-1000,-1000, 2721,-1000,-1000, -1000,-1000, 1299, 1680, 68, 3564,-1000, 201, 1285,-1000, -119, -124,-1000,-1000, -351,-1000,-1000, 68, 411, 454, 68,-1000,-1000, 1041,-1000,-1000, 68,-1000, 68,-1000, 1040, 991,-1000,-1000, 535, -157, -360, 1679,-1000,-1000, -1000,-1000, 535, -361,-1000,-1000, -346,-1000,-1000,-1000, 1282,-1000, 869, 535, 3564, 1193, 3510, 102, 108, 1181, -1000,-1000,-1000,-1000,-1000,-1000,-1000, 1678,-1000,-1000, -1000,-1000,-1000,-1000, 1677,-1000,-1000, 1385, 108, 1505, -1000, 1503, 883, 1502, 1498, 1497, 1496, 1492,-1000, 362, 1157,-1000, 97, 1193,-1000,-1000,-1000, 298, 535, 108, 388, 175, 3052,-1000,-1000, 1278, 1193,-1000, 793,-1000, -1000, -50, 2983, 2983, 943, 1277, 1217, 1193, 1193, 1193, 1193,-1000, 2418,-1000, 1193,-1000, 535, 535, 535, 867, 1193, 33, 1193, 494, 1491,-1000, 128,-1000,-1000,-1000, -1000,-1000,-1000, 102,-1000, 1299,-1000,-1000, 1255, 30, 1076,-1000,-1000, 1193, 1490, 1202,-1000,-1000,-1000,-1000, -1000,-1000, -10, 65, 465, 459, 2983, 2816, -106, -47, 1488, 1265,-1000,-1000, 3510, -53, 881, 102, -96, 3564, 102, 1193, 102, 1238, 876,-1000,-1000,-1000, 201,-1000, -1000,-1000,-1000,-1000,-1000,-1000, 102, 124,-1000, -18, 1193, 108, 1487, 1386, 1485, 1262, 1259,-1000, 123, 102, 102, 1482, 1155,-1000,-1000, 1299, 1674, 1477, 1673, 1476, 1475, 1672, 1668, 1193, 535,-1000, 535, 102, 141, 535, 68, 2983, 535, 706, 1298, 81, -182, 1471, 95, 1795, 131, 1877, 102,-1000, 1306,-1000, 900,-1000, 900, 900, 900, 900, 900, -166,-1000, 102, 102, 535,-1000,-1000, -1000,-1000,-1000,-1000, 1193, 1470, 1234, 1083,-1000,-1000, 347, 1230, 964, 271, 166,-1000, 46, 102, 1469, 1468, -1000, 3564, 1667, 1081, 1081, 1081, 535, 535,-1000, 941, 542, 128,-1000,-1000,-1000,-1000,-1000, 1467, 343, 226, 958, -96, 1659, 1658, 3449,-1000,-1000, 1568, 104, 204, 690, -96, 3564, 102, 1193, 102, 1235, -322, 535, 1193, -1000,-1000, 3564,-1000,-1000, 1193,-1000, -53, 81, 1466, -241,-1000,-1000, 1193, 2721, 874, 873, 2983, 945, -126, -137, 1457, 1456, 535, 1300,-1000, -53,-1000, 201, 201, -1000,-1000,-1000,-1000, 411,-1000,-1000,-1000,-1000,-1000, -1000,-1000, 1081, 1193, 1455, 102, 1193, 1451,-1000, 535, -96, 1655, 871, 864, 856, 854,-1000, 108, 1670,-1000, -1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000, 1154, 1148, 1654, 945, 123, 1446, 947, 68, 1639, -405, -56,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000, -1000,-1000, 495,-1000,-1000,-1000,-1000,-1000,-1000,-1000, -1000,-1000,-1000,-1000, 1635, 1635,-1000, 1635, 1762,-1000, -1000, -408,-1000, -387,-1000,-1000, -429,-1000,-1000,-1000, 1442,-1000,-1000,-1000,-1000,-1000,-1000,-1000, 123,-1000, -1000,-1000,-1000,-1000, 165, 331, 1193,-1000, 108, 829, 338,-1000, 3052, 374, 955,-1000,-1000,-1000,-1000,-1000, 1217, -53, 1081, 1193,-1000, 535, 1223, 2983,-1000,-1000, -1000, 393,-1000,-1000,-1000, 1111, 1102, 1094, 1075, 1067, 1055, 1054, 1033, 1032, 1031, 997, 996, 995, 399, 987, 975, 68, 455, 1076, -53, -53, 102, 938,-1000,-1000, -1000, 1255, 1255, 1255, 1255,-1000,-1000,-1000,-1000,-1000, -1000, 1255, 1255, 1255,-1000,-1000,-1000,-1000,-1000, -441, 2721, 853, 852, 2983,-1000, 1255, 1193, 1181,-1000, 123, -1000, 123, -23,-1000, 1227,-1000,-1000, 1913, 123, 102, -1000,-1000, 1193,-1000, 1439,-1000,-1000, 1143,-1000,-1000, -287, 998, 1877,-1000,-1000,-1000,-1000, 1299,-1000, -236, -257, 102,-1000,-1000,-1000,-1000, 383, 192, 108, 899, 880,-1000,-1000,-1000,-1000,-1000,-1000,-1000, -434,-1000, -1000, 35,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000, -1000,-1000,-1000, 336,-1000,-1000,-1000,-1000,-1000,-1000, -1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000, -1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000, -1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000, 102,-1000,-1000,-1000,-1000, 1624, 1299, 1622,-1000,-1000, -1000,-1000,-1000, 359, 1438, 1223,-1000, 128, 1433, 1220, -1000, 2375,-1000,-1000,-1000, -37, 102, 977, 102, 1938, 102, 110, 102, 93, 102, 124, 102, 102, 102, 102, 102, 102, 102, 124, 102, 102, 102, 102, 102, 102, 102, 974, 968, 953, 913, 102, 102, -112, 102, 1432, 1299,-1000,-1000, 1621, 1616, 1430, 1429, 851,-1000,-1000, -1000,-1000,-1000,-1000,-1000,-1000, 65, -25,-1000, 1214, -1000, 1216,-1000,-1000, -96, 2983,-1000,-1000, 1299,-1000, 1615, 1614, 1613, 1608, 1607, 1605, 18, 1604, 1603, 1602, 1597, 1595, 1590,-1000,-1000,-1000, 411,-1000, 1586, 1426, 1335,-1000,-1000,-1000,-1000, 1425,-1000, 740, 102,-1000, 1275, 102, 102, 950, 108, 850,-1000,-1000,-1000,-1000, -1000,-1000,-1000, 155, 102, 5, 371,-1000,-1000,-1000, -1000,-1000, 2983, 395,-1000,-1000,-1000, 1172, 1422, 1417, 847, 144, 1416, 1413, 846, 1412, 844, 1408, 1407, 843, 1406, 1404, 842, 1402, 841, 1398, 833, 1396, 831, 1384, 830, 1378, 828, 1377, 823, 1375, 811, 1373, 787, 124, 102, 102, 102, 102, 102, 102, 102, 1372, 780, 1370, 759,-1000, 332, -53, -53,-1000,-1000, 822, 3564, -96, 2983, -53, 969,-1000, 1585, 1584, 1576, 1573, 1142, -53, -1000,-1000,-1000,-1000, 102, 758, 108, 757, 752, 102, 1299,-1000,-1000, 1366, 1133, 1125, 1085, 1365,-1000, 73, -1000, 1068, 735, 101,-1000,-1000,-1000, 1571, 1363,-1000, -1000, 1570,-1000, 1556,-1000,-1000, 1554,-1000,-1000, 1553, -1000, 1552,-1000, 1551,-1000, 1549,-1000, 1542,-1000, 1535, -1000, 1534,-1000, 1533,-1000, 1532, 1362, 723, 1360, 716, 1352, 687, 1347, 677,-1000, 1530,-1000, 1529,-1000, 1343, 1338,-1000, 2721, 969,-1000, 1334, 1528,-1000, 857, 411, 1331, 429,-1000, 1261,-1000, 2042, 1330,-1000, 102, 102, 102,-1000,-1000, 1938,-1000,-1000,-1000,-1000,-1000,-1000, -1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000, -1000, 1526,-1000, 1525,-1000, 1524,-1000, 1522,-1000,-1000, -1000,-1000, -39, 1521, 945, -53,-1000,-1000,-1000, 108, -1000, 947,-1000, 1327, 1324, 1323,-1000, 182, 1106, 2264, 428, 278, 527, 608, 582, 562, 443, 544, 530, 426, -1000,-1000,-1000,-1000, 405, 135, -96, -53,-1000, 1321, 2115, 1203,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000, 88,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000, -1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000, -1000,-1000, 328, 381, 357, 350,-1000,-1000,-1000, 1520, 1320,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000, -1000,-1000,-1000,-1000,-1000,-1000,-1000, 1424, 108,-1000, -1000,-1000,-1000,-1000, -53, -443, 102, 1296, 1319, -188, 1316,-1000,-1000, 65,-1000, 3564, 2721, -46, -96, 969, 1369, -53, 1307,-1000 }; YYSTATIC YYCONST short YYFARDATA YYPGO[] = { 0, 33, 178, 5, 1991, 78, 39, 7, 1989, 0, 1988, 1984, 1982, 268, 80, 1981, 1977, 4, 1972, 52, 40, 3, 26, 32, 24, 6, 1970, 44, 41, 45, 1969, 38, 34, 10, 17, 11, 31, 1968, 42, 1967, 35, 18, 1966, 1965, 9, 1, 13, 8, 1954, 1950, 1947, 1946, 22, 27, 43, 1945, 1944, 1943, 1942, 15, 1941, 1940, 12, 1939, 30, 1938, 14, 36, 16, 23, 46, 2, 599, 59, 1236, 29, 106, 1928, 1924, 1921, 1920, 1919, 1918, 19, 28, 1917, 1329, 1916, 1915, 25, 789, 131, 1914, 50, 1221, 1913, 1912, 1911, 1910, 1909, 1901, 1900, 1899, 1898, 1897, 1895, 1892, 1891, 1890, 1028, 1888, 67, 56, 1887, 65, 134, 62, 55, 1885, 1884, 89, 1882, 1881, 1880, 1874, 1869, 1866, 53, 1864, 1863, 1862, 100, 70, 49, 1861, 92, 292, 1859, 1858, 1856, 1855, 1850, 1849, 1843, 1842, 1839, 1838, 1837, 1830, 832, 1829, 1814, 1813, 1812, 1811, 1810, 1803, 1802, 75, 1801, 1800, 125, 1797, 1796, 1795, 130, 1791, 1790, 1783, 1782, 1781, 1779, 1778, 58, 1760, 63, 1777, 54, 1776, 602, 1762, 1761, 1759, 1646, 1615, 1438 }; YYSTATIC YYCONST yyr_t YYFARDATA YYR1[]={ 0, 109, 109, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 136, 136, 36, 36, 133, 133, 133, 2, 2, 1, 1, 1, 9, 24, 24, 23, 23, 23, 134, 134, 134, 134, 134, 135, 135, 135, 135, 135, 135, 135, 135, 135, 93, 93, 93, 93, 94, 94, 94, 94, 10, 11, 73, 72, 72, 59, 61, 61, 61, 62, 62, 62, 65, 65, 132, 132, 132, 60, 60, 60, 60, 60, 60, 130, 130, 130, 119, 12, 12, 12, 12, 12, 12, 118, 137, 113, 138, 139, 111, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 140, 140, 141, 141, 112, 112, 142, 142, 56, 56, 57, 57, 69, 69, 18, 18, 18, 18, 18, 19, 19, 68, 68, 67, 67, 58, 21, 21, 22, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 116, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 4, 4, 35, 35, 16, 16, 75, 75, 75, 75, 75, 75, 75, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 76, 74, 74, 74, 74, 74, 74, 144, 144, 81, 81, 81, 145, 145, 150, 150, 150, 150, 150, 150, 150, 150, 146, 82, 82, 82, 147, 147, 151, 151, 151, 151, 151, 151, 151, 152, 38, 38, 34, 34, 153, 114, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 83, 83, 83, 83, 83, 83, 83, 83, 83, 83, 83, 83, 83, 83, 83, 83, 3, 3, 3, 13, 13, 13, 13, 13, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 154, 115, 115, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 158, 159, 156, 161, 161, 160, 160, 160, 163, 162, 162, 162, 162, 166, 166, 166, 169, 164, 167, 168, 165, 165, 165, 117, 170, 170, 172, 172, 172, 171, 171, 173, 173, 14, 14, 174, 174, 174, 174, 174, 174, 174, 174, 174, 174, 174, 174, 174, 174, 174, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 175, 31, 31, 32, 32, 39, 39, 39, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 42, 42, 42, 43, 43, 43, 47, 47, 46, 46, 45, 45, 44, 44, 48, 48, 49, 49, 49, 50, 50, 50, 50, 51, 51, 149, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 6, 6, 6, 6, 6, 53, 53, 54, 54, 55, 55, 25, 25, 26, 26, 27, 27, 27, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 5, 5, 71, 71, 71, 71, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 20, 20, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 30, 30, 29, 29, 29, 29, 29, 131, 131, 131, 131, 131, 131, 64, 64, 64, 63, 63, 87, 87, 84, 84, 85, 17, 17, 37, 37, 37, 37, 37, 37, 37, 37, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 176, 176, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 121, 121, 88, 88, 89, 89, 177, 122, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 123, 123, 178, 178, 178, 66, 66, 179, 179, 179, 179, 179, 179, 180, 182, 181, 124, 124, 125, 125, 183, 183, 183, 183, 126, 148, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 127, 127, 184, 184, 184, 184, 184, 184, 184, 128, 128, 92, 92, 92, 129, 129, 185, 185, 185, 185 }; YYSTATIC YYCONST yyr_t YYFARDATA YYR2[]={ 0, 0, 2, 4, 4, 3, 1, 1, 1, 1, 1, 1, 4, 4, 4, 4, 1, 1, 1, 2, 2, 3, 2, 2, 1, 1, 1, 4, 1, 0, 2, 1, 3, 2, 4, 6, 1, 1, 1, 1, 3, 1, 1, 1, 1, 4, 4, 4, 4, 4, 4, 4, 2, 3, 2, 2, 2, 1, 1, 2, 1, 2, 4, 6, 3, 5, 7, 9, 3, 4, 7, 1, 1, 1, 2, 0, 2, 2, 0, 6, 2, 1, 1, 1, 1, 1, 1, 1, 1, 3, 2, 3, 1, 2, 3, 7, 0, 2, 2, 2, 2, 2, 3, 3, 2, 1, 4, 3, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 2, 2, 2, 5, 0, 2, 0, 2, 0, 2, 3, 1, 0, 1, 1, 3, 0, 3, 1, 1, 1, 1, 1, 0, 2, 4, 3, 0, 2, 3, 0, 1, 5, 3, 4, 4, 4, 1, 1, 1, 1, 1, 2, 2, 4, 13, 22, 1, 1, 5, 3, 7, 5, 4, 7, 0, 2, 2, 2, 2, 2, 2, 2, 5, 2, 2, 2, 2, 2, 2, 5, 0, 2, 0, 2, 0, 3, 9, 9, 7, 7, 1, 1, 1, 2, 2, 1, 4, 0, 1, 1, 2, 2, 2, 2, 1, 4, 2, 5, 3, 2, 2, 1, 4, 3, 0, 2, 2, 0, 2, 2, 2, 2, 2, 1, 1, 1, 1, 9, 0, 2, 2, 0, 2, 2, 2, 2, 1, 1, 1, 1, 1, 0, 4, 1, 3, 1, 13, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 8, 6, 5, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 4, 4, 4, 4, 5, 1, 1, 1, 0, 4, 4, 4, 4, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 1, 0, 2, 2, 1, 2, 4, 5, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 4, 6, 4, 4, 11, 1, 5, 3, 7, 5, 5, 3, 1, 2, 2, 1, 2, 4, 4, 1, 2, 2, 2, 2, 2, 2, 2, 1, 2, 1, 1, 1, 4, 4, 2, 4, 2, 0, 1, 1, 3, 1, 3, 1, 0, 3, 5, 4, 3, 5, 5, 5, 5, 5, 5, 2, 2, 2, 2, 2, 2, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 0, 1, 1, 2, 1, 1, 1, 1, 4, 4, 5, 4, 4, 4, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 0, 2, 2, 0, 2, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 2, 0, 2, 3, 2, 0, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 2, 2, 2, 2, 2, 2, 3, 2, 2, 2, 5, 3, 2, 2, 2, 2, 2, 5, 4, 6, 2, 4, 0, 3, 3, 1, 1, 0, 3, 0, 1, 1, 3, 0, 1, 1, 3, 1, 3, 4, 4, 4, 4, 5, 1, 1, 1, 1, 1, 1, 1, 3, 1, 3, 4, 1, 0, 10, 6, 5, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 1, 1, 2, 3, 4, 6, 5, 1, 1, 1, 1, 1, 1, 1, 2, 2, 1, 2, 2, 4, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 1, 0, 5, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 1, 1, 1, 3, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 3, 2, 3, 4, 2, 2, 2, 5, 5, 7, 4, 3, 2, 3, 2, 1, 1, 2, 3, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 3, 0, 1, 1, 3, 2, 6, 7, 3, 3, 3, 6, 0, 1, 3, 5, 6, 4, 4, 1, 3, 3, 1, 1, 1, 1, 4, 1, 6, 6, 6, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 2, 5, 4, 7, 6, 7, 6, 9, 8, 3, 8, 4, 0, 2, 0, 1, 3, 3, 0, 2, 2, 2, 3, 2, 2, 2, 2, 2, 0, 2, 3, 1, 1, 1, 1, 3, 8, 2, 3, 1, 1, 3, 3, 3, 4, 6, 0, 2, 3, 1, 3, 1, 4, 3, 0, 2, 2, 2, 3, 3, 3, 3, 3, 3, 0, 2, 2, 3, 3, 4, 2, 1, 1, 3, 5, 0, 2, 2, 0, 2, 4, 3, 1, 1 }; YYSTATIC YYCONST short YYFARDATA YYCHK[]={ -1000,-109,-110,-111,-113,-114,-116,-117,-118,-119, -120,-121,-122,-124,-126,-128,-130,-131,-132, 525, 526, 460, 528, 529,-133,-134,-135, 532, 533,-139, 409,-152, 411,-170,-137, 455,-176, 463, 408, 470, 471, 430, -87, 431, -93, -94, 273, 449, 530, 534, 535, 536, 537, 538, 539, 540, 59,-138, 410, 412, 454, 447, 448, 450, -10, -11, 123, 123,-115, 123, 123, 123, 123, -9, 264, -9, 527, -88, -24, 265, 264, -24, 123,-140, 314, -1, -2, 261, 260, 263, -78, -16, 91,-171, 123,-174, 278, 38,-175, 286, 287, 284, 283, 282, 281, 288, -31, -32, 267, 91, -9, -90, 469, 469, -92, -1, 469, -86, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 445, 446, -31, -86, 263, -28, -70, -74, -93, -94, 306, 297, 322, 323,-149, 33, 307, 276, 324, -52, 275, 91, -5, -76, 268, 413, 414, 415, 358, 357, 278, 298, 277, 281, 282, 283, 284, 286, 287, 279, 290, 291, 292, 293, 271, -1, 296, -1, -1, -1, -1, 262, -77,-172, 318, 379, 61, -73, 40, -75, -7, -76, 269, 272, 325, 340, -8, 295, 300, 302, 308, -31, -31,-112,-109, 125,-155, 416,-156, 418,-154, 420, 421,-117,-157, -2,-131,-120,-133, -132,-135, 472, 458, 508,-158, 507,-160, 419, -95, -96, -97, -98, -99,-108,-100,-101,-102,-103,-104, -105,-106,-107,-159,-163, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 123, 417, -123,-125,-127,-129, -9, -1, 461,-136, -70, -76, -141, 315, -71, -70, 91, -28,-149, 46, -7, 328, 329, 330, 331, 332, 326, 346, 353, 337, 365, 366, 367, 368, 369, 370, 371, 351, 378, 294, 372, -79, -9,-173,-174, 42, 40, -31, 40, -14, 91, 40, -14, 40, -14, 40, -14, 40, -14, 40, -14, 40, 41, 267, -9, 263, 58, 44, 262, -1, 354, 355, 356, 473, 379, 475, 476, 477, 478, -90, -91, -1, 329, 330, -1, -71, 41, -36, 61, 288, 262, 44, 390, 91, 38, 42, 359, 360, 361, 60, 390, 390, 390, 390, -70, 306, -70, -75, -7, 33, -9, -1, 280, 279, 289, -28, -1, -76, 42, 471, 47, -28, 270, 272, 281, 282, 283, 284, 40, -36, -1, 329, 330, 322, 345, 334, 335, 337, 338, 339, 340, 341, 342, 343, 344, 362, 355, 336, 352, 326, 371, 294, -2, 40, 61, -72, -71, -74, -28, -7, -7, 40, 301, 303, 304, 305, 41, 41, 125,-143,-114,-111, -144,-146,-116,-117,-131,-120,-132, 452, 453,-148, 508,-133,-135, 507, 321, 422, 427, 472, 408, 125, -9, -9, 40, 451, 58, 91, -9, -71, 357, 364, 541, 91,-161,-162,-164,-166,-167,-168, 311,-169, 309, 313, 312, -9, -2, -9, -24, 40, -23, -24, 266, 286, 287, -31, -9, -2, -75, -28, -76, 270, 272, -71, -36, 341,-175, -7, -72, 40,-115,-158, -2, -9, 125,-178, 462,-131,-179,-180, 467, 468, -181,-132,-135, 464, 125,-183,-177,-179,-182, 338, 462, 465, 125,-184, 460, 408, 463, 296,-132,-135, 125,-185, 460, 463,-132,-135, -89, 420, 125,-136, -142, -71, -1, 471, -7, -1, -13, 40, 40, -28, 328, 329, 330, 331, 377, 371, 326, 479, 365, 366, 367, 368, 375, 376, 294, 93, 125, 44, 40, -2, 41, -23, -9, -23, -24, -9, -9, -9, 93, -9, -9, 474, -1, -1, 330, 329, 327, 336, 390, 40, 61, 43, 123, 40, 40, 263, -1, 93, -30, -29, 275, -9, 40, 40, -54, -55, -28, -1, -1, -1, -1, -70, -28, -9, -1, 280, 93, 93, 93, -1, -1, -71, -1, 91, -9, -69, 60, 329, 330, 331, 365, 366, 367, 40, 61, -36, 123, 40, 41, -71, -3, 373, 374, -1, -9,-115, 123, 123, 123, -9, -9, 123, -71, 357, 364, 541, 364, -81, -82, -91, -25, -26, -27, 275, -13, 40, -9, 58, 274, -7, 91, -1, 91, -1, -9,-161,-165,-158, 310,-165, -165,-165, -71,-158, -2, -9, 40, 40, 41, -71, -1, 40, -31, -28, -6, -2, -9, 125, 316, 316, 466, -31, -66, -9, 42, -36, 61, -31, 61, -31, -31, 61, 61, -1, 469, -9, 469, 40, -1, 469, -177, 44, 93, -1, -28, -28, 91, -9, -36, -83, -1, 40, 40,-173, -36, 41, 41, 93, 41, 41, 41, 41, 41, -12, 263, 44, 58, 390, 329, 330, 331, 365, 366, 367, -1, -84, -85, -36, 123, 262, -64, -63, -71, 306, 44, 93, 44, 275, -71, -71, 62, 44, 42, -5, -5, -5, 93, 274, 41, -68, -19, -18, 43, 45, 306, 323, 373, -9, -59, -61, -73, 274, -53, -22, 60, 41, 125,-112,-145,-147, -127, 274, -7, 91, -1, 91, -1, -71, -71, -1, 371, 326, -7, 371, 326, -1, 41, 44, -28, -25, 93, -9, -3, -1, -28, -9, -9, 44, 93, -2, -9, -9, -24, 274, -36, 41, 40, 41, 44, 44, -2, -9, -9, 41, 58, 40, 41, 40, 41, 41, 40, 40, -5, -1, -9, 317, -1, -31, -71, 93, -38, 479, 504, 505, 506, -9, 41, 390, -83, 41, 387, 341, 342, 343, 388, 389, 301, 303, 304, 305, 391, 394, 294, -4, 317, -34, -33,-153, 480, 482, 483, 484, 485, 276, 277, 281, 282, 283, 284, 286, 287, 257, 279, 290, 291, 292, 293, 486, 487, 488, 490, 491, 492, 493, 494, 495, 496, 334, 497, 280, 289, 336, 498, 341, 489, 357, 390, 502, 271, 123, -9, 41, -14, -14, -14, -14, -14, -14, 317, 283, 284, 456, 457, 459, -9, -9, -1, 41, 44, 61, -59, 125, 44, 61, 263, 263, -29, -9, 41, 41, -28, 40, -5, -1, 62, -58, -1, 40, -19, 41, 125, -62, -40,-135, -41, 298, 364, 297, 286, 287, 284, 283, 282, 281, 293, 292, 291, 290, 279, 278, 277,-175, 61, -3, 40, 40, 91, -54, 125, 125, -150, 423, 424, 425, 426,-120,-132,-133,-135, 125, -151, 428, 429, 426,-132,-120,-133,-135, 125, -3, -28, -9, -9, 44, -93, 450, -1, -28, -27, -38, 41, 390, -71, 93, 93, -71, -35, 61, 316, 316, 41, 41, -1, 41, -25, -6, -6, -66, 41, -9, 41, -3, 40, 93, 93, 93, 93, -36, 41, 58, 58, 40, -35, -2, 41, 42, 91, -32, 40, 481, 501, 277, 281, 282, 283, 284, 280, -20, 40, -20, -20, -15, 510, 483, 484, 276, 277, 281, 282, 283, 284, 286, 287, 279, 290, 291, 292, 293, 42, 486, 487, 488, 490, 491, 494, 495, 497, 280, 289, 257, 511, 512, 513, 514, 515, 516, 517, 518, 519, 520, 521, 522, 523, 496, 488, 500, 41, -2, 263, 263, 44, -84, -37, -17, -9, 283, -36, -70, 319, 320, 125, -64, 123, 61, -25, -1, -67, 44, -56, -57, -71, -65,-135, 358, 363, 40, 91, 40, 91, 40, 91, 40, 91, 40, 91, 40, 91, 40, 91, 40, 91, 40, 91, 40, 91, 40, 91, 40, 91, 40, 91, 284, 283, 282, 281, 40, 91, 40, 91, -31, -36, 123, 40, -53, -22, -25, -25, -9, 62, -75, -75, -75, -75, -75, -75, -75, 509, -71, 93, 93, -71, -1, -2, -2, 274, 44, -39, -41, -36, 299, 286, 287, 284, 283, 282, 281, 279, 293, 292, 291, 290, 278, 277, -2, -9, 41, 58, -89, -69, -34, -83, 392, 393, 392, 393, -9, 93, -9, 43, 125, -36, 91, 91, 503, 44, 91, 524, 38, 281, 282, 283, 284, 280, -9, 40, 40, -62, 123, 41, -67, -68, 41, 44, -60, -52, 364, 297, 345, 299, 263, -9, 306, -70, 299, -9, -40, -9, -23, -9, -9, -23, -24, -9, -24, -9, -9, -9, -9, -9, -9, -9, -24, -9, -9, -9, -9, -9, -9, -9, 40, 91, 40, 91, 40, 91, 40, 91, -9, -9, -17, -9, 41, -59, 40, 40, 41, 41, 93, -7, 274, 44, 40, -3, -71, 284, 283, 282, 281, -66, 40, 41, 41, 41, 93, 43, -9, 44, -9, -9, 61, -36, 93, 263, -9, 281, 282, 283, -9, 125, -62, -71, -1, 91, 306, -70, 41, 41, 93, 263, 41, 41, 93, 41, 93, 41, 41, 93, 41, 41, 93, 41, 93, 41, 93, 41, 93, 41, 93, 41, 93, 41, 93, 41, 93, 41, 93, -24, -9, -9, -9, -9, -9, -9, -9, 41, 93, 41, 93, 125, -25, -25, 62, -28, -3, -71, -25, -21, -22, 60, 58, -25, -9, 93, -36, 93, 93, -9, 41, 58, 58, 58, 41, 125, 61, 93, 263, 40, 41, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 41, 93, 41, 93, 41, 93, 41, 93, 40, 40, 41, 41, -71, -21, 41, 40, -66, 41, 93, 44, 41, -33, 41, -9, -9, -9, -40, -49, -50, -51, -42, -43, -47, -46, -45, -44, -47, -46, -45, -44, 40, 40, 40, 40, -45, -48, 274, 40, -35, -25, -80, -36, 41, 41, 41, 41, 299, 263, 41, 299, 306, -70, 41, -40, 41, -23, -9, 41, -23, -24, 41, -24, 41, -9, 41, -9, 41, -9, 41, 41, 41, 41, -47, -46, -45, -44, 41, 41, -17, -3, -25, 41, 123, 324, 379, 380, 381, 308, 382, 383, 384, 385, 333, 347, 348, 349, 350, 294, 44, 263, 41, 41, 41, 41, 40, 41, 40, -36, -25, 509, -9, 41, 41, 357, 41, -7, -28, -71, 274, -3, -21, 40, -25, 41 }; YYSTATIC YYCONST short YYFARDATA YYDEF[]={ 1, -2, 2, 0, 0, 333, 6, 7, 8, 9, 10, 11, 0, 0, 0, 0, 16, 17, 18, 0, 0, 772, 0, 0, 24, 25, 26, 0, 28, 135, 0, 269, 206, 0, 431, 0, 0, 778, 105, 835, 92, 0, 431, 0, 83, 84, 85, 0, 0, 0, 0, 0, 0, 57, 58, 0, 60, 108, 262, 387, 0, 757, 758, 219, 431, 431, 139, 1, 0, 788, 806, 824, 838, 19, 41, 20, 0, 0, 22, 42, 43, 23, 29, 137, 0, 104, 38, 39, 36, 37, 219, 186, 0, 384, 0, 391, 0, 0, 431, 394, 394, 394, 394, 394, 394, 0, 0, 432, 433, 0, 760, 0, 778, 814, 0, 93, 0, 0, 742, 743, 744, 745, 746, 747, 748, 749, 750, 751, 752, 753, 754, 755, 756, 0, 0, 33, 0, 0, 0, 0, 0, 0, 668, 0, 0, 219, 0, 684, 685, 0, 689, 0, 0, 549, 233, 551, 552, 553, 554, 0, 489, 691, 692, 693, 694, 695, 696, 697, 698, 699, 0, 704, 705, 706, 707, 708, 555, 0, 52, 54, 55, 56, 59, 0, 386, 388, 389, 0, 61, 0, 71, 0, 212, 213, 214, 219, 219, 217, 0, 220, 221, 226, 0, 0, 0, 0, 5, 334, 0, 336, 0, 0, 340, 341, 342, 343, 0, 345, 346, 347, 348, 349, 0, 0, 0, 355, 0, 0, 332, 504, 0, 0, 0, 0, 431, 0, 219, 0, 0, 0, 219, 0, 0, 333, 0, 490, 491, 492, 493, 494, 495, 496, 497, 498, 499, 500, 501, 502, 362, 369, 0, 0, 0, 0, 21, 774, 773, 0, 29, 550, 107, 0, 136, 557, 0, 560, 219, 0, 311, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 0, 0, 0, 0, 0, 393, 0, 0, 0, 0, 405, 0, 0, 406, 0, 407, 0, 408, 0, 409, 0, 410, 430, 102, 434, 0, 759, 0, 0, 769, 777, 779, 780, 781, 0, 783, 784, 785, 786, 787, 0, 0, 833, 836, 837, 94, 718, 719, 720, 0, 0, 31, 0, 0, 711, 673, 674, 675, 0, 0, 534, 0, 0, 0, 0, 667, 0, 670, 228, 0, 0, 681, 683, 686, 0, 688, 690, 0, 0, 0, 0, 0, 0, 231, 232, 700, 701, 702, 703, 0, 53, 147, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 0, 131, 132, 133, 0, 0, 103, 0, 0, 72, 73, 0, 215, 216, 0, 222, 223, 224, 225, 64, 68, 3, 140, 333, 0, 0, 0, 168, 169, 170, 171, 172, 0, 0, 0, 0, 178, 179, 0, 0, 236, 250, 814, 105, 4, 335, 337, -2, 0, 344, 0, 0, 0, 219, 0, 0, 0, 363, 365, 0, 0, 0, 0, 0, 0, 379, 380, 377, 505, 506, 507, 508, 503, 509, 510, 44, 0, 0, 0, 512, 513, 514, 0, 517, 518, 519, 520, 521, 0, 431, 0, 525, 527, 0, 366, 0, 0, 12, 789, 0, 791, 792, 431, 0, 0, 431, 799, 800, 0, 13, 807, 431, 809, 431, 811, 0, 0, 14, 825, 0, 0, 0, 0, 831, 832, 15, 839, 0, 0, 842, 843, 771, 775, 27, 30, 138, 142, 0, 0, 0, 40, 0, 0, 292, 0, 187, 188, 189, 190, 191, 192, 193, 0, 195, 196, 197, 198, 199, 200, 0, 207, 390, 0, 0, 0, 398, 0, 0, 0, 0, 0, 0, 0, 96, 762, 0, 782, 804, 812, 815, 816, 817, 0, 0, 0, 0, 0, 722, 727, 728, 34, 47, 671, 0, 709, 712, 713, 0, 0, 0, 535, 536, 48, 49, 50, 51, 669, 0, 680, 682, 687, 0, 0, 0, 0, 556, 0, -2, 711, 0, 106, 154, 125, 126, 127, 128, 129, 130, 0, 385, 62, 75, 69, 219, 0, 532, 308, 309, -2, 0, 0, 139, 239, 253, 173, 174, 824, 0, 219, 0, 0, 0, 0, 219, 0, 0, 539, 540, 542, 0, -2, 0, 0, 0, 0, 0, 357, 0, 0, 0, 364, 370, 381, 0, 371, 372, 373, 378, 374, 375, 376, 0, 0, 511, 0, -2, 0, 0, 0, 0, 530, 531, 361, 0, 0, 0, 0, 0, 793, 794, 797, 0, 0, 0, 0, 0, 0, 0, 826, 0, 830, 0, 0, 0, 0, 431, 0, 558, 0, 0, 263, 0, 0, 292, 0, 202, 561, 0, 392, 0, 397, 394, 395, 394, 394, 394, 394, 394, 0, 761, 0, 0, 0, 818, 819, 820, 821, 822, 823, 834, 0, 729, 0, 75, 32, 0, 723, 0, 0, 0, 672, 711, 715, 0, 0, 679, 0, 674, 545, 546, 547, 0, 0, 227, 0, 0, 154, 149, 150, 151, 152, 153, 0, 0, 78, 65, 0, 0, 0, 534, 218, 164, 0, 0, 0, 0, 0, 0, 0, 181, 0, 0, 0, 0, -2, 237, 238, 0, 251, 252, 813, 338, 311, 263, 0, 350, 352, 353, 310, 0, 0, 0, 0, 204, 0, 0, 0, 0, 0, 0, 523, -2, 526, 527, 527, 367, 368, 790, 795, 0, 803, 798, 801, 808, 810, 776, 802, 827, 828, 0, 0, 841, 0, 141, 559, 0, 0, 0, 0, 0, 0, 288, 0, 0, 291, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 0, 0, 0, 204, 0, 0, 265, 0, 0, 0, 566, 567, 568, 569, 570, 571, 572, 573, 574, 575, 576, 577, 0, 582, 583, 584, 585, 591, 592, 593, 594, 595, 596, 597, 616, 616, 600, 616, 618, 604, 606, 0, 608, 0, 610, 612, 0, 614, 615, 267, 0, 396, 399, 400, 401, 402, 403, 404, 0, 97, 98, 99, 100, 101, 764, 766, 805, 716, 0, 0, 0, 721, 722, 0, 37, 35, 710, 714, 676, 677, 537, -2, 548, 229, 148, 0, 158, 143, 155, 134, 63, 74, 76, 77, 438, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 431, 0, 532, -2, -2, 0, 0, 165, 166, 240, 219, 219, 219, 219, 245, 246, 247, 248, 167, 254, 219, 219, 219, 258, 259, 260, 261, 175, 0, 0, 0, 0, 0, 184, 219, 234, 0, 541, 543, 339, 0, 0, 356, 0, 359, 360, 0, 0, 0, 45, 46, 515, 522, 0, 528, 529, 0, 829, 840, 774, 147, 561, 312, 313, 314, 315, 292, 290, 0, 0, 0, 185, 203, 194, 586, 0, 0, 0, 0, 0, 611, 578, 579, 580, 581, 605, 598, 0, 599, 601, 602, 619, 620, 621, 622, 623, 624, 625, 626, 627, 628, 629, 0, 634, 635, 636, 637, 638, 642, 643, 644, 645, 646, 647, 648, 649, 650, 652, 653, 654, 655, 656, 657, 658, 659, 660, 661, 662, 663, 664, 665, 666, 607, 609, 613, 201, 95, 763, 765, 0, 730, 731, 734, 735, 0, 737, 0, 732, 733, 717, 724, 78, 0, 0, 158, 157, 154, 0, 144, 145, 0, 80, 81, 82, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 66, 75, 70, 0, 0, 0, 0, 0, 533, 241, 242, 243, 244, 255, 256, 257, 219, 0, 180, 0, 183, 0, 544, 351, 0, 0, 205, 435, 436, 437, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 382, 383, 524, 0, 770, 0, 0, 0, 303, 304, 305, 306, 0, 587, 0, 0, 266, 0, 0, 0, 0, 0, 0, 640, 641, 630, 631, 632, 633, 651, 768, 0, 0, 0, 78, 678, 156, 159, 160, 0, 0, 86, 87, 88, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 429, 0, -2, -2, 210, 211, 0, 0, 0, 0, -2, 161, 358, 0, 0, 0, 0, 0, -2, 264, 289, 307, 588, 0, 0, 0, 0, 0, 0, 603, 639, 767, 0, 0, 0, 0, 0, 725, 0, 146, 0, 0, 0, 90, 439, 440, 0, 0, 442, 443, 0, 444, 0, 411, 413, 0, 412, 414, 0, 415, 0, 416, 0, 417, 0, 418, 0, 423, 0, 424, 0, 425, 0, 426, 0, 0, 0, 0, 0, 0, 0, 0, 0, 427, 0, 428, 0, 67, 0, 0, 163, 0, 161, 182, 0, 0, 162, 0, 0, 0, 0, 590, 0, 564, 561, 0, 736, 0, 0, 0, 741, 726, 0, 91, 89, 480, 441, 483, 487, 464, 467, 470, 472, 474, 476, 470, 472, 474, 476, 419, 0, 420, 0, 421, 0, 422, 0, 474, 478, 208, 209, 0, 0, 204, -2, 796, 316, 589, 0, 563, 565, 617, 0, 0, 0, 79, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 470, 472, 474, 476, 0, 0, 0, -2, 249, 0, 0, 0, 738, 739, 740, 461, 481, 482, 462, 484, 0, 486, 463, 488, 445, 465, 466, 446, 468, 469, 447, 471, 448, 473, 449, 475, 450, 477, 451, 452, 453, 454, 0, 0, 0, 0, 459, 460, 479, 0, 0, 354, 268, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 0, 0, 485, 455, 456, 457, 458, -2, 0, 0, 0, 0, 0, 0, 562, 176, 219, 331, 0, 0, 0, 0, 161, 0, -2, 0, 177 }; #ifdef YYRECOVER YYSTATIC YYCONST short yyrecover[] = { -1000 }; #endif /* SCCSWHAT( "@(#)yypars.c 3.1 88/11/16 22:00:49 " ) */ #line 3 "F:\\NetFXDev1\\src\\tools\\devdiv\\amd64\\yypars.c" #if ! defined(YYAPI_PACKAGE) /* ** YYAPI_TOKENNAME : name used for return value of yylex ** YYAPI_TOKENTYPE : type of the token ** YYAPI_TOKENEME(t) : the value of the token that the parser should see ** YYAPI_TOKENNONE : the representation when there is no token ** YYAPI_VALUENAME : the name of the value of the token ** YYAPI_VALUETYPE : the type of the value of the token (if null, then the value is derivable from the token itself) ** YYAPI_VALUEOF(v) : how to get the value of the token. */ #define YYAPI_TOKENNAME yychar #define YYAPI_TOKENTYPE int #define YYAPI_TOKENEME(t) (t) #define YYAPI_TOKENNONE -1 #define YYAPI_TOKENSTR(t) (sprintf_s(yytokbuf, ARRAY_SIZE(yytokbuf), "%d", t), yytokbuf) #define YYAPI_VALUENAME yylval #define YYAPI_VALUETYPE YYSTYPE #define YYAPI_VALUEOF(v) (v) #endif #if ! defined(YYAPI_CALLAFTERYYLEX) #define YYAPI_CALLAFTERYYLEX #endif # define YYFLAG -1000 # define YYERROR goto yyerrlab # define YYACCEPT return(0) # define YYABORT return(1) #ifdef YYDEBUG /* RRR - 10/9/85 */ char yytokbuf[20]; # ifndef YYDBFLG # define YYDBFLG (yydebug) # endif # define yyprintf(a, b, c, d) if (YYDBFLG) YYPRINT(a, b, c, d) #else # define yyprintf(a, b, c, d) #endif #ifndef YYPRINT #define YYPRINT printf #endif /* parser for yacc output */ #ifdef YYDUMP int yydump = 1; /* 1 for dumping */ void yydumpinfo(void); #endif #ifdef YYDEBUG YYSTATIC int yydebug = 0; /* 1 for debugging */ #endif YYSTATIC YYSTYPE yyv[YYMAXDEPTH]; /* where the values are stored */ YYSTATIC short yys[YYMAXDEPTH]; /* the parse stack */ #if ! defined(YYRECURSIVE) YYSTATIC YYAPI_TOKENTYPE YYAPI_TOKENNAME = YYAPI_TOKENNONE; #if defined(YYAPI_VALUETYPE) // YYSTATIC YYAPI_VALUETYPE YYAPI_VALUENAME; FIX #endif YYSTATIC int yynerrs = 0; /* number of errors */ YYSTATIC short yyerrflag = 0; /* error recovery flag */ #endif #ifdef YYRECOVER /* ** yyscpy : copy f onto t and return a ptr to the null terminator at the ** end of t. */ YYSTATIC char *yyscpy(register char*t, register char*f) { while(*t = *f++) t++; return(t); /* ptr to the null char */ } #endif #ifndef YYNEAR #define YYNEAR #endif #ifndef YYPASCAL #define YYPASCAL #endif #ifndef YYLOCAL #define YYLOCAL #endif #if ! defined YYPARSER #define YYPARSER yyparse #endif #if ! defined YYLEX #define YYLEX yylex #endif #if defined(YYRECURSIVE) YYSTATIC YYAPI_TOKENTYPE YYAPI_TOKENNAME = YYAPI_TOKENNONE; #if defined(YYAPI_VALUETYPE) YYSTATIC YYAPI_VALUETYPE YYAPI_VALUENAME; #endif YYSTATIC int yynerrs = 0; /* number of errors */ YYSTATIC short yyerrflag = 0; /* error recovery flag */ YYSTATIC short yyn; YYSTATIC short yystate = 0; YYSTATIC short *yyps= &yys[-1]; YYSTATIC YYSTYPE *yypv= &yyv[-1]; YYSTATIC short yyj; YYSTATIC short yym; #endif #pragma warning(disable:102) YYLOCAL YYNEAR YYPASCAL YYPARSER() { #if ! defined(YYRECURSIVE) register short yyn; short yystate, *yyps; YYSTYPE *yypv; short yyj, yym; YYAPI_TOKENNAME = YYAPI_TOKENNONE; yystate = 0; #ifdef _PREFAST_ #pragma warning(push) #pragma warning(disable:6200) // Index '-1' is out of valid index range...for non-stack buffer... #endif yyps= &yys[-1]; yypv= &yyv[-1]; #ifdef _PREFAST_ #pragma warning(pop) #endif #endif #ifdef YYDUMP yydumpinfo(); #endif yystack: /* put a state and value onto the stack */ #ifdef YYDEBUG if(YYAPI_TOKENNAME == YYAPI_TOKENNONE) { yyprintf( "state %d, token # '%d'\n", yystate, -1, 0 ); } else { yyprintf( "state %d, token # '%s'\n", yystate, YYAPI_TOKENSTR(YYAPI_TOKENNAME), 0 ); } #endif if( ++yyps > &yys[YYMAXDEPTH] ) { yyerror( "yacc stack overflow" ); return(1); } *yyps = yystate; ++yypv; *yypv = yyval; yynewstate: yyn = YYPACT[yystate]; if( yyn <= YYFLAG ) { /* simple state, no lookahead */ goto yydefault; } if( YYAPI_TOKENNAME == YYAPI_TOKENNONE ) { /* need a lookahead */ YYAPI_TOKENNAME = YYLEX(); YYAPI_CALLAFTERYYLEX(YYAPI_TOKENNAME); } if( ((yyn += YYAPI_TOKENEME(YYAPI_TOKENNAME)) < 0) || (yyn >= YYLAST) ) { goto yydefault; } if( YYCHK[ yyn = YYACT[ yyn ] ] == YYAPI_TOKENEME(YYAPI_TOKENNAME) ) { /* valid shift */ yyval = YYAPI_VALUEOF(YYAPI_VALUENAME); yystate = yyn; yyprintf( "SHIFT: saw token '%s', now in state %4d\n", YYAPI_TOKENSTR(YYAPI_TOKENNAME), yystate, 0 ); YYAPI_TOKENNAME = YYAPI_TOKENNONE; if( yyerrflag > 0 ) { --yyerrflag; } goto yystack; } yydefault: /* default state action */ if( (yyn = YYDEF[yystate]) == -2 ) { register YYCONST short *yyxi; if( YYAPI_TOKENNAME == YYAPI_TOKENNONE ) { YYAPI_TOKENNAME = YYLEX(); YYAPI_CALLAFTERYYLEX(YYAPI_TOKENNAME); yyprintf("LOOKAHEAD: token '%s'\n", YYAPI_TOKENSTR(YYAPI_TOKENNAME), 0, 0); } /* ** search exception table, we find a -1 followed by the current state. ** if we find one, we'll look through terminal,state pairs. if we find ** a terminal which matches the current one, we have a match. ** the exception table is when we have a reduce on a terminal. */ #if YYOPTTIME yyxi = yyexca + yyexcaind[yystate]; while(( *yyxi != YYAPI_TOKENEME(YYAPI_TOKENNAME) ) && ( *yyxi >= 0 )){ yyxi += 2; } #else for(yyxi = yyexca; (*yyxi != (-1)) || (yyxi[1] != yystate); yyxi += 2 ) { ; /* VOID */ } while( *(yyxi += 2) >= 0 ){ if( *yyxi == YYAPI_TOKENEME(YYAPI_TOKENNAME) ) { break; } } #endif if( (yyn = yyxi[1]) < 0 ) { return(0); /* accept */ } } if( yyn == 0 ){ /* error */ /* error ... attempt to resume parsing */ switch( yyerrflag ){ case 0: /* brand new error */ #ifdef YYRECOVER { register int i,j; for(i = 0; (yyrecover[i] != -1000) && (yystate > yyrecover[i]); i += 3 ) { ; } if(yystate == yyrecover[i]) { yyprintf("recovered, from state %d to state %d on token # %d\n", yystate,yyrecover[i+2],yyrecover[i+1] ); j = yyrecover[i + 1]; if(j < 0) { /* ** here we have one of the injection set, so we're not quite ** sure that the next valid thing will be a shift. so we'll ** count it as an error and continue. ** actually we're not absolutely sure that the next token ** we were supposed to get is the one when j > 0. for example, ** for(+) {;} error recovery with yyerrflag always set, stops ** after inserting one ; before the +. at the point of the +, ** we're pretty sure the caller wants a 'for' loop. without ** setting the flag, when we're almost absolutely sure, we'll ** give them one, since the only thing we can shift on this ** error is after finding an expression followed by a + */ yyerrflag++; j = -j; } if(yyerrflag <= 1) { /* only on first insertion */ yyrecerr(YYAPI_TOKENNAME, j); /* what was, what should be first */ } yyval = yyeval(j); yystate = yyrecover[i + 2]; goto yystack; } } #endif yyerror("syntax error"); yyerrlab: ++yynerrs; FALLTHROUGH; case 1: case 2: /* incompletely recovered error ... try again */ yyerrflag = 3; /* find a state where "error" is a legal shift action */ while ( yyps >= yys ) { yyn = YYPACT[*yyps] + YYERRCODE; if( yyn>= 0 && yyn < YYLAST && YYCHK[YYACT[yyn]] == YYERRCODE ){ yystate = YYACT[yyn]; /* simulate a shift of "error" */ yyprintf( "SHIFT 'error': now in state %4d\n", yystate, 0, 0 ); goto yystack; } yyn = YYPACT[*yyps]; /* the current yyps has no shift onn "error", pop stack */ yyprintf( "error recovery pops state %4d, uncovers %4d\n", *yyps, yyps[-1], 0 ); --yyps; --yypv; } /* there is no state on the stack with an error shift ... abort */ yyabort: return(1); case 3: /* no shift yet; clobber input char */ yyprintf( "error recovery discards token '%s'\n", YYAPI_TOKENSTR(YYAPI_TOKENNAME), 0, 0 ); if( YYAPI_TOKENEME(YYAPI_TOKENNAME) == 0 ) goto yyabort; /* don't discard EOF, quit */ YYAPI_TOKENNAME = YYAPI_TOKENNONE; goto yynewstate; /* try again in the same state */ } } /* reduction by production yyn */ yyreduce: { register YYSTYPE *yypvt; yypvt = yypv; yyps -= YYR2[yyn]; yypv -= YYR2[yyn]; yyval = yypv[1]; yyprintf("REDUCE: rule %4d, popped %2d tokens, uncovered state %4d, ",yyn, YYR2[yyn], *yyps); yym = yyn; yyn = YYR1[yyn]; /* consult goto table to find next state */ yyj = YYPGO[yyn] + *yyps + 1; if( (yyj >= YYLAST) || (YYCHK[ yystate = YYACT[yyj] ] != -yyn) ) { yystate = YYACT[YYPGO[yyn]]; } yyprintf("goto state %4d\n", yystate, 0, 0); #ifdef YYDUMP yydumpinfo(); #endif switch(yym){ case 3: #line 194 "asmparse.y" { PASM->EndClass(); } break; case 4: #line 195 "asmparse.y" { PASM->EndNameSpace(); } break; case 5: #line 196 "asmparse.y" { if(PASM->m_pCurMethod->m_ulLines[1] ==0) { PASM->m_pCurMethod->m_ulLines[1] = PASM->m_ulCurLine; PASM->m_pCurMethod->m_ulColumns[1]=PASM->m_ulCurColumn;} PASM->EndMethod(); } break; case 12: #line 206 "asmparse.y" { PASMM->EndAssembly(); } break; case 13: #line 207 "asmparse.y" { PASMM->EndAssembly(); } break; case 14: #line 208 "asmparse.y" { PASMM->EndComType(); } break; case 15: #line 209 "asmparse.y" { PASMM->EndManifestRes(); } break; case 19: #line 213 "asmparse.y" { #ifdef _PREFAST_ #pragma warning(push) #pragma warning(disable:22011) // Suppress PREFast warning about integer overflow/underflow #endif PASM->m_dwSubsystem = yypvt[-0].int32; #ifdef _PREFAST_ #pragma warning(pop) #endif } break; case 20: #line 223 "asmparse.y" { PASM->m_dwComImageFlags = yypvt[-0].int32; } break; case 21: #line 224 "asmparse.y" { PASM->m_dwFileAlignment = yypvt[-0].int32; if((yypvt[-0].int32 & (yypvt[-0].int32 - 1))||(yypvt[-0].int32 < 0x200)||(yypvt[-0].int32 > 0x10000)) PASM->report->error("Invalid file alignment, must be power of 2 from 0x200 to 0x10000\n");} break; case 22: #line 227 "asmparse.y" { PASM->m_stBaseAddress = (ULONGLONG)(*(yypvt[-0].int64)); delete yypvt[-0].int64; if(PASM->m_stBaseAddress & 0xFFFF) PASM->report->error("Invalid image base, must be 0x10000-aligned\n");} break; case 23: #line 230 "asmparse.y" { PASM->m_stSizeOfStackReserve = (size_t)(*(yypvt[-0].int64)); delete yypvt[-0].int64; } break; case 28: #line 235 "asmparse.y" { PASM->m_fIsMscorlib = TRUE; } break; case 31: #line 242 "asmparse.y" { yyval.binstr = yypvt[-0].binstr; } break; case 32: #line 243 "asmparse.y" { yyval.binstr = yypvt[-2].binstr; yyval.binstr->append(yypvt[-0].binstr); delete yypvt[-0].binstr; } break; case 33: #line 246 "asmparse.y" { LPCSTRToGuid(yypvt[-0].string,&(PASM->m_guidLang)); } break; case 34: #line 247 "asmparse.y" { LPCSTRToGuid(yypvt[-2].string,&(PASM->m_guidLang)); LPCSTRToGuid(yypvt[-0].string,&(PASM->m_guidLangVendor));} break; case 35: #line 249 "asmparse.y" { LPCSTRToGuid(yypvt[-4].string,&(PASM->m_guidLang)); LPCSTRToGuid(yypvt[-2].string,&(PASM->m_guidLangVendor)); LPCSTRToGuid(yypvt[-2].string,&(PASM->m_guidDoc));} break; case 36: #line 254 "asmparse.y" { yyval.string = yypvt[-0].string; } break; case 37: #line 255 "asmparse.y" { yyval.string = yypvt[-0].string; } break; case 38: #line 258 "asmparse.y" { yyval.string = yypvt[-0].string; } break; case 39: #line 259 "asmparse.y" { yyval.string = yypvt[-0].string; } break; case 40: #line 260 "asmparse.y" { yyval.string = newStringWDel(yypvt[-2].string, '.', yypvt[-0].string); } break; case 41: #line 263 "asmparse.y" { yyval.int32 = yypvt[-0].int32; } break; case 42: #line 266 "asmparse.y" { yyval.int64 = yypvt[-0].int64; } break; case 43: #line 267 "asmparse.y" { yyval.int64 = neg ? new __int64(yypvt[-0].int32) : new __int64((unsigned)yypvt[-0].int32); } break; case 44: #line 270 "asmparse.y" { yyval.float64 = yypvt[-0].float64; } break; case 45: #line 271 "asmparse.y" { float f; *((__int32*) (&f)) = yypvt[-1].int32; yyval.float64 = new double(f); } break; case 46: #line 272 "asmparse.y" { yyval.float64 = (double*) yypvt[-1].int64; } break; case 47: #line 276 "asmparse.y" { PASM->AddTypeDef(yypvt[-2].binstr,yypvt[-0].string); } break; case 48: #line 277 "asmparse.y" { PASM->AddTypeDef(yypvt[-2].token,yypvt[-0].string); } break; case 49: #line 278 "asmparse.y" { PASM->AddTypeDef(yypvt[-2].token,yypvt[-0].string); } break; case 50: #line 279 "asmparse.y" { yypvt[-2].cad->tkOwner = 0; PASM->AddTypeDef(yypvt[-2].cad,yypvt[-0].string); } break; case 51: #line 280 "asmparse.y" { PASM->AddTypeDef(yypvt[-2].cad,yypvt[-0].string); } break; case 52: #line 285 "asmparse.y" { DefineVar(yypvt[-0].string, NULL); } break; case 53: #line 286 "asmparse.y" { DefineVar(yypvt[-1].string, yypvt[-0].binstr); } break; case 54: #line 287 "asmparse.y" { UndefVar(yypvt[-0].string); } break; case 55: #line 288 "asmparse.y" { SkipToken = !IsVarDefined(yypvt[-0].string); IfEndif++; } break; case 56: #line 291 "asmparse.y" { SkipToken = IsVarDefined(yypvt[-0].string); IfEndif++; } break; case 57: #line 294 "asmparse.y" { if(IfEndif == 1) SkipToken = !SkipToken;} break; case 58: #line 295 "asmparse.y" { if(IfEndif == 0) PASM->report->error("Unmatched #endif\n"); else IfEndif--; } break; case 59: #line 299 "asmparse.y" { _ASSERTE(!"yylex should have dealt with this"); } break; case 60: #line 300 "asmparse.y" { } break; case 61: #line 304 "asmparse.y" { yyval.cad = new CustomDescr(PASM->m_tkCurrentCVOwner, yypvt[-0].token, NULL); } break; case 62: #line 305 "asmparse.y" { yyval.cad = new CustomDescr(PASM->m_tkCurrentCVOwner, yypvt[-2].token, yypvt[-0].binstr); } break; case 63: #line 306 "asmparse.y" { yyval.cad = new CustomDescr(PASM->m_tkCurrentCVOwner, yypvt[-4].token, yypvt[-1].binstr); } break; case 64: #line 307 "asmparse.y" { yyval.cad = new CustomDescr(PASM->m_tkCurrentCVOwner, yypvt[-2].int32, yypvt[-1].binstr); } break; case 65: #line 310 "asmparse.y" { yyval.cad = new CustomDescr(yypvt[-2].token, yypvt[-0].token, NULL); } break; case 66: #line 311 "asmparse.y" { yyval.cad = new CustomDescr(yypvt[-4].token, yypvt[-2].token, yypvt[-0].binstr); } break; case 67: #line 313 "asmparse.y" { yyval.cad = new CustomDescr(yypvt[-6].token, yypvt[-4].token, yypvt[-1].binstr); } break; case 68: #line 314 "asmparse.y" { yyval.cad = new CustomDescr(PASM->m_tkCurrentCVOwner, yypvt[-2].int32, yypvt[-1].binstr); } break; case 69: #line 317 "asmparse.y" { yyval.int32 = yypvt[-2].token; bParsingByteArray = TRUE; } break; case 70: #line 321 "asmparse.y" { PASM->m_pCustomDescrList = NULL; PASM->m_tkCurrentCVOwner = yypvt[-4].token; yyval.int32 = yypvt[-2].token; bParsingByteArray = TRUE; } break; case 71: #line 326 "asmparse.y" { yyval.token = yypvt[-0].token; } break; case 72: #line 329 "asmparse.y" { yyval.token = yypvt[-0].token; } break; case 73: #line 330 "asmparse.y" { yyval.token = yypvt[-0].token; } break; case 74: #line 334 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->appendInt16(VAL16(nCustomBlobNVPairs)); yyval.binstr->append(yypvt[-0].binstr); nCustomBlobNVPairs = 0; } break; case 75: #line 340 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt16(VAL16(0x0001)); } break; case 76: #line 341 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; AppendFieldToCustomBlob(yyval.binstr,yypvt[-0].binstr); } break; case 77: #line 343 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; } break; case 78: #line 346 "asmparse.y" { yyval.binstr = new BinStr(); } break; case 79: #line 348 "asmparse.y" { yyval.binstr = yypvt[-5].binstr; yyval.binstr->appendInt8(yypvt[-4].int32); yyval.binstr->append(yypvt[-3].binstr); AppendStringWithLength(yyval.binstr,yypvt[-2].string); AppendFieldToCustomBlob(yyval.binstr,yypvt[-0].binstr); nCustomBlobNVPairs++; } break; case 80: #line 353 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; } break; case 81: #line 356 "asmparse.y" { yyval.int32 = SERIALIZATION_TYPE_FIELD; } break; case 82: #line 357 "asmparse.y" { yyval.int32 = SERIALIZATION_TYPE_PROPERTY; } break; case 83: #line 360 "asmparse.y" { if(yypvt[-0].cad->tkOwner && !yypvt[-0].cad->tkInterfacePair) PASM->DefineCV(yypvt[-0].cad); else if(PASM->m_pCustomDescrList) PASM->m_pCustomDescrList->PUSH(yypvt[-0].cad); } break; case 84: #line 364 "asmparse.y" { PASM->DefineCV(yypvt[-0].cad); } break; case 85: #line 365 "asmparse.y" { CustomDescr* pNew = new CustomDescr(yypvt[-0].tdd->m_pCA); if(pNew->tkOwner == 0) pNew->tkOwner = PASM->m_tkCurrentCVOwner; if(pNew->tkOwner) PASM->DefineCV(pNew); else if(PASM->m_pCustomDescrList) PASM->m_pCustomDescrList->PUSH(pNew); } break; case 86: #line 373 "asmparse.y" { yyval.binstr = yypvt[-0].binstr; } break; case 87: #line 374 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(SERIALIZATION_TYPE_TYPE); } break; case 88: #line 375 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(SERIALIZATION_TYPE_TAGGED_OBJECT); } break; case 89: #line 376 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(SERIALIZATION_TYPE_ENUM); AppendStringWithLength(yyval.binstr,yypvt[-0].string); } break; case 90: #line 378 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(SERIALIZATION_TYPE_ENUM); AppendStringWithLength(yyval.binstr,PASM->ReflectionNotation(yypvt[-0].token)); } break; case 91: #line 380 "asmparse.y" { yyval.binstr = yypvt[-2].binstr; yyval.binstr->insertInt8(ELEMENT_TYPE_SZARRAY); } break; case 92: #line 385 "asmparse.y" { PASMM->SetModuleName(NULL); PASM->m_tkCurrentCVOwner=1; } break; case 93: #line 386 "asmparse.y" { PASMM->SetModuleName(yypvt[-0].string); PASM->m_tkCurrentCVOwner=1; } break; case 94: #line 387 "asmparse.y" { BinStr* pbs = new BinStr(); unsigned L = (unsigned)strlen(yypvt[-0].string); memcpy((char*)(pbs->getBuff(L)),yypvt[-0].string,L); PASM->EmitImport(pbs); delete pbs;} break; case 95: #line 394 "asmparse.y" { /*PASM->SetDataSection(); PASM->EmitDataLabel($7);*/ PASM->m_VTFList.PUSH(new VTFEntry((USHORT)yypvt[-4].int32, (USHORT)yypvt[-2].int32, yypvt[-0].string)); } break; case 96: #line 398 "asmparse.y" { yyval.int32 = 0; } break; case 97: #line 399 "asmparse.y" { yyval.int32 = yypvt[-1].int32 | COR_VTABLE_32BIT; } break; case 98: #line 400 "asmparse.y" { yyval.int32 = yypvt[-1].int32 | COR_VTABLE_64BIT; } break; case 99: #line 401 "asmparse.y" { yyval.int32 = yypvt[-1].int32 | COR_VTABLE_FROM_UNMANAGED; } break; case 100: #line 402 "asmparse.y" { yyval.int32 = yypvt[-1].int32 | COR_VTABLE_CALL_MOST_DERIVED; } break; case 101: #line 403 "asmparse.y" { yyval.int32 = yypvt[-1].int32 | COR_VTABLE_FROM_UNMANAGED_RETAIN_APPDOMAIN; } break; case 102: #line 406 "asmparse.y" { PASM->m_pVTable = yypvt[-1].binstr; } break; case 103: #line 409 "asmparse.y" { bParsingByteArray = TRUE; } break; case 104: #line 413 "asmparse.y" { PASM->StartNameSpace(yypvt[-0].string); } break; case 105: #line 416 "asmparse.y" { newclass = TRUE; } break; case 106: #line 419 "asmparse.y" { if(yypvt[-0].typarlist) FixupConstraints(); PASM->StartClass(yypvt[-1].string, yypvt[-2].classAttr, yypvt[-0].typarlist); TyParFixupList.RESET(false); newclass = FALSE; } break; case 107: #line 425 "asmparse.y" { PASM->AddClass(); } break; case 108: #line 428 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) 0; } break; case 109: #line 429 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) ((yypvt[-1].classAttr & ~tdVisibilityMask) | tdPublic); } break; case 110: #line 430 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) ((yypvt[-1].classAttr & ~tdVisibilityMask) | tdNotPublic); } break; case 111: #line 431 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) (yypvt[-1].classAttr | 0x80000000 | tdSealed); } break; case 112: #line 432 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) (yypvt[-1].classAttr | 0x40000000); } break; case 113: #line 433 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) (yypvt[-1].classAttr | tdInterface | tdAbstract); } break; case 114: #line 434 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) (yypvt[-1].classAttr | tdSealed); } break; case 115: #line 435 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) (yypvt[-1].classAttr | tdAbstract); } break; case 116: #line 436 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) ((yypvt[-1].classAttr & ~tdLayoutMask) | tdAutoLayout); } break; case 117: #line 437 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) ((yypvt[-1].classAttr & ~tdLayoutMask) | tdSequentialLayout); } break; case 118: #line 438 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) ((yypvt[-1].classAttr & ~tdLayoutMask) | tdExplicitLayout); } break; case 119: #line 439 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) ((yypvt[-1].classAttr & ~tdStringFormatMask) | tdAnsiClass); } break; case 120: #line 440 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) ((yypvt[-1].classAttr & ~tdStringFormatMask) | tdUnicodeClass); } break; case 121: #line 441 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) ((yypvt[-1].classAttr & ~tdStringFormatMask) | tdAutoClass); } break; case 122: #line 442 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) (yypvt[-1].classAttr | tdImport); } break; case 123: #line 443 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) (yypvt[-1].classAttr | tdSerializable); } break; case 124: #line 444 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) (yypvt[-1].classAttr | tdWindowsRuntime); } break; case 125: #line 445 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) ((yypvt[-2].classAttr & ~tdVisibilityMask) | tdNestedPublic); } break; case 126: #line 446 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) ((yypvt[-2].classAttr & ~tdVisibilityMask) | tdNestedPrivate); } break; case 127: #line 447 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) ((yypvt[-2].classAttr & ~tdVisibilityMask) | tdNestedFamily); } break; case 128: #line 448 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) ((yypvt[-2].classAttr & ~tdVisibilityMask) | tdNestedAssembly); } break; case 129: #line 449 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) ((yypvt[-2].classAttr & ~tdVisibilityMask) | tdNestedFamANDAssem); } break; case 130: #line 450 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) ((yypvt[-2].classAttr & ~tdVisibilityMask) | tdNestedFamORAssem); } break; case 131: #line 451 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) (yypvt[-1].classAttr | tdBeforeFieldInit); } break; case 132: #line 452 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) (yypvt[-1].classAttr | tdSpecialName); } break; case 133: #line 453 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) (yypvt[-1].classAttr); } break; case 134: #line 454 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) (yypvt[-1].int32); } break; case 136: #line 458 "asmparse.y" { PASM->m_crExtends = yypvt[-0].token; } break; case 141: #line 469 "asmparse.y" { PASM->AddToImplList(yypvt[-0].token); } break; case 142: #line 470 "asmparse.y" { PASM->AddToImplList(yypvt[-0].token); } break; case 143: #line 474 "asmparse.y" { yyval.binstr = new BinStr(); } break; case 144: #line 475 "asmparse.y" { yyval.binstr = yypvt[-0].binstr; } break; case 145: #line 478 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt32(yypvt[-0].token); } break; case 146: #line 479 "asmparse.y" { yyval.binstr = yypvt[-2].binstr; yyval.binstr->appendInt32(yypvt[-0].token); } break; case 147: #line 482 "asmparse.y" { yyval.typarlist = NULL; PASM->m_TyParList = NULL;} break; case 148: #line 483 "asmparse.y" { yyval.typarlist = yypvt[-1].typarlist; PASM->m_TyParList = yypvt[-1].typarlist;} break; case 149: #line 486 "asmparse.y" { yyval.int32 = gpCovariant; } break; case 150: #line 487 "asmparse.y" { yyval.int32 = gpContravariant; } break; case 151: #line 488 "asmparse.y" { yyval.int32 = gpReferenceTypeConstraint; } break; case 152: #line 489 "asmparse.y" { yyval.int32 = gpNotNullableValueTypeConstraint; } break; case 153: #line 490 "asmparse.y" { yyval.int32 = gpDefaultConstructorConstraint; } break; case 154: #line 493 "asmparse.y" { yyval.int32 = 0; } break; case 155: #line 494 "asmparse.y" { yyval.int32 = yypvt[-1].int32 | yypvt[-0].int32; } break; case 156: #line 497 "asmparse.y" {yyval.typarlist = new TyParList(yypvt[-3].int32, yypvt[-2].binstr, yypvt[-1].string, yypvt[-0].typarlist);} break; case 157: #line 498 "asmparse.y" {yyval.typarlist = new TyParList(yypvt[-2].int32, NULL, yypvt[-1].string, yypvt[-0].typarlist);} break; case 158: #line 501 "asmparse.y" { yyval.typarlist = NULL; } break; case 159: #line 502 "asmparse.y" { yyval.typarlist = yypvt[-0].typarlist; } break; case 160: #line 505 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; } break; case 161: #line 508 "asmparse.y" { yyval.int32= 0; } break; case 162: #line 509 "asmparse.y" { yyval.int32 = yypvt[-0].int32; } break; case 163: #line 512 "asmparse.y" { yyval.int32 = yypvt[-2].int32; } break; case 164: #line 516 "asmparse.y" { if(PASM->m_pCurMethod->m_ulLines[1] ==0) { PASM->m_pCurMethod->m_ulLines[1] = PASM->m_ulCurLine; PASM->m_pCurMethod->m_ulColumns[1]=PASM->m_ulCurColumn;} PASM->EndMethod(); } break; case 165: #line 520 "asmparse.y" { PASM->EndClass(); } break; case 166: #line 521 "asmparse.y" { PASM->EndEvent(); } break; case 167: #line 522 "asmparse.y" { PASM->EndProp(); } break; case 173: #line 528 "asmparse.y" { PASM->m_pCurClass->m_ulSize = yypvt[-0].int32; } break; case 174: #line 529 "asmparse.y" { PASM->m_pCurClass->m_ulPack = yypvt[-0].int32; } break; case 175: #line 530 "asmparse.y" { PASMM->EndComType(); } break; case 176: #line 532 "asmparse.y" { BinStr *sig1 = parser->MakeSig(yypvt[-7].int32, yypvt[-6].binstr, yypvt[-1].binstr); BinStr *sig2 = new BinStr(); sig2->append(sig1); PASM->AddMethodImpl(yypvt[-11].token,yypvt[-9].string,sig1,yypvt[-5].token,yypvt[-3].string,sig2); PASM->ResetArgNameList(); } break; case 177: #line 538 "asmparse.y" { PASM->AddMethodImpl(yypvt[-17].token,yypvt[-15].string, (yypvt[-14].int32==0 ? parser->MakeSig(yypvt[-19].int32,yypvt[-18].binstr,yypvt[-12].binstr) : parser->MakeSig(yypvt[-19].int32| IMAGE_CEE_CS_CALLCONV_GENERIC,yypvt[-18].binstr,yypvt[-12].binstr,yypvt[-14].int32)), yypvt[-6].token,yypvt[-4].string, (yypvt[-3].int32==0 ? parser->MakeSig(yypvt[-8].int32,yypvt[-7].binstr,yypvt[-1].binstr) : parser->MakeSig(yypvt[-8].int32| IMAGE_CEE_CS_CALLCONV_GENERIC,yypvt[-7].binstr,yypvt[-1].binstr,yypvt[-3].int32))); PASM->ResetArgNameList(); } break; case 180: #line 548 "asmparse.y" { if((yypvt[-1].int32 > 0) && (yypvt[-1].int32 <= (int)PASM->m_pCurClass->m_NumTyPars)) PASM->m_pCustomDescrList = PASM->m_pCurClass->m_TyPars[yypvt[-1].int32-1].CAList(); else PASM->report->error("Type parameter index out of range\n"); } break; case 181: #line 553 "asmparse.y" { int n = PASM->m_pCurClass->FindTyPar(yypvt[-0].string); if(n >= 0) PASM->m_pCustomDescrList = PASM->m_pCurClass->m_TyPars[n].CAList(); else PASM->report->error("Type parameter '%s' undefined\n",yypvt[-0].string); } break; case 182: #line 559 "asmparse.y" { PASM->AddGenericParamConstraint(yypvt[-3].int32, 0, yypvt[-0].token); } break; case 183: #line 560 "asmparse.y" { PASM->AddGenericParamConstraint(0, yypvt[-2].string, yypvt[-0].token); } break; case 184: #line 561 "asmparse.y" { yypvt[-0].cad->tkInterfacePair = yypvt[-1].token; if(PASM->m_pCustomDescrList) PASM->m_pCustomDescrList->PUSH(yypvt[-0].cad); } break; case 185: #line 569 "asmparse.y" { yypvt[-3].binstr->insertInt8(IMAGE_CEE_CS_CALLCONV_FIELD); PASM->AddField(yypvt[-2].string, yypvt[-3].binstr, yypvt[-4].fieldAttr, yypvt[-1].string, yypvt[-0].binstr, yypvt[-5].int32); } break; case 186: #line 573 "asmparse.y" { yyval.fieldAttr = (CorFieldAttr) 0; } break; case 187: #line 574 "asmparse.y" { yyval.fieldAttr = (CorFieldAttr) (yypvt[-1].fieldAttr | fdStatic); } break; case 188: #line 575 "asmparse.y" { yyval.fieldAttr = (CorFieldAttr) ((yypvt[-1].fieldAttr & ~mdMemberAccessMask) | fdPublic); } break; case 189: #line 576 "asmparse.y" { yyval.fieldAttr = (CorFieldAttr) ((yypvt[-1].fieldAttr & ~mdMemberAccessMask) | fdPrivate); } break; case 190: #line 577 "asmparse.y" { yyval.fieldAttr = (CorFieldAttr) ((yypvt[-1].fieldAttr & ~mdMemberAccessMask) | fdFamily); } break; case 191: #line 578 "asmparse.y" { yyval.fieldAttr = (CorFieldAttr) (yypvt[-1].fieldAttr | fdInitOnly); } break; case 192: #line 579 "asmparse.y" { yyval.fieldAttr = yypvt[-1].fieldAttr; } break; case 193: #line 580 "asmparse.y" { yyval.fieldAttr = (CorFieldAttr) (yypvt[-1].fieldAttr | fdSpecialName); } break; case 194: #line 593 "asmparse.y" { PASM->m_pMarshal = yypvt[-1].binstr; } break; case 195: #line 594 "asmparse.y" { yyval.fieldAttr = (CorFieldAttr) ((yypvt[-1].fieldAttr & ~mdMemberAccessMask) | fdAssembly); } break; case 196: #line 595 "asmparse.y" { yyval.fieldAttr = (CorFieldAttr) ((yypvt[-1].fieldAttr & ~mdMemberAccessMask) | fdFamANDAssem); } break; case 197: #line 596 "asmparse.y" { yyval.fieldAttr = (CorFieldAttr) ((yypvt[-1].fieldAttr & ~mdMemberAccessMask) | fdFamORAssem); } break; case 198: #line 597 "asmparse.y" { yyval.fieldAttr = (CorFieldAttr) ((yypvt[-1].fieldAttr & ~mdMemberAccessMask) | fdPrivateScope); } break; case 199: #line 598 "asmparse.y" { yyval.fieldAttr = (CorFieldAttr) (yypvt[-1].fieldAttr | fdLiteral); } break; case 200: #line 599 "asmparse.y" { yyval.fieldAttr = (CorFieldAttr) (yypvt[-1].fieldAttr | fdNotSerialized); } break; case 201: #line 600 "asmparse.y" { yyval.fieldAttr = (CorFieldAttr) (yypvt[-1].int32); } break; case 202: #line 603 "asmparse.y" { yyval.string = 0; } break; case 203: #line 604 "asmparse.y" { yyval.string = yypvt[-0].string; } break; case 204: #line 607 "asmparse.y" { yyval.binstr = NULL; } break; case 205: #line 608 "asmparse.y" { yyval.binstr = yypvt[-0].binstr; } break; case 206: #line 611 "asmparse.y" { yyval.int32 = 0xFFFFFFFF; } break; case 207: #line 612 "asmparse.y" { yyval.int32 = yypvt[-1].int32; } break; case 208: #line 617 "asmparse.y" { PASM->ResetArgNameList(); if (yypvt[-3].binstr == NULL) { if((iCallConv)&&((yypvt[-8].int32 & iCallConv) != iCallConv)) parser->warn("'instance' added to method's calling convention\n"); yyval.token = PASM->MakeMemberRef(yypvt[-6].token, yypvt[-4].string, parser->MakeSig(yypvt[-8].int32|iCallConv, yypvt[-7].binstr, yypvt[-1].binstr)); } else { mdToken mr; if((iCallConv)&&((yypvt[-8].int32 & iCallConv) != iCallConv)) parser->warn("'instance' added to method's calling convention\n"); mr = PASM->MakeMemberRef(yypvt[-6].token, yypvt[-4].string, parser->MakeSig(yypvt[-8].int32 | IMAGE_CEE_CS_CALLCONV_GENERIC|iCallConv, yypvt[-7].binstr, yypvt[-1].binstr, corCountArgs(yypvt[-3].binstr))); yyval.token = PASM->MakeMethodSpec(mr, parser->MakeSig(IMAGE_CEE_CS_CALLCONV_INSTANTIATION, 0, yypvt[-3].binstr)); } } break; case 209: #line 634 "asmparse.y" { PASM->ResetArgNameList(); if((iCallConv)&&((yypvt[-8].int32 & iCallConv) != iCallConv)) parser->warn("'instance' added to method's calling convention\n"); yyval.token = PASM->MakeMemberRef(yypvt[-6].token, yypvt[-4].string, parser->MakeSig(yypvt[-8].int32 | IMAGE_CEE_CS_CALLCONV_GENERIC|iCallConv, yypvt[-7].binstr, yypvt[-1].binstr, yypvt[-3].int32)); } break; case 210: #line 640 "asmparse.y" { PASM->ResetArgNameList(); if (yypvt[-3].binstr == NULL) { if((iCallConv)&&((yypvt[-6].int32 & iCallConv) != iCallConv)) parser->warn("'instance' added to method's calling convention\n"); yyval.token = PASM->MakeMemberRef(mdTokenNil, yypvt[-4].string, parser->MakeSig(yypvt[-6].int32|iCallConv, yypvt[-5].binstr, yypvt[-1].binstr)); } else { mdToken mr; if((iCallConv)&&((yypvt[-6].int32 & iCallConv) != iCallConv)) parser->warn("'instance' added to method's calling convention\n"); mr = PASM->MakeMemberRef(mdTokenNil, yypvt[-4].string, parser->MakeSig(yypvt[-6].int32 | IMAGE_CEE_CS_CALLCONV_GENERIC|iCallConv, yypvt[-5].binstr, yypvt[-1].binstr, corCountArgs(yypvt[-3].binstr))); yyval.token = PASM->MakeMethodSpec(mr, parser->MakeSig(IMAGE_CEE_CS_CALLCONV_INSTANTIATION, 0, yypvt[-3].binstr)); } } break; case 211: #line 656 "asmparse.y" { PASM->ResetArgNameList(); if((iCallConv)&&((yypvt[-6].int32 & iCallConv) != iCallConv)) parser->warn("'instance' added to method's calling convention\n"); yyval.token = PASM->MakeMemberRef(mdTokenNil, yypvt[-4].string, parser->MakeSig(yypvt[-6].int32 | IMAGE_CEE_CS_CALLCONV_GENERIC|iCallConv, yypvt[-5].binstr, yypvt[-1].binstr, yypvt[-3].int32)); } break; case 212: #line 660 "asmparse.y" { yyval.token = yypvt[-0].token; } break; case 213: #line 661 "asmparse.y" { yyval.token = yypvt[-0].tdd->m_tkTypeSpec; } break; case 214: #line 662 "asmparse.y" { yyval.token = yypvt[-0].tdd->m_tkTypeSpec; } break; case 215: #line 665 "asmparse.y" { yyval.int32 = (yypvt[-0].int32 | IMAGE_CEE_CS_CALLCONV_HASTHIS); } break; case 216: #line 666 "asmparse.y" { yyval.int32 = (yypvt[-0].int32 | IMAGE_CEE_CS_CALLCONV_EXPLICITTHIS); } break; case 217: #line 667 "asmparse.y" { yyval.int32 = yypvt[-0].int32; } break; case 218: #line 668 "asmparse.y" { yyval.int32 = yypvt[-1].int32; } break; case 219: #line 671 "asmparse.y" { yyval.int32 = IMAGE_CEE_CS_CALLCONV_DEFAULT; } break; case 220: #line 672 "asmparse.y" { yyval.int32 = IMAGE_CEE_CS_CALLCONV_DEFAULT; } break; case 221: #line 673 "asmparse.y" { yyval.int32 = IMAGE_CEE_CS_CALLCONV_VARARG; } break; case 222: #line 674 "asmparse.y" { yyval.int32 = IMAGE_CEE_CS_CALLCONV_C; } break; case 223: #line 675 "asmparse.y" { yyval.int32 = IMAGE_CEE_CS_CALLCONV_STDCALL; } break; case 224: #line 676 "asmparse.y" { yyval.int32 = IMAGE_CEE_CS_CALLCONV_THISCALL; } break; case 225: #line 677 "asmparse.y" { yyval.int32 = IMAGE_CEE_CS_CALLCONV_FASTCALL; } break; case 226: #line 678 "asmparse.y" { yyval.int32 = IMAGE_CEE_CS_CALLCONV_UNMANAGED; } break; case 227: #line 681 "asmparse.y" { yyval.token = yypvt[-1].int32; } break; case 228: #line 684 "asmparse.y" { yyval.token = yypvt[-0].token; PASM->delArgNameList(PASM->m_firstArgName); PASM->m_firstArgName = parser->m_ANSFirst.POP(); PASM->m_lastArgName = parser->m_ANSLast.POP(); PASM->SetMemberRefFixup(yypvt[-0].token,iOpcodeLen); } break; case 229: #line 690 "asmparse.y" { yypvt[-3].binstr->insertInt8(IMAGE_CEE_CS_CALLCONV_FIELD); yyval.token = PASM->MakeMemberRef(yypvt[-2].token, yypvt[-0].string, yypvt[-3].binstr); PASM->SetMemberRefFixup(yyval.token,iOpcodeLen); } break; case 230: #line 694 "asmparse.y" { yypvt[-1].binstr->insertInt8(IMAGE_CEE_CS_CALLCONV_FIELD); yyval.token = PASM->MakeMemberRef(NULL, yypvt[-0].string, yypvt[-1].binstr); PASM->SetMemberRefFixup(yyval.token,iOpcodeLen); } break; case 231: #line 697 "asmparse.y" { yyval.token = yypvt[-0].tdd->m_tkTypeSpec; PASM->SetMemberRefFixup(yyval.token,iOpcodeLen); } break; case 232: #line 699 "asmparse.y" { yyval.token = yypvt[-0].tdd->m_tkTypeSpec; PASM->SetMemberRefFixup(yyval.token,iOpcodeLen); } break; case 233: #line 701 "asmparse.y" { yyval.token = yypvt[-0].token; PASM->SetMemberRefFixup(yyval.token,iOpcodeLen); } break; case 234: #line 706 "asmparse.y" { PASM->ResetEvent(yypvt[-0].string, yypvt[-1].token, yypvt[-2].eventAttr); } break; case 235: #line 707 "asmparse.y" { PASM->ResetEvent(yypvt[-0].string, mdTypeRefNil, yypvt[-1].eventAttr); } break; case 236: #line 711 "asmparse.y" { yyval.eventAttr = (CorEventAttr) 0; } break; case 237: #line 712 "asmparse.y" { yyval.eventAttr = yypvt[-1].eventAttr; } break; case 238: #line 713 "asmparse.y" { yyval.eventAttr = (CorEventAttr) (yypvt[-1].eventAttr | evSpecialName); } break; case 241: #line 720 "asmparse.y" { PASM->SetEventMethod(0, yypvt[-0].token); } break; case 242: #line 721 "asmparse.y" { PASM->SetEventMethod(1, yypvt[-0].token); } break; case 243: #line 722 "asmparse.y" { PASM->SetEventMethod(2, yypvt[-0].token); } break; case 244: #line 723 "asmparse.y" { PASM->SetEventMethod(3, yypvt[-0].token); } break; case 249: #line 732 "asmparse.y" { PASM->ResetProp(yypvt[-4].string, parser->MakeSig((IMAGE_CEE_CS_CALLCONV_PROPERTY | (yypvt[-6].int32 & IMAGE_CEE_CS_CALLCONV_HASTHIS)),yypvt[-5].binstr,yypvt[-2].binstr), yypvt[-7].propAttr, yypvt[-0].binstr);} break; case 250: #line 737 "asmparse.y" { yyval.propAttr = (CorPropertyAttr) 0; } break; case 251: #line 738 "asmparse.y" { yyval.propAttr = yypvt[-1].propAttr; } break; case 252: #line 739 "asmparse.y" { yyval.propAttr = (CorPropertyAttr) (yypvt[-1].propAttr | prSpecialName); } break; case 255: #line 747 "asmparse.y" { PASM->SetPropMethod(0, yypvt[-0].token); } break; case 256: #line 748 "asmparse.y" { PASM->SetPropMethod(1, yypvt[-0].token); } break; case 257: #line 749 "asmparse.y" { PASM->SetPropMethod(2, yypvt[-0].token); } break; case 262: #line 757 "asmparse.y" { PASM->ResetForNextMethod(); uMethodBeginLine = PASM->m_ulCurLine; uMethodBeginColumn=PASM->m_ulCurColumn; } break; case 263: #line 763 "asmparse.y" { yyval.binstr = NULL; } break; case 264: #line 764 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; } break; case 265: #line 767 "asmparse.y" { yyval.binstr = yypvt[-0].binstr; } break; case 266: #line 768 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; } break; case 267: #line 771 "asmparse.y" { bParsingByteArray = TRUE; } break; case 268: #line 775 "asmparse.y" { BinStr* sig; if (yypvt[-5].typarlist == NULL) sig = parser->MakeSig(yypvt[-10].int32, yypvt[-8].binstr, yypvt[-3].binstr); else { FixupTyPars(yypvt[-8].binstr); sig = parser->MakeSig(yypvt[-10].int32 | IMAGE_CEE_CS_CALLCONV_GENERIC, yypvt[-8].binstr, yypvt[-3].binstr, yypvt[-5].typarlist->Count()); FixupConstraints(); } PASM->StartMethod(yypvt[-6].string, sig, yypvt[-11].methAttr, yypvt[-7].binstr, yypvt[-9].int32, yypvt[-5].typarlist); TyParFixupList.RESET(false); PASM->SetImplAttr((USHORT)yypvt[-1].implAttr); PASM->m_pCurMethod->m_ulLines[0] = uMethodBeginLine; PASM->m_pCurMethod->m_ulColumns[0]=uMethodBeginColumn; } break; case 269: #line 790 "asmparse.y" { yyval.methAttr = (CorMethodAttr) 0; } break; case 270: #line 791 "asmparse.y" { yyval.methAttr = (CorMethodAttr) (yypvt[-1].methAttr | mdStatic); } break; case 271: #line 792 "asmparse.y" { yyval.methAttr = (CorMethodAttr) ((yypvt[-1].methAttr & ~mdMemberAccessMask) | mdPublic); } break; case 272: #line 793 "asmparse.y" { yyval.methAttr = (CorMethodAttr) ((yypvt[-1].methAttr & ~mdMemberAccessMask) | mdPrivate); } break; case 273: #line 794 "asmparse.y" { yyval.methAttr = (CorMethodAttr) ((yypvt[-1].methAttr & ~mdMemberAccessMask) | mdFamily); } break; case 274: #line 795 "asmparse.y" { yyval.methAttr = (CorMethodAttr) (yypvt[-1].methAttr | mdFinal); } break; case 275: #line 796 "asmparse.y" { yyval.methAttr = (CorMethodAttr) (yypvt[-1].methAttr | mdSpecialName); } break; case 276: #line 797 "asmparse.y" { yyval.methAttr = (CorMethodAttr) (yypvt[-1].methAttr | mdVirtual); } break; case 277: #line 798 "asmparse.y" { yyval.methAttr = (CorMethodAttr) (yypvt[-1].methAttr | mdCheckAccessOnOverride); } break; case 278: #line 799 "asmparse.y" { yyval.methAttr = (CorMethodAttr) (yypvt[-1].methAttr | mdAbstract); } break; case 279: #line 800 "asmparse.y" { yyval.methAttr = (CorMethodAttr) ((yypvt[-1].methAttr & ~mdMemberAccessMask) | mdAssem); } break; case 280: #line 801 "asmparse.y" { yyval.methAttr = (CorMethodAttr) ((yypvt[-1].methAttr & ~mdMemberAccessMask) | mdFamANDAssem); } break; case 281: #line 802 "asmparse.y" { yyval.methAttr = (CorMethodAttr) ((yypvt[-1].methAttr & ~mdMemberAccessMask) | mdFamORAssem); } break; case 282: #line 803 "asmparse.y" { yyval.methAttr = (CorMethodAttr) ((yypvt[-1].methAttr & ~mdMemberAccessMask) | mdPrivateScope); } break; case 283: #line 804 "asmparse.y" { yyval.methAttr = (CorMethodAttr) (yypvt[-1].methAttr | mdHideBySig); } break; case 284: #line 805 "asmparse.y" { yyval.methAttr = (CorMethodAttr) (yypvt[-1].methAttr | mdNewSlot); } break; case 285: #line 806 "asmparse.y" { yyval.methAttr = yypvt[-1].methAttr; } break; case 286: #line 807 "asmparse.y" { yyval.methAttr = (CorMethodAttr) (yypvt[-1].methAttr | mdUnmanagedExport); } break; case 287: #line 808 "asmparse.y" { yyval.methAttr = (CorMethodAttr) (yypvt[-1].methAttr | mdRequireSecObject); } break; case 288: #line 809 "asmparse.y" { yyval.methAttr = (CorMethodAttr) (yypvt[-1].int32); } break; case 289: #line 811 "asmparse.y" { PASM->SetPinvoke(yypvt[-4].binstr,0,yypvt[-2].binstr,yypvt[-1].pinvAttr); yyval.methAttr = (CorMethodAttr) (yypvt[-7].methAttr | mdPinvokeImpl); } break; case 290: #line 814 "asmparse.y" { PASM->SetPinvoke(yypvt[-2].binstr,0,NULL,yypvt[-1].pinvAttr); yyval.methAttr = (CorMethodAttr) (yypvt[-5].methAttr | mdPinvokeImpl); } break; case 291: #line 817 "asmparse.y" { PASM->SetPinvoke(new BinStr(),0,NULL,yypvt[-1].pinvAttr); yyval.methAttr = (CorMethodAttr) (yypvt[-4].methAttr | mdPinvokeImpl); } break; case 292: #line 821 "asmparse.y" { yyval.pinvAttr = (CorPinvokeMap) 0; } break; case 293: #line 822 "asmparse.y" { yyval.pinvAttr = (CorPinvokeMap) (yypvt[-1].pinvAttr | pmNoMangle); } break; case 294: #line 823 "asmparse.y" { yyval.pinvAttr = (CorPinvokeMap) (yypvt[-1].pinvAttr | pmCharSetAnsi); } break; case 295: #line 824 "asmparse.y" { yyval.pinvAttr = (CorPinvokeMap) (yypvt[-1].pinvAttr | pmCharSetUnicode); } break; case 296: #line 825 "asmparse.y" { yyval.pinvAttr = (CorPinvokeMap) (yypvt[-1].pinvAttr | pmCharSetAuto); } break; case 297: #line 826 "asmparse.y" { yyval.pinvAttr = (CorPinvokeMap) (yypvt[-1].pinvAttr | pmSupportsLastError); } break; case 298: #line 827 "asmparse.y" { yyval.pinvAttr = (CorPinvokeMap) (yypvt[-1].pinvAttr | pmCallConvWinapi); } break; case 299: #line 828 "asmparse.y" { yyval.pinvAttr = (CorPinvokeMap) (yypvt[-1].pinvAttr | pmCallConvCdecl); } break; case 300: #line 829 "asmparse.y" { yyval.pinvAttr = (CorPinvokeMap) (yypvt[-1].pinvAttr | pmCallConvStdcall); } break; case 301: #line 830 "asmparse.y" { yyval.pinvAttr = (CorPinvokeMap) (yypvt[-1].pinvAttr | pmCallConvThiscall); } break; case 302: #line 831 "asmparse.y" { yyval.pinvAttr = (CorPinvokeMap) (yypvt[-1].pinvAttr | pmCallConvFastcall); } break; case 303: #line 832 "asmparse.y" { yyval.pinvAttr = (CorPinvokeMap) (yypvt[-3].pinvAttr | pmBestFitEnabled); } break; case 304: #line 833 "asmparse.y" { yyval.pinvAttr = (CorPinvokeMap) (yypvt[-3].pinvAttr | pmBestFitDisabled); } break; case 305: #line 834 "asmparse.y" { yyval.pinvAttr = (CorPinvokeMap) (yypvt[-3].pinvAttr | pmThrowOnUnmappableCharEnabled); } break; case 306: #line 835 "asmparse.y" { yyval.pinvAttr = (CorPinvokeMap) (yypvt[-3].pinvAttr | pmThrowOnUnmappableCharDisabled); } break; case 307: #line 836 "asmparse.y" { yyval.pinvAttr = (CorPinvokeMap) (yypvt[-1].int32); } break; case 308: #line 839 "asmparse.y" { yyval.string = newString(COR_CTOR_METHOD_NAME); } break; case 309: #line 840 "asmparse.y" { yyval.string = newString(COR_CCTOR_METHOD_NAME); } break; case 310: #line 841 "asmparse.y" { yyval.string = yypvt[-0].string; } break; case 311: #line 844 "asmparse.y" { yyval.int32 = 0; } break; case 312: #line 845 "asmparse.y" { yyval.int32 = yypvt[-3].int32 | pdIn; } break; case 313: #line 846 "asmparse.y" { yyval.int32 = yypvt[-3].int32 | pdOut; } break; case 314: #line 847 "asmparse.y" { yyval.int32 = yypvt[-3].int32 | pdOptional; } break; case 315: #line 848 "asmparse.y" { yyval.int32 = yypvt[-1].int32 + 1; } break; case 316: #line 851 "asmparse.y" { yyval.implAttr = (CorMethodImpl) (miIL | miManaged); } break; case 317: #line 852 "asmparse.y" { yyval.implAttr = (CorMethodImpl) ((yypvt[-1].implAttr & 0xFFF4) | miNative); } break; case 318: #line 853 "asmparse.y" { yyval.implAttr = (CorMethodImpl) ((yypvt[-1].implAttr & 0xFFF4) | miIL); } break; case 319: #line 854 "asmparse.y" { yyval.implAttr = (CorMethodImpl) ((yypvt[-1].implAttr & 0xFFF4) | miOPTIL); } break; case 320: #line 855 "asmparse.y" { yyval.implAttr = (CorMethodImpl) ((yypvt[-1].implAttr & 0xFFFB) | miManaged); } break; case 321: #line 856 "asmparse.y" { yyval.implAttr = (CorMethodImpl) ((yypvt[-1].implAttr & 0xFFFB) | miUnmanaged); } break; case 322: #line 857 "asmparse.y" { yyval.implAttr = (CorMethodImpl) (yypvt[-1].implAttr | miForwardRef); } break; case 323: #line 858 "asmparse.y" { yyval.implAttr = (CorMethodImpl) (yypvt[-1].implAttr | miPreserveSig); } break; case 324: #line 859 "asmparse.y" { yyval.implAttr = (CorMethodImpl) (yypvt[-1].implAttr | miRuntime); } break; case 325: #line 860 "asmparse.y" { yyval.implAttr = (CorMethodImpl) (yypvt[-1].implAttr | miInternalCall); } break; case 326: #line 861 "asmparse.y" { yyval.implAttr = (CorMethodImpl) (yypvt[-1].implAttr | miSynchronized); } break; case 327: #line 862 "asmparse.y" { yyval.implAttr = (CorMethodImpl) (yypvt[-1].implAttr | miNoInlining); } break; case 328: #line 863 "asmparse.y" { yyval.implAttr = (CorMethodImpl) (yypvt[-1].implAttr | miAggressiveInlining); } break; case 329: #line 864 "asmparse.y" { yyval.implAttr = (CorMethodImpl) (yypvt[-1].implAttr | miNoOptimization); } break; case 330: #line 865 "asmparse.y" { yyval.implAttr = (CorMethodImpl) (yypvt[-1].implAttr | miAggressiveOptimization); } break; case 331: #line 866 "asmparse.y" { yyval.implAttr = (CorMethodImpl) (yypvt[-1].int32); } break; case 332: #line 869 "asmparse.y" { PASM->delArgNameList(PASM->m_firstArgName); PASM->m_firstArgName = NULL;PASM->m_lastArgName = NULL; } break; case 335: #line 877 "asmparse.y" { PASM->EmitByte(yypvt[-0].int32); } break; case 336: #line 878 "asmparse.y" { delete PASM->m_SEHD; PASM->m_SEHD = PASM->m_SEHDstack.POP(); } break; case 337: #line 879 "asmparse.y" { PASM->EmitMaxStack(yypvt[-0].int32); } break; case 338: #line 880 "asmparse.y" { PASM->EmitLocals(parser->MakeSig(IMAGE_CEE_CS_CALLCONV_LOCAL_SIG, 0, yypvt[-1].binstr)); } break; case 339: #line 882 "asmparse.y" { PASM->EmitZeroInit(); PASM->EmitLocals(parser->MakeSig(IMAGE_CEE_CS_CALLCONV_LOCAL_SIG, 0, yypvt[-1].binstr)); } break; case 340: #line 885 "asmparse.y" { PASM->EmitEntryPoint(); } break; case 341: #line 886 "asmparse.y" { PASM->EmitZeroInit(); } break; case 344: #line 889 "asmparse.y" { PASM->AddLabel(PASM->m_CurPC,yypvt[-1].string); /*PASM->EmitLabel($1);*/ } break; case 350: #line 895 "asmparse.y" { if(PASM->m_pCurMethod->m_dwExportOrdinal == 0xFFFFFFFF) { PASM->m_pCurMethod->m_dwExportOrdinal = yypvt[-1].int32; PASM->m_pCurMethod->m_szExportAlias = NULL; if(PASM->m_pCurMethod->m_wVTEntry == 0) PASM->m_pCurMethod->m_wVTEntry = 1; if(PASM->m_pCurMethod->m_wVTSlot == 0) PASM->m_pCurMethod->m_wVTSlot = yypvt[-1].int32 + 0x8000; } else PASM->report->warn("Duplicate .export directive, ignored\n"); } break; case 351: #line 905 "asmparse.y" { if(PASM->m_pCurMethod->m_dwExportOrdinal == 0xFFFFFFFF) { PASM->m_pCurMethod->m_dwExportOrdinal = yypvt[-3].int32; PASM->m_pCurMethod->m_szExportAlias = yypvt[-0].string; if(PASM->m_pCurMethod->m_wVTEntry == 0) PASM->m_pCurMethod->m_wVTEntry = 1; if(PASM->m_pCurMethod->m_wVTSlot == 0) PASM->m_pCurMethod->m_wVTSlot = yypvt[-3].int32 + 0x8000; } else PASM->report->warn("Duplicate .export directive, ignored\n"); } break; case 352: #line 915 "asmparse.y" { PASM->m_pCurMethod->m_wVTEntry = (WORD)yypvt[-2].int32; PASM->m_pCurMethod->m_wVTSlot = (WORD)yypvt[-0].int32; } break; case 353: #line 918 "asmparse.y" { PASM->AddMethodImpl(yypvt[-2].token,yypvt[-0].string,NULL,NULL,NULL,NULL); } break; case 354: #line 921 "asmparse.y" { PASM->AddMethodImpl(yypvt[-6].token,yypvt[-4].string, (yypvt[-3].int32==0 ? parser->MakeSig(yypvt[-8].int32,yypvt[-7].binstr,yypvt[-1].binstr) : parser->MakeSig(yypvt[-8].int32| IMAGE_CEE_CS_CALLCONV_GENERIC,yypvt[-7].binstr,yypvt[-1].binstr,yypvt[-3].int32)) ,NULL,NULL,NULL); PASM->ResetArgNameList(); } break; case 356: #line 928 "asmparse.y" { if((yypvt[-1].int32 > 0) && (yypvt[-1].int32 <= (int)PASM->m_pCurMethod->m_NumTyPars)) PASM->m_pCustomDescrList = PASM->m_pCurMethod->m_TyPars[yypvt[-1].int32-1].CAList(); else PASM->report->error("Type parameter index out of range\n"); } break; case 357: #line 933 "asmparse.y" { int n = PASM->m_pCurMethod->FindTyPar(yypvt[-0].string); if(n >= 0) PASM->m_pCustomDescrList = PASM->m_pCurMethod->m_TyPars[n].CAList(); else PASM->report->error("Type parameter '%s' undefined\n",yypvt[-0].string); } break; case 358: #line 939 "asmparse.y" { PASM->m_pCurMethod->AddGenericParamConstraint(yypvt[-3].int32, 0, yypvt[-0].token); } break; case 359: #line 940 "asmparse.y" { PASM->m_pCurMethod->AddGenericParamConstraint(0, yypvt[-2].string, yypvt[-0].token); } break; case 360: #line 943 "asmparse.y" { if( yypvt[-2].int32 ) { ARG_NAME_LIST* pAN=PASM->findArg(PASM->m_pCurMethod->m_firstArgName, yypvt[-2].int32 - 1); if(pAN) { PASM->m_pCustomDescrList = &(pAN->CustDList); pAN->pValue = yypvt[-0].binstr; } else { PASM->m_pCustomDescrList = NULL; if(yypvt[-0].binstr) delete yypvt[-0].binstr; } } else { PASM->m_pCustomDescrList = &(PASM->m_pCurMethod->m_RetCustDList); PASM->m_pCurMethod->m_pRetValue = yypvt[-0].binstr; } PASM->m_tkCurrentCVOwner = 0; } break; case 361: #line 963 "asmparse.y" { PASM->m_pCurMethod->CloseScope(); } break; case 362: #line 966 "asmparse.y" { PASM->m_pCurMethod->OpenScope(); } break; case 366: #line 977 "asmparse.y" { PASM->m_SEHD->tryTo = PASM->m_CurPC; } break; case 367: #line 978 "asmparse.y" { PASM->SetTryLabels(yypvt[-2].string, yypvt[-0].string); } break; case 368: #line 979 "asmparse.y" { if(PASM->m_SEHD) {PASM->m_SEHD->tryFrom = yypvt[-2].int32; PASM->m_SEHD->tryTo = yypvt[-0].int32;} } break; case 369: #line 983 "asmparse.y" { PASM->NewSEHDescriptor(); PASM->m_SEHD->tryFrom = PASM->m_CurPC; } break; case 370: #line 988 "asmparse.y" { PASM->EmitTry(); } break; case 371: #line 989 "asmparse.y" { PASM->EmitTry(); } break; case 372: #line 990 "asmparse.y" { PASM->EmitTry(); } break; case 373: #line 991 "asmparse.y" { PASM->EmitTry(); } break; case 374: #line 995 "asmparse.y" { PASM->m_SEHD->sehHandler = PASM->m_CurPC; } break; case 375: #line 996 "asmparse.y" { PASM->SetFilterLabel(yypvt[-0].string); PASM->m_SEHD->sehHandler = PASM->m_CurPC; } break; case 376: #line 998 "asmparse.y" { PASM->m_SEHD->sehFilter = yypvt[-0].int32; PASM->m_SEHD->sehHandler = PASM->m_CurPC; } break; case 377: #line 1002 "asmparse.y" { PASM->m_SEHD->sehClause = COR_ILEXCEPTION_CLAUSE_FILTER; PASM->m_SEHD->sehFilter = PASM->m_CurPC; } break; case 378: #line 1006 "asmparse.y" { PASM->m_SEHD->sehClause = COR_ILEXCEPTION_CLAUSE_NONE; PASM->SetCatchClass(yypvt[-0].token); PASM->m_SEHD->sehHandler = PASM->m_CurPC; } break; case 379: #line 1011 "asmparse.y" { PASM->m_SEHD->sehClause = COR_ILEXCEPTION_CLAUSE_FINALLY; PASM->m_SEHD->sehHandler = PASM->m_CurPC; } break; case 380: #line 1015 "asmparse.y" { PASM->m_SEHD->sehClause = COR_ILEXCEPTION_CLAUSE_FAULT; PASM->m_SEHD->sehHandler = PASM->m_CurPC; } break; case 381: #line 1019 "asmparse.y" { PASM->m_SEHD->sehHandlerTo = PASM->m_CurPC; } break; case 382: #line 1020 "asmparse.y" { PASM->SetHandlerLabels(yypvt[-2].string, yypvt[-0].string); } break; case 383: #line 1021 "asmparse.y" { PASM->m_SEHD->sehHandler = yypvt[-2].int32; PASM->m_SEHD->sehHandlerTo = yypvt[-0].int32; } break; case 385: #line 1029 "asmparse.y" { PASM->EmitDataLabel(yypvt[-1].string); } break; case 387: #line 1033 "asmparse.y" { PASM->SetDataSection(); } break; case 388: #line 1034 "asmparse.y" { PASM->SetTLSSection(); } break; case 389: #line 1035 "asmparse.y" { PASM->SetILSection(); } break; case 394: #line 1046 "asmparse.y" { yyval.int32 = 1; } break; case 395: #line 1047 "asmparse.y" { yyval.int32 = yypvt[-1].int32; if(yypvt[-1].int32 <= 0) { PASM->report->error("Illegal item count: %d\n",yypvt[-1].int32); if(!PASM->OnErrGo) yyval.int32 = 1; }} break; case 396: #line 1052 "asmparse.y" { PASM->EmitDataString(yypvt[-1].binstr); } break; case 397: #line 1053 "asmparse.y" { PASM->EmitDD(yypvt[-1].string); } break; case 398: #line 1054 "asmparse.y" { PASM->EmitData(yypvt[-1].binstr->ptr(),yypvt[-1].binstr->length()); } break; case 399: #line 1056 "asmparse.y" { float f = (float) (*yypvt[-2].float64); float* p = new (nothrow) float[yypvt[-0].int32]; if(p != NULL) { for(int i=0; i < yypvt[-0].int32; i++) p[i] = f; PASM->EmitData(p, sizeof(float)*yypvt[-0].int32); delete yypvt[-2].float64; delete [] p; } else PASM->report->error("Out of memory emitting data block %d bytes\n", sizeof(float)*yypvt[-0].int32); } break; case 400: #line 1063 "asmparse.y" { double* p = new (nothrow) double[yypvt[-0].int32]; if(p != NULL) { for(int i=0; i<yypvt[-0].int32; i++) p[i] = *(yypvt[-2].float64); PASM->EmitData(p, sizeof(double)*yypvt[-0].int32); delete yypvt[-2].float64; delete [] p; } else PASM->report->error("Out of memory emitting data block %d bytes\n", sizeof(double)*yypvt[-0].int32); } break; case 401: #line 1070 "asmparse.y" { __int64* p = new (nothrow) __int64[yypvt[-0].int32]; if(p != NULL) { for(int i=0; i<yypvt[-0].int32; i++) p[i] = *(yypvt[-2].int64); PASM->EmitData(p, sizeof(__int64)*yypvt[-0].int32); delete yypvt[-2].int64; delete [] p; } else PASM->report->error("Out of memory emitting data block %d bytes\n", sizeof(__int64)*yypvt[-0].int32); } break; case 402: #line 1077 "asmparse.y" { __int32* p = new (nothrow) __int32[yypvt[-0].int32]; if(p != NULL) { for(int i=0; i<yypvt[-0].int32; i++) p[i] = yypvt[-2].int32; PASM->EmitData(p, sizeof(__int32)*yypvt[-0].int32); delete [] p; } else PASM->report->error("Out of memory emitting data block %d bytes\n", sizeof(__int32)*yypvt[-0].int32); } break; case 403: #line 1084 "asmparse.y" { __int16 i = (__int16) yypvt[-2].int32; FAIL_UNLESS(i == yypvt[-2].int32, ("Value %d too big\n", yypvt[-2].int32)); __int16* p = new (nothrow) __int16[yypvt[-0].int32]; if(p != NULL) { for(int j=0; j<yypvt[-0].int32; j++) p[j] = i; PASM->EmitData(p, sizeof(__int16)*yypvt[-0].int32); delete [] p; } else PASM->report->error("Out of memory emitting data block %d bytes\n", sizeof(__int16)*yypvt[-0].int32); } break; case 404: #line 1092 "asmparse.y" { __int8 i = (__int8) yypvt[-2].int32; FAIL_UNLESS(i == yypvt[-2].int32, ("Value %d too big\n", yypvt[-2].int32)); __int8* p = new (nothrow) __int8[yypvt[-0].int32]; if(p != NULL) { for(int j=0; j<yypvt[-0].int32; j++) p[j] = i; PASM->EmitData(p, sizeof(__int8)*yypvt[-0].int32); delete [] p; } else PASM->report->error("Out of memory emitting data block %d bytes\n", sizeof(__int8)*yypvt[-0].int32); } break; case 405: #line 1099 "asmparse.y" { PASM->EmitData(NULL, sizeof(float)*yypvt[-0].int32); } break; case 406: #line 1100 "asmparse.y" { PASM->EmitData(NULL, sizeof(double)*yypvt[-0].int32); } break; case 407: #line 1101 "asmparse.y" { PASM->EmitData(NULL, sizeof(__int64)*yypvt[-0].int32); } break; case 408: #line 1102 "asmparse.y" { PASM->EmitData(NULL, sizeof(__int32)*yypvt[-0].int32); } break; case 409: #line 1103 "asmparse.y" { PASM->EmitData(NULL, sizeof(__int16)*yypvt[-0].int32); } break; case 410: #line 1104 "asmparse.y" { PASM->EmitData(NULL, sizeof(__int8)*yypvt[-0].int32); } break; case 411: #line 1108 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_R4); float f = (float)(*yypvt[-1].float64); yyval.binstr->appendInt32(*((__int32*)&f)); delete yypvt[-1].float64; } break; case 412: #line 1111 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_R8); yyval.binstr->appendInt64((__int64 *)yypvt[-1].float64); delete yypvt[-1].float64; } break; case 413: #line 1113 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_R4); yyval.binstr->appendInt32(yypvt[-1].int32); } break; case 414: #line 1115 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_R8); yyval.binstr->appendInt64((__int64 *)yypvt[-1].int64); delete yypvt[-1].int64; } break; case 415: #line 1117 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_I8); yyval.binstr->appendInt64((__int64 *)yypvt[-1].int64); delete yypvt[-1].int64; } break; case 416: #line 1119 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_I4); yyval.binstr->appendInt32(yypvt[-1].int32); } break; case 417: #line 1121 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_I2); yyval.binstr->appendInt16(yypvt[-1].int32); } break; case 418: #line 1123 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_I1); yyval.binstr->appendInt8(yypvt[-1].int32); } break; case 419: #line 1125 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_U8); yyval.binstr->appendInt64((__int64 *)yypvt[-1].int64); delete yypvt[-1].int64; } break; case 420: #line 1127 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_U4); yyval.binstr->appendInt32(yypvt[-1].int32); } break; case 421: #line 1129 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_U2); yyval.binstr->appendInt16(yypvt[-1].int32); } break; case 422: #line 1131 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_U1); yyval.binstr->appendInt8(yypvt[-1].int32); } break; case 423: #line 1133 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_U8); yyval.binstr->appendInt64((__int64 *)yypvt[-1].int64); delete yypvt[-1].int64; } break; case 424: #line 1135 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_U4); yyval.binstr->appendInt32(yypvt[-1].int32); } break; case 425: #line 1137 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_U2); yyval.binstr->appendInt16(yypvt[-1].int32); } break; case 426: #line 1139 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_U1); yyval.binstr->appendInt8(yypvt[-1].int32); } break; case 427: #line 1141 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_CHAR); yyval.binstr->appendInt16(yypvt[-1].int32); } break; case 428: #line 1143 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_BOOLEAN); yyval.binstr->appendInt8(yypvt[-1].int32);} break; case 429: #line 1145 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_STRING); yyval.binstr->append(yypvt[-1].binstr); delete yypvt[-1].binstr;} break; case 430: #line 1149 "asmparse.y" { bParsingByteArray = TRUE; } break; case 431: #line 1152 "asmparse.y" { yyval.binstr = new BinStr(); } break; case 432: #line 1153 "asmparse.y" { yyval.binstr = yypvt[-0].binstr; } break; case 433: #line 1156 "asmparse.y" { __int8 i = (__int8) yypvt[-0].int32; yyval.binstr = new BinStr(); yyval.binstr->appendInt8(i); } break; case 434: #line 1157 "asmparse.y" { __int8 i = (__int8) yypvt[-0].int32; yyval.binstr = yypvt[-1].binstr; yyval.binstr->appendInt8(i); } break; case 435: #line 1161 "asmparse.y" { yyval.binstr = yypvt[-0].binstr; } break; case 436: #line 1162 "asmparse.y" { yyval.binstr = BinStrToUnicode(yypvt[-0].binstr,true); yyval.binstr->insertInt8(ELEMENT_TYPE_STRING);} break; case 437: #line 1163 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_CLASS); yyval.binstr->appendInt32(0); } break; case 438: #line 1168 "asmparse.y" { yyval.binstr = yypvt[-0].binstr; } break; case 439: #line 1169 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_STRING); yyval.binstr->appendInt8(0xFF); } break; case 440: #line 1170 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_STRING); AppendStringWithLength(yyval.binstr,yypvt[-1].string); delete [] yypvt[-1].string;} break; case 441: #line 1172 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(SERIALIZATION_TYPE_TYPE); AppendStringWithLength(yyval.binstr,yypvt[-1].string); delete [] yypvt[-1].string;} break; case 442: #line 1174 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(SERIALIZATION_TYPE_TYPE); AppendStringWithLength(yyval.binstr,PASM->ReflectionNotation(yypvt[-1].token));} break; case 443: #line 1176 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(SERIALIZATION_TYPE_TYPE); yyval.binstr->appendInt8(0xFF); } break; case 444: #line 1177 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->insertInt8(SERIALIZATION_TYPE_TAGGED_OBJECT);} break; case 445: #line 1179 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->insertInt32(yypvt[-4].int32); yyval.binstr->insertInt8(ELEMENT_TYPE_R4); yyval.binstr->insertInt8(ELEMENT_TYPE_SZARRAY); } break; case 446: #line 1183 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->insertInt32(yypvt[-4].int32); yyval.binstr->insertInt8(ELEMENT_TYPE_R8); yyval.binstr->insertInt8(ELEMENT_TYPE_SZARRAY); } break; case 447: #line 1187 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->insertInt32(yypvt[-4].int32); yyval.binstr->insertInt8(ELEMENT_TYPE_I8); yyval.binstr->insertInt8(ELEMENT_TYPE_SZARRAY); } break; case 448: #line 1191 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->insertInt32(yypvt[-4].int32); yyval.binstr->insertInt8(ELEMENT_TYPE_I4); yyval.binstr->insertInt8(ELEMENT_TYPE_SZARRAY); } break; case 449: #line 1195 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->insertInt32(yypvt[-4].int32); yyval.binstr->insertInt8(ELEMENT_TYPE_I2); yyval.binstr->insertInt8(ELEMENT_TYPE_SZARRAY); } break; case 450: #line 1199 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->insertInt32(yypvt[-4].int32); yyval.binstr->insertInt8(ELEMENT_TYPE_I1); yyval.binstr->insertInt8(ELEMENT_TYPE_SZARRAY); } break; case 451: #line 1203 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->insertInt32(yypvt[-4].int32); yyval.binstr->insertInt8(ELEMENT_TYPE_U8); yyval.binstr->insertInt8(ELEMENT_TYPE_SZARRAY); } break; case 452: #line 1207 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->insertInt32(yypvt[-4].int32); yyval.binstr->insertInt8(ELEMENT_TYPE_U4); yyval.binstr->insertInt8(ELEMENT_TYPE_SZARRAY); } break; case 453: #line 1211 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->insertInt32(yypvt[-4].int32); yyval.binstr->insertInt8(ELEMENT_TYPE_U2); yyval.binstr->insertInt8(ELEMENT_TYPE_SZARRAY); } break; case 454: #line 1215 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->insertInt32(yypvt[-4].int32); yyval.binstr->insertInt8(ELEMENT_TYPE_U1); yyval.binstr->insertInt8(ELEMENT_TYPE_SZARRAY); } break; case 455: #line 1219 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->insertInt32(yypvt[-4].int32); yyval.binstr->insertInt8(ELEMENT_TYPE_U8); yyval.binstr->insertInt8(ELEMENT_TYPE_SZARRAY); } break; case 456: #line 1223 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->insertInt32(yypvt[-4].int32); yyval.binstr->insertInt8(ELEMENT_TYPE_U4); yyval.binstr->insertInt8(ELEMENT_TYPE_SZARRAY); } break; case 457: #line 1227 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->insertInt32(yypvt[-4].int32); yyval.binstr->insertInt8(ELEMENT_TYPE_U2); yyval.binstr->insertInt8(ELEMENT_TYPE_SZARRAY); } break; case 458: #line 1231 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->insertInt32(yypvt[-4].int32); yyval.binstr->insertInt8(ELEMENT_TYPE_U1); yyval.binstr->insertInt8(ELEMENT_TYPE_SZARRAY); } break; case 459: #line 1235 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->insertInt32(yypvt[-4].int32); yyval.binstr->insertInt8(ELEMENT_TYPE_CHAR); yyval.binstr->insertInt8(ELEMENT_TYPE_SZARRAY); } break; case 460: #line 1239 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->insertInt32(yypvt[-4].int32); yyval.binstr->insertInt8(ELEMENT_TYPE_BOOLEAN); yyval.binstr->insertInt8(ELEMENT_TYPE_SZARRAY); } break; case 461: #line 1243 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->insertInt32(yypvt[-4].int32); yyval.binstr->insertInt8(ELEMENT_TYPE_STRING); yyval.binstr->insertInt8(ELEMENT_TYPE_SZARRAY); } break; case 462: #line 1247 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->insertInt32(yypvt[-4].int32); yyval.binstr->insertInt8(SERIALIZATION_TYPE_TYPE); yyval.binstr->insertInt8(ELEMENT_TYPE_SZARRAY); } break; case 463: #line 1251 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->insertInt32(yypvt[-4].int32); yyval.binstr->insertInt8(SERIALIZATION_TYPE_TAGGED_OBJECT); yyval.binstr->insertInt8(ELEMENT_TYPE_SZARRAY); } break; case 464: #line 1257 "asmparse.y" { yyval.binstr = new BinStr(); } break; case 465: #line 1258 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; float f = (float) (*yypvt[-0].float64); yyval.binstr->appendInt32(*((__int32*)&f)); delete yypvt[-0].float64; } break; case 466: #line 1260 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->appendInt32(yypvt[-0].int32); } break; case 467: #line 1264 "asmparse.y" { yyval.binstr = new BinStr(); } break; case 468: #line 1265 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->appendInt64((__int64 *)yypvt[-0].float64); delete yypvt[-0].float64; } break; case 469: #line 1267 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->appendInt64((__int64 *)yypvt[-0].int64); delete yypvt[-0].int64; } break; case 470: #line 1271 "asmparse.y" { yyval.binstr = new BinStr(); } break; case 471: #line 1272 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->appendInt64((__int64 *)yypvt[-0].int64); delete yypvt[-0].int64; } break; case 472: #line 1276 "asmparse.y" { yyval.binstr = new BinStr(); } break; case 473: #line 1277 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->appendInt32(yypvt[-0].int32);} break; case 474: #line 1280 "asmparse.y" { yyval.binstr = new BinStr(); } break; case 475: #line 1281 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->appendInt16(yypvt[-0].int32);} break; case 476: #line 1284 "asmparse.y" { yyval.binstr = new BinStr(); } break; case 477: #line 1285 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->appendInt8(yypvt[-0].int32); } break; case 478: #line 1288 "asmparse.y" { yyval.binstr = new BinStr(); } break; case 479: #line 1289 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->appendInt8(yypvt[-0].int32);} break; case 480: #line 1293 "asmparse.y" { yyval.binstr = new BinStr(); } break; case 481: #line 1294 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->appendInt8(0xFF); } break; case 482: #line 1295 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; AppendStringWithLength(yyval.binstr,yypvt[-0].string); delete [] yypvt[-0].string;} break; case 483: #line 1299 "asmparse.y" { yyval.binstr = new BinStr(); } break; case 484: #line 1300 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->appendInt8(0xFF); } break; case 485: #line 1301 "asmparse.y" { yyval.binstr = yypvt[-2].binstr; AppendStringWithLength(yyval.binstr,yypvt[-0].string); delete [] yypvt[-0].string;} break; case 486: #line 1303 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; AppendStringWithLength(yyval.binstr,PASM->ReflectionNotation(yypvt[-0].token));} break; case 487: #line 1307 "asmparse.y" { yyval.binstr = new BinStr(); } break; case 488: #line 1308 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->append(yypvt[-0].binstr); delete yypvt[-0].binstr; } break; case 489: #line 1312 "asmparse.y" { parser->m_ANSFirst.PUSH(PASM->m_firstArgName); parser->m_ANSLast.PUSH(PASM->m_lastArgName); PASM->m_firstArgName = NULL; PASM->m_lastArgName = NULL; } break; case 490: #line 1318 "asmparse.y" { yyval.instr = SetupInstr(yypvt[-0].opcode); } break; case 491: #line 1321 "asmparse.y" { yyval.instr = SetupInstr(yypvt[-0].opcode); } break; case 492: #line 1324 "asmparse.y" { yyval.instr = SetupInstr(yypvt[-0].opcode); } break; case 493: #line 1327 "asmparse.y" { yyval.instr = SetupInstr(yypvt[-0].opcode); } break; case 494: #line 1330 "asmparse.y" { yyval.instr = SetupInstr(yypvt[-0].opcode); } break; case 495: #line 1333 "asmparse.y" { yyval.instr = SetupInstr(yypvt[-0].opcode); } break; case 496: #line 1336 "asmparse.y" { yyval.instr = SetupInstr(yypvt[-0].opcode); if((!PASM->OnErrGo)&& ((yypvt[-0].opcode == CEE_NEWOBJ)|| (yypvt[-0].opcode == CEE_CALLVIRT))) iCallConv = IMAGE_CEE_CS_CALLCONV_HASTHIS; } break; case 497: #line 1344 "asmparse.y" { yyval.instr = SetupInstr(yypvt[-0].opcode); } break; case 498: #line 1347 "asmparse.y" { yyval.instr = SetupInstr(yypvt[-0].opcode); } break; case 499: #line 1350 "asmparse.y" { yyval.instr = SetupInstr(yypvt[-0].opcode); } break; case 500: #line 1353 "asmparse.y" { yyval.instr = SetupInstr(yypvt[-0].opcode); } break; case 501: #line 1356 "asmparse.y" { yyval.instr = SetupInstr(yypvt[-0].opcode); iOpcodeLen = PASM->OpcodeLen(yyval.instr); } break; case 502: #line 1359 "asmparse.y" { yyval.instr = SetupInstr(yypvt[-0].opcode); } break; case 503: #line 1362 "asmparse.y" { yyval.instr = yypvt[-1].instr; bParsingByteArray = TRUE; } break; case 504: #line 1366 "asmparse.y" { PASM->EmitOpcode(yypvt[-0].instr); } break; case 505: #line 1367 "asmparse.y" { PASM->EmitInstrVar(yypvt[-1].instr, yypvt[-0].int32); } break; case 506: #line 1368 "asmparse.y" { PASM->EmitInstrVarByName(yypvt[-1].instr, yypvt[-0].string); } break; case 507: #line 1369 "asmparse.y" { PASM->EmitInstrI(yypvt[-1].instr, yypvt[-0].int32); } break; case 508: #line 1370 "asmparse.y" { PASM->EmitInstrI8(yypvt[-1].instr, yypvt[-0].int64); } break; case 509: #line 1371 "asmparse.y" { PASM->EmitInstrR(yypvt[-1].instr, yypvt[-0].float64); delete (yypvt[-0].float64);} break; case 510: #line 1372 "asmparse.y" { double f = (double) (*yypvt[-0].int64); PASM->EmitInstrR(yypvt[-1].instr, &f); } break; case 511: #line 1373 "asmparse.y" { unsigned L = yypvt[-1].binstr->length(); FAIL_UNLESS(L >= sizeof(float), ("%d hexbytes, must be at least %d\n", L,sizeof(float))); if(L < sizeof(float)) {YYERROR; } else { double f = (L >= sizeof(double)) ? *((double *)(yypvt[-1].binstr->ptr())) : (double)(*(float *)(yypvt[-1].binstr->ptr())); PASM->EmitInstrR(yypvt[-2].instr,&f); } delete yypvt[-1].binstr; } break; case 512: #line 1382 "asmparse.y" { PASM->EmitInstrBrOffset(yypvt[-1].instr, yypvt[-0].int32); } break; case 513: #line 1383 "asmparse.y" { PASM->EmitInstrBrTarget(yypvt[-1].instr, yypvt[-0].string); } break; case 514: #line 1385 "asmparse.y" { PASM->SetMemberRefFixup(yypvt[-0].token,PASM->OpcodeLen(yypvt[-1].instr)); PASM->EmitInstrI(yypvt[-1].instr,yypvt[-0].token); PASM->m_tkCurrentCVOwner = yypvt[-0].token; PASM->m_pCustomDescrList = NULL; iCallConv = 0; } break; case 515: #line 1392 "asmparse.y" { yypvt[-3].binstr->insertInt8(IMAGE_CEE_CS_CALLCONV_FIELD); mdToken mr = PASM->MakeMemberRef(yypvt[-2].token, yypvt[-0].string, yypvt[-3].binstr); PASM->SetMemberRefFixup(mr, PASM->OpcodeLen(yypvt[-4].instr)); PASM->EmitInstrI(yypvt[-4].instr,mr); PASM->m_tkCurrentCVOwner = mr; PASM->m_pCustomDescrList = NULL; } break; case 516: #line 1400 "asmparse.y" { yypvt[-1].binstr->insertInt8(IMAGE_CEE_CS_CALLCONV_FIELD); mdToken mr = PASM->MakeMemberRef(mdTokenNil, yypvt[-0].string, yypvt[-1].binstr); PASM->SetMemberRefFixup(mr, PASM->OpcodeLen(yypvt[-2].instr)); PASM->EmitInstrI(yypvt[-2].instr,mr); PASM->m_tkCurrentCVOwner = mr; PASM->m_pCustomDescrList = NULL; } break; case 517: #line 1407 "asmparse.y" { mdToken mr = yypvt[-0].token; PASM->SetMemberRefFixup(mr, PASM->OpcodeLen(yypvt[-1].instr)); PASM->EmitInstrI(yypvt[-1].instr,mr); PASM->m_tkCurrentCVOwner = mr; PASM->m_pCustomDescrList = NULL; } break; case 518: #line 1413 "asmparse.y" { mdToken mr = yypvt[-0].tdd->m_tkTypeSpec; PASM->SetMemberRefFixup(mr, PASM->OpcodeLen(yypvt[-1].instr)); PASM->EmitInstrI(yypvt[-1].instr,mr); PASM->m_tkCurrentCVOwner = mr; PASM->m_pCustomDescrList = NULL; } break; case 519: #line 1419 "asmparse.y" { mdToken mr = yypvt[-0].tdd->m_tkTypeSpec; PASM->SetMemberRefFixup(mr, PASM->OpcodeLen(yypvt[-1].instr)); PASM->EmitInstrI(yypvt[-1].instr,mr); PASM->m_tkCurrentCVOwner = mr; PASM->m_pCustomDescrList = NULL; } break; case 520: #line 1425 "asmparse.y" { PASM->EmitInstrI(yypvt[-1].instr, yypvt[-0].token); PASM->m_tkCurrentCVOwner = yypvt[-0].token; PASM->m_pCustomDescrList = NULL; } break; case 521: #line 1429 "asmparse.y" { PASM->EmitInstrStringLiteral(yypvt[-1].instr, yypvt[-0].binstr,TRUE); } break; case 522: #line 1431 "asmparse.y" { PASM->EmitInstrStringLiteral(yypvt[-4].instr, yypvt[-1].binstr,FALSE); } break; case 523: #line 1433 "asmparse.y" { PASM->EmitInstrStringLiteral(yypvt[-3].instr, yypvt[-1].binstr,FALSE,TRUE); } break; case 524: #line 1435 "asmparse.y" { PASM->EmitInstrSig(yypvt[-5].instr, parser->MakeSig(yypvt[-4].int32, yypvt[-3].binstr, yypvt[-1].binstr)); PASM->ResetArgNameList(); } break; case 525: #line 1439 "asmparse.y" { PASM->EmitInstrI(yypvt[-1].instr,yypvt[-0].token); PASM->m_tkCurrentCVOwner = yypvt[-0].token; PASM->m_pCustomDescrList = NULL; iOpcodeLen = 0; } break; case 526: #line 1444 "asmparse.y" { PASM->EmitInstrSwitch(yypvt[-3].instr, yypvt[-1].labels); } break; case 527: #line 1447 "asmparse.y" { yyval.labels = 0; } break; case 528: #line 1448 "asmparse.y" { yyval.labels = new Labels(yypvt[-2].string, yypvt[-0].labels, TRUE); } break; case 529: #line 1449 "asmparse.y" { yyval.labels = new Labels((char *)(UINT_PTR)yypvt[-2].int32, yypvt[-0].labels, FALSE); } break; case 530: #line 1450 "asmparse.y" { yyval.labels = new Labels(yypvt[-0].string, NULL, TRUE); } break; case 531: #line 1451 "asmparse.y" { yyval.labels = new Labels((char *)(UINT_PTR)yypvt[-0].int32, NULL, FALSE); } break; case 532: #line 1455 "asmparse.y" { yyval.binstr = NULL; } break; case 533: #line 1456 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; } break; case 534: #line 1459 "asmparse.y" { yyval.binstr = NULL; } break; case 535: #line 1460 "asmparse.y" { yyval.binstr = yypvt[-0].binstr; } break; case 536: #line 1463 "asmparse.y" { yyval.binstr = yypvt[-0].binstr; } break; case 537: #line 1464 "asmparse.y" { yyval.binstr = yypvt[-2].binstr; yyval.binstr->append(yypvt[-0].binstr); delete yypvt[-0].binstr; } break; case 538: #line 1468 "asmparse.y" { yyval.binstr = new BinStr(); } break; case 539: #line 1469 "asmparse.y" { yyval.binstr = yypvt[-0].binstr;} break; case 540: #line 1472 "asmparse.y" { yyval.binstr = yypvt[-0].binstr; } break; case 541: #line 1473 "asmparse.y" { yyval.binstr = yypvt[-2].binstr; yyval.binstr->append(yypvt[-0].binstr); delete yypvt[-0].binstr; } break; case 542: #line 1476 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_SENTINEL); } break; case 543: #line 1477 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->append(yypvt[-1].binstr); PASM->addArgName(NULL, yypvt[-1].binstr, yypvt[-0].binstr, yypvt[-2].int32); } break; case 544: #line 1478 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->append(yypvt[-2].binstr); PASM->addArgName(yypvt[-0].string, yypvt[-2].binstr, yypvt[-1].binstr, yypvt[-3].int32);} break; case 545: #line 1482 "asmparse.y" { yyval.token = PASM->ResolveClassRef(PASM->GetAsmRef(yypvt[-2].string), yypvt[-0].string, NULL); delete[] yypvt[-2].string;} break; case 546: #line 1483 "asmparse.y" { yyval.token = PASM->ResolveClassRef(yypvt[-2].token, yypvt[-0].string, NULL); } break; case 547: #line 1484 "asmparse.y" { yyval.token = PASM->ResolveClassRef(mdTokenNil, yypvt[-0].string, NULL); } break; case 548: #line 1485 "asmparse.y" { yyval.token = PASM->ResolveClassRef(PASM->GetModRef(yypvt[-2].string),yypvt[-0].string, NULL); delete[] yypvt[-2].string;} break; case 549: #line 1486 "asmparse.y" { yyval.token = PASM->ResolveClassRef(1,yypvt[-0].string,NULL); } break; case 550: #line 1487 "asmparse.y" { yyval.token = yypvt[-0].token; } break; case 551: #line 1488 "asmparse.y" { yyval.token = yypvt[-0].tdd->m_tkTypeSpec; } break; case 552: #line 1489 "asmparse.y" { if(PASM->m_pCurClass != NULL) yyval.token = PASM->m_pCurClass->m_cl; else { yyval.token = 0; PASM->report->error(".this outside class scope\n"); } } break; case 553: #line 1492 "asmparse.y" { if(PASM->m_pCurClass != NULL) { yyval.token = PASM->m_pCurClass->m_crExtends; if(RidFromToken(yyval.token) == 0) PASM->report->error(".base undefined\n"); } else { yyval.token = 0; PASM->report->error(".base outside class scope\n"); } } break; case 554: #line 1498 "asmparse.y" { if(PASM->m_pCurClass != NULL) { if(PASM->m_pCurClass->m_pEncloser != NULL) yyval.token = PASM->m_pCurClass->m_pEncloser->m_cl; else { yyval.token = 0; PASM->report->error(".nester undefined\n"); } } else { yyval.token = 0; PASM->report->error(".nester outside class scope\n"); } } break; case 555: #line 1505 "asmparse.y" { yyval.string = yypvt[-0].string; } break; case 556: #line 1506 "asmparse.y" { yyval.string = newStringWDel(yypvt[-2].string, NESTING_SEP, yypvt[-0].string); } break; case 557: #line 1509 "asmparse.y" { yyval.token = yypvt[-0].token;} break; case 558: #line 1510 "asmparse.y" { yyval.token = PASM->GetAsmRef(yypvt[-1].string); delete[] yypvt[-1].string;} break; case 559: #line 1511 "asmparse.y" { yyval.token = PASM->GetModRef(yypvt[-1].string); delete[] yypvt[-1].string;} break; case 560: #line 1512 "asmparse.y" { yyval.token = PASM->ResolveTypeSpec(yypvt[-0].binstr); } break; case 561: #line 1516 "asmparse.y" { yyval.binstr = new BinStr(); } break; case 562: #line 1518 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_CUSTOMMARSHALER); corEmitInt(yyval.binstr,yypvt[-7].binstr->length()); yyval.binstr->append(yypvt[-7].binstr); corEmitInt(yyval.binstr,yypvt[-5].binstr->length()); yyval.binstr->append(yypvt[-5].binstr); corEmitInt(yyval.binstr,yypvt[-3].binstr->length()); yyval.binstr->append(yypvt[-3].binstr); corEmitInt(yyval.binstr,yypvt[-1].binstr->length()); yyval.binstr->append(yypvt[-1].binstr); PASM->report->warn("Deprecated 4-string form of custom marshaler, first two strings ignored\n");} break; case 563: #line 1525 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_CUSTOMMARSHALER); corEmitInt(yyval.binstr,0); corEmitInt(yyval.binstr,0); corEmitInt(yyval.binstr,yypvt[-3].binstr->length()); yyval.binstr->append(yypvt[-3].binstr); corEmitInt(yyval.binstr,yypvt[-1].binstr->length()); yyval.binstr->append(yypvt[-1].binstr); } break; case 564: #line 1530 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_FIXEDSYSSTRING); corEmitInt(yyval.binstr,yypvt[-1].int32); } break; case 565: #line 1533 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_FIXEDARRAY); corEmitInt(yyval.binstr,yypvt[-2].int32); yyval.binstr->append(yypvt[-0].binstr); } break; case 566: #line 1535 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_VARIANT); PASM->report->warn("Deprecated native type 'variant'\n"); } break; case 567: #line 1537 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_CURRENCY); } break; case 568: #line 1538 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_SYSCHAR); PASM->report->warn("Deprecated native type 'syschar'\n"); } break; case 569: #line 1540 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_VOID); PASM->report->warn("Deprecated native type 'void'\n"); } break; case 570: #line 1542 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_BOOLEAN); } break; case 571: #line 1543 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_I1); } break; case 572: #line 1544 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_I2); } break; case 573: #line 1545 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_I4); } break; case 574: #line 1546 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_I8); } break; case 575: #line 1547 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_R4); } break; case 576: #line 1548 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_R8); } break; case 577: #line 1549 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_ERROR); } break; case 578: #line 1550 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_U1); } break; case 579: #line 1551 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_U2); } break; case 580: #line 1552 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_U4); } break; case 581: #line 1553 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_U8); } break; case 582: #line 1554 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_U1); } break; case 583: #line 1555 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_U2); } break; case 584: #line 1556 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_U4); } break; case 585: #line 1557 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_U8); } break; case 586: #line 1558 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->insertInt8(NATIVE_TYPE_PTR); PASM->report->warn("Deprecated native type '*'\n"); } break; case 587: #line 1560 "asmparse.y" { yyval.binstr = yypvt[-2].binstr; if(yyval.binstr->length()==0) yyval.binstr->appendInt8(NATIVE_TYPE_MAX); yyval.binstr->insertInt8(NATIVE_TYPE_ARRAY); } break; case 588: #line 1562 "asmparse.y" { yyval.binstr = yypvt[-3].binstr; if(yyval.binstr->length()==0) yyval.binstr->appendInt8(NATIVE_TYPE_MAX); yyval.binstr->insertInt8(NATIVE_TYPE_ARRAY); corEmitInt(yyval.binstr,0); corEmitInt(yyval.binstr,yypvt[-1].int32); corEmitInt(yyval.binstr,0); } break; case 589: #line 1567 "asmparse.y" { yyval.binstr = yypvt[-5].binstr; if(yyval.binstr->length()==0) yyval.binstr->appendInt8(NATIVE_TYPE_MAX); yyval.binstr->insertInt8(NATIVE_TYPE_ARRAY); corEmitInt(yyval.binstr,yypvt[-1].int32); corEmitInt(yyval.binstr,yypvt[-3].int32); corEmitInt(yyval.binstr,ntaSizeParamIndexSpecified); } break; case 590: #line 1572 "asmparse.y" { yyval.binstr = yypvt[-4].binstr; if(yyval.binstr->length()==0) yyval.binstr->appendInt8(NATIVE_TYPE_MAX); yyval.binstr->insertInt8(NATIVE_TYPE_ARRAY); corEmitInt(yyval.binstr,yypvt[-1].int32); } break; case 591: #line 1575 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_DECIMAL); PASM->report->warn("Deprecated native type 'decimal'\n"); } break; case 592: #line 1577 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_DATE); PASM->report->warn("Deprecated native type 'date'\n"); } break; case 593: #line 1579 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_BSTR); } break; case 594: #line 1580 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_LPSTR); } break; case 595: #line 1581 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_LPWSTR); } break; case 596: #line 1582 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_LPTSTR); } break; case 597: #line 1583 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_OBJECTREF); PASM->report->warn("Deprecated native type 'objectref'\n"); } break; case 598: #line 1585 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_IUNKNOWN); if(yypvt[-0].int32 != -1) corEmitInt(yyval.binstr,yypvt[-0].int32); } break; case 599: #line 1587 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_IDISPATCH); if(yypvt[-0].int32 != -1) corEmitInt(yyval.binstr,yypvt[-0].int32); } break; case 600: #line 1589 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_STRUCT); } break; case 601: #line 1590 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_INTF); if(yypvt[-0].int32 != -1) corEmitInt(yyval.binstr,yypvt[-0].int32); } break; case 602: #line 1592 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_SAFEARRAY); corEmitInt(yyval.binstr,yypvt[-0].int32); corEmitInt(yyval.binstr,0);} break; case 603: #line 1595 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_SAFEARRAY); corEmitInt(yyval.binstr,yypvt[-2].int32); corEmitInt(yyval.binstr,yypvt[-0].binstr->length()); yyval.binstr->append(yypvt[-0].binstr); } break; case 604: #line 1599 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_INT); } break; case 605: #line 1600 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_UINT); } break; case 606: #line 1601 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_UINT); } break; case 607: #line 1602 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_NESTEDSTRUCT); PASM->report->warn("Deprecated native type 'nested struct'\n"); } break; case 608: #line 1604 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_BYVALSTR); } break; case 609: #line 1605 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_ANSIBSTR); } break; case 610: #line 1606 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_TBSTR); } break; case 611: #line 1607 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_VARIANTBOOL); } break; case 612: #line 1608 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_FUNC); } break; case 613: #line 1609 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_ASANY); } break; case 614: #line 1610 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_LPSTRUCT); } break; case 615: #line 1611 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->append(yypvt[-0].tdd->m_pbsTypeSpec); } break; case 616: #line 1614 "asmparse.y" { yyval.int32 = -1; } break; case 617: #line 1615 "asmparse.y" { yyval.int32 = yypvt[-1].int32; } break; case 618: #line 1618 "asmparse.y" { yyval.int32 = VT_EMPTY; } break; case 619: #line 1619 "asmparse.y" { yyval.int32 = VT_NULL; } break; case 620: #line 1620 "asmparse.y" { yyval.int32 = VT_VARIANT; } break; case 621: #line 1621 "asmparse.y" { yyval.int32 = VT_CY; } break; case 622: #line 1622 "asmparse.y" { yyval.int32 = VT_VOID; } break; case 623: #line 1623 "asmparse.y" { yyval.int32 = VT_BOOL; } break; case 624: #line 1624 "asmparse.y" { yyval.int32 = VT_I1; } break; case 625: #line 1625 "asmparse.y" { yyval.int32 = VT_I2; } break; case 626: #line 1626 "asmparse.y" { yyval.int32 = VT_I4; } break; case 627: #line 1627 "asmparse.y" { yyval.int32 = VT_I8; } break; case 628: #line 1628 "asmparse.y" { yyval.int32 = VT_R4; } break; case 629: #line 1629 "asmparse.y" { yyval.int32 = VT_R8; } break; case 630: #line 1630 "asmparse.y" { yyval.int32 = VT_UI1; } break; case 631: #line 1631 "asmparse.y" { yyval.int32 = VT_UI2; } break; case 632: #line 1632 "asmparse.y" { yyval.int32 = VT_UI4; } break; case 633: #line 1633 "asmparse.y" { yyval.int32 = VT_UI8; } break; case 634: #line 1634 "asmparse.y" { yyval.int32 = VT_UI1; } break; case 635: #line 1635 "asmparse.y" { yyval.int32 = VT_UI2; } break; case 636: #line 1636 "asmparse.y" { yyval.int32 = VT_UI4; } break; case 637: #line 1637 "asmparse.y" { yyval.int32 = VT_UI8; } break; case 638: #line 1638 "asmparse.y" { yyval.int32 = VT_PTR; } break; case 639: #line 1639 "asmparse.y" { yyval.int32 = yypvt[-2].int32 | VT_ARRAY; } break; case 640: #line 1640 "asmparse.y" { yyval.int32 = yypvt[-1].int32 | VT_VECTOR; } break; case 641: #line 1641 "asmparse.y" { yyval.int32 = yypvt[-1].int32 | VT_BYREF; } break; case 642: #line 1642 "asmparse.y" { yyval.int32 = VT_DECIMAL; } break; case 643: #line 1643 "asmparse.y" { yyval.int32 = VT_DATE; } break; case 644: #line 1644 "asmparse.y" { yyval.int32 = VT_BSTR; } break; case 645: #line 1645 "asmparse.y" { yyval.int32 = VT_LPSTR; } break; case 646: #line 1646 "asmparse.y" { yyval.int32 = VT_LPWSTR; } break; case 647: #line 1647 "asmparse.y" { yyval.int32 = VT_UNKNOWN; } break; case 648: #line 1648 "asmparse.y" { yyval.int32 = VT_DISPATCH; } break; case 649: #line 1649 "asmparse.y" { yyval.int32 = VT_SAFEARRAY; } break; case 650: #line 1650 "asmparse.y" { yyval.int32 = VT_INT; } break; case 651: #line 1651 "asmparse.y" { yyval.int32 = VT_UINT; } break; case 652: #line 1652 "asmparse.y" { yyval.int32 = VT_UINT; } break; case 653: #line 1653 "asmparse.y" { yyval.int32 = VT_ERROR; } break; case 654: #line 1654 "asmparse.y" { yyval.int32 = VT_HRESULT; } break; case 655: #line 1655 "asmparse.y" { yyval.int32 = VT_CARRAY; } break; case 656: #line 1656 "asmparse.y" { yyval.int32 = VT_USERDEFINED; } break; case 657: #line 1657 "asmparse.y" { yyval.int32 = VT_RECORD; } break; case 658: #line 1658 "asmparse.y" { yyval.int32 = VT_FILETIME; } break; case 659: #line 1659 "asmparse.y" { yyval.int32 = VT_BLOB; } break; case 660: #line 1660 "asmparse.y" { yyval.int32 = VT_STREAM; } break; case 661: #line 1661 "asmparse.y" { yyval.int32 = VT_STORAGE; } break; case 662: #line 1662 "asmparse.y" { yyval.int32 = VT_STREAMED_OBJECT; } break; case 663: #line 1663 "asmparse.y" { yyval.int32 = VT_STORED_OBJECT; } break; case 664: #line 1664 "asmparse.y" { yyval.int32 = VT_BLOB_OBJECT; } break; case 665: #line 1665 "asmparse.y" { yyval.int32 = VT_CF; } break; case 666: #line 1666 "asmparse.y" { yyval.int32 = VT_CLSID; } break; case 667: #line 1670 "asmparse.y" { if(yypvt[-0].token == PASM->m_tkSysString) { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_STRING); } else if(yypvt[-0].token == PASM->m_tkSysObject) { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_OBJECT); } else yyval.binstr = parser->MakeTypeClass(ELEMENT_TYPE_CLASS, yypvt[-0].token); } break; case 668: #line 1676 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_OBJECT); } break; case 669: #line 1677 "asmparse.y" { yyval.binstr = parser->MakeTypeClass(ELEMENT_TYPE_VALUETYPE, yypvt[-0].token); } break; case 670: #line 1678 "asmparse.y" { yyval.binstr = parser->MakeTypeClass(ELEMENT_TYPE_VALUETYPE, yypvt[-0].token); } break; case 671: #line 1679 "asmparse.y" { yyval.binstr = yypvt[-2].binstr; yyval.binstr->insertInt8(ELEMENT_TYPE_SZARRAY); } break; case 672: #line 1680 "asmparse.y" { yyval.binstr = parser->MakeTypeArray(ELEMENT_TYPE_ARRAY, yypvt[-3].binstr, yypvt[-1].binstr); } break; case 673: #line 1681 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->insertInt8(ELEMENT_TYPE_BYREF); } break; case 674: #line 1682 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->insertInt8(ELEMENT_TYPE_PTR); } break; case 675: #line 1683 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->insertInt8(ELEMENT_TYPE_PINNED); } break; case 676: #line 1684 "asmparse.y" { yyval.binstr = parser->MakeTypeClass(ELEMENT_TYPE_CMOD_REQD, yypvt[-1].token); yyval.binstr->append(yypvt[-4].binstr); } break; case 677: #line 1686 "asmparse.y" { yyval.binstr = parser->MakeTypeClass(ELEMENT_TYPE_CMOD_OPT, yypvt[-1].token); yyval.binstr->append(yypvt[-4].binstr); } break; case 678: #line 1689 "asmparse.y" { yyval.binstr = parser->MakeSig(yypvt[-5].int32, yypvt[-4].binstr, yypvt[-1].binstr); yyval.binstr->insertInt8(ELEMENT_TYPE_FNPTR); PASM->delArgNameList(PASM->m_firstArgName); PASM->m_firstArgName = parser->m_ANSFirst.POP(); PASM->m_lastArgName = parser->m_ANSLast.POP(); } break; case 679: #line 1695 "asmparse.y" { if(yypvt[-1].binstr == NULL) yyval.binstr = yypvt[-3].binstr; else { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_GENERICINST); yyval.binstr->append(yypvt[-3].binstr); corEmitInt(yyval.binstr, corCountArgs(yypvt[-1].binstr)); yyval.binstr->append(yypvt[-1].binstr); delete yypvt[-3].binstr; delete yypvt[-1].binstr; }} break; case 680: #line 1702 "asmparse.y" { //if(PASM->m_pCurMethod) { // if(($3 < 0)||((DWORD)$3 >= PASM->m_pCurMethod->m_NumTyPars)) // PASM->report->error("Invalid method type parameter '%d'\n",$3); yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_MVAR); corEmitInt(yyval.binstr, yypvt[-0].int32); //} else PASM->report->error("Method type parameter '%d' outside method scope\n",$3); } break; case 681: #line 1708 "asmparse.y" { //if(PASM->m_pCurClass) { // if(($2 < 0)||((DWORD)$2 >= PASM->m_pCurClass->m_NumTyPars)) // PASM->report->error("Invalid type parameter '%d'\n",$2); yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_VAR); corEmitInt(yyval.binstr, yypvt[-0].int32); //} else PASM->report->error("Type parameter '%d' outside class scope\n",$2); } break; case 682: #line 1714 "asmparse.y" { int eltype = ELEMENT_TYPE_MVAR; int n=-1; if(PASM->m_pCurMethod) n = PASM->m_pCurMethod->FindTyPar(yypvt[-0].string); else { if(PASM->m_TyParList) n = PASM->m_TyParList->IndexOf(yypvt[-0].string); if(n == -1) { n = TyParFixupList.COUNT(); TyParFixupList.PUSH(yypvt[-0].string); eltype = ELEMENT_TYPE_MVARFIXUP; } } if(n == -1) { PASM->report->error("Invalid method type parameter '%s'\n",yypvt[-0].string); n = 0x1FFFFFFF; } yyval.binstr = new BinStr(); yyval.binstr->appendInt8(eltype); corEmitInt(yyval.binstr,n); } break; case 683: #line 1729 "asmparse.y" { int eltype = ELEMENT_TYPE_VAR; int n=-1; if(PASM->m_pCurClass && !newclass) n = PASM->m_pCurClass->FindTyPar(yypvt[-0].string); else { if(PASM->m_TyParList) n = PASM->m_TyParList->IndexOf(yypvt[-0].string); if(n == -1) { n = TyParFixupList.COUNT(); TyParFixupList.PUSH(yypvt[-0].string); eltype = ELEMENT_TYPE_VARFIXUP; } } if(n == -1) { PASM->report->error("Invalid type parameter '%s'\n",yypvt[-0].string); n = 0x1FFFFFFF; } yyval.binstr = new BinStr(); yyval.binstr->appendInt8(eltype); corEmitInt(yyval.binstr,n); } break; case 684: #line 1744 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_TYPEDBYREF); } break; case 685: #line 1745 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_VOID); } break; case 686: #line 1746 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_I); } break; case 687: #line 1747 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_U); } break; case 688: #line 1748 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_U); } break; case 689: #line 1749 "asmparse.y" { yyval.binstr = yypvt[-0].binstr; } break; case 690: #line 1750 "asmparse.y" { yyval.binstr = yypvt[-0].binstr; yyval.binstr->insertInt8(ELEMENT_TYPE_SENTINEL); } break; case 691: #line 1753 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_CHAR); } break; case 692: #line 1754 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_STRING); } break; case 693: #line 1755 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_BOOLEAN); } break; case 694: #line 1756 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_I1); } break; case 695: #line 1757 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_I2); } break; case 696: #line 1758 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_I4); } break; case 697: #line 1759 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_I8); } break; case 698: #line 1760 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_R4); } break; case 699: #line 1761 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_R8); } break; case 700: #line 1762 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_U1); } break; case 701: #line 1763 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_U2); } break; case 702: #line 1764 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_U4); } break; case 703: #line 1765 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_U8); } break; case 704: #line 1766 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_U1); } break; case 705: #line 1767 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_U2); } break; case 706: #line 1768 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_U4); } break; case 707: #line 1769 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_U8); } break; case 708: #line 1770 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->append(yypvt[-0].tdd->m_pbsTypeSpec); } break; case 709: #line 1773 "asmparse.y" { yyval.binstr = yypvt[-0].binstr; } break; case 710: #line 1774 "asmparse.y" { yyval.binstr = yypvt[-2].binstr; yypvt[-2].binstr->append(yypvt[-0].binstr); delete yypvt[-0].binstr; } break; case 711: #line 1777 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt32(0x7FFFFFFF); yyval.binstr->appendInt32(0x7FFFFFFF); } break; case 712: #line 1778 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt32(0x7FFFFFFF); yyval.binstr->appendInt32(0x7FFFFFFF); } break; case 713: #line 1779 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt32(0); yyval.binstr->appendInt32(yypvt[-0].int32); } break; case 714: #line 1780 "asmparse.y" { FAIL_UNLESS(yypvt[-2].int32 <= yypvt[-0].int32, ("lower bound %d must be <= upper bound %d\n", yypvt[-2].int32, yypvt[-0].int32)); if (yypvt[-2].int32 > yypvt[-0].int32) { YYERROR; }; yyval.binstr = new BinStr(); yyval.binstr->appendInt32(yypvt[-2].int32); yyval.binstr->appendInt32(yypvt[-0].int32-yypvt[-2].int32+1); } break; case 715: #line 1783 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt32(yypvt[-1].int32); yyval.binstr->appendInt32(0x7FFFFFFF); } break; case 716: #line 1788 "asmparse.y" { PASM->AddPermissionDecl(yypvt[-4].secAct, yypvt[-3].token, yypvt[-1].pair); } break; case 717: #line 1790 "asmparse.y" { PASM->AddPermissionDecl(yypvt[-5].secAct, yypvt[-4].token, yypvt[-1].binstr); } break; case 718: #line 1791 "asmparse.y" { PASM->AddPermissionDecl(yypvt[-1].secAct, yypvt[-0].token, (NVPair *)NULL); } break; case 719: #line 1792 "asmparse.y" { PASM->AddPermissionSetDecl(yypvt[-2].secAct, yypvt[-1].binstr); } break; case 720: #line 1794 "asmparse.y" { PASM->AddPermissionSetDecl(yypvt[-1].secAct,BinStrToUnicode(yypvt[-0].binstr,true));} break; case 721: #line 1796 "asmparse.y" { BinStr* ret = new BinStr(); ret->insertInt8('.'); corEmitInt(ret, nSecAttrBlobs); ret->append(yypvt[-1].binstr); PASM->AddPermissionSetDecl(yypvt[-4].secAct,ret); nSecAttrBlobs = 0; } break; case 722: #line 1804 "asmparse.y" { yyval.binstr = new BinStr(); nSecAttrBlobs = 0;} break; case 723: #line 1805 "asmparse.y" { yyval.binstr = yypvt[-0].binstr; nSecAttrBlobs = 1; } break; case 724: #line 1806 "asmparse.y" { yyval.binstr = yypvt[-2].binstr; yyval.binstr->append(yypvt[-0].binstr); nSecAttrBlobs++; } break; case 725: #line 1810 "asmparse.y" { yyval.binstr = PASM->EncodeSecAttr(PASM->ReflectionNotation(yypvt[-4].token),yypvt[-1].binstr,nCustomBlobNVPairs); nCustomBlobNVPairs = 0; } break; case 726: #line 1813 "asmparse.y" { yyval.binstr = PASM->EncodeSecAttr(yypvt[-4].string,yypvt[-1].binstr,nCustomBlobNVPairs); nCustomBlobNVPairs = 0; } break; case 727: #line 1817 "asmparse.y" { yyval.secAct = yypvt[-2].secAct; bParsingByteArray = TRUE; } break; case 728: #line 1819 "asmparse.y" { yyval.secAct = yypvt[-2].secAct; bParsingByteArray = TRUE; } break; case 729: #line 1822 "asmparse.y" { yyval.pair = yypvt[-0].pair; } break; case 730: #line 1823 "asmparse.y" { yyval.pair = yypvt[-2].pair->Concat(yypvt[-0].pair); } break; case 731: #line 1826 "asmparse.y" { yypvt[-2].binstr->appendInt8(0); yyval.pair = new NVPair(yypvt[-2].binstr, yypvt[-0].binstr); } break; case 732: #line 1829 "asmparse.y" { yyval.int32 = 1; } break; case 733: #line 1830 "asmparse.y" { yyval.int32 = 0; } break; case 734: #line 1833 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(SERIALIZATION_TYPE_BOOLEAN); yyval.binstr->appendInt8(yypvt[-0].int32); } break; case 735: #line 1836 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(SERIALIZATION_TYPE_I4); yyval.binstr->appendInt32(yypvt[-0].int32); } break; case 736: #line 1839 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(SERIALIZATION_TYPE_I4); yyval.binstr->appendInt32(yypvt[-1].int32); } break; case 737: #line 1842 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(SERIALIZATION_TYPE_STRING); yyval.binstr->append(yypvt[-0].binstr); delete yypvt[-0].binstr; yyval.binstr->appendInt8(0); } break; case 738: #line 1846 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(SERIALIZATION_TYPE_ENUM); char* sz = PASM->ReflectionNotation(yypvt[-5].token); strcpy_s((char *)yyval.binstr->getBuff((unsigned)strlen(sz) + 1), strlen(sz) + 1,sz); yyval.binstr->appendInt8(1); yyval.binstr->appendInt32(yypvt[-1].int32); } break; case 739: #line 1852 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(SERIALIZATION_TYPE_ENUM); char* sz = PASM->ReflectionNotation(yypvt[-5].token); strcpy_s((char *)yyval.binstr->getBuff((unsigned)strlen(sz) + 1), strlen(sz) + 1,sz); yyval.binstr->appendInt8(2); yyval.binstr->appendInt32(yypvt[-1].int32); } break; case 740: #line 1858 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(SERIALIZATION_TYPE_ENUM); char* sz = PASM->ReflectionNotation(yypvt[-5].token); strcpy_s((char *)yyval.binstr->getBuff((unsigned)strlen(sz) + 1), strlen(sz) + 1,sz); yyval.binstr->appendInt8(4); yyval.binstr->appendInt32(yypvt[-1].int32); } break; case 741: #line 1864 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(SERIALIZATION_TYPE_ENUM); char* sz = PASM->ReflectionNotation(yypvt[-3].token); strcpy_s((char *)yyval.binstr->getBuff((unsigned)strlen(sz) + 1), strlen(sz) + 1,sz); yyval.binstr->appendInt8(4); yyval.binstr->appendInt32(yypvt[-1].int32); } break; case 742: #line 1872 "asmparse.y" { yyval.secAct = dclRequest; } break; case 743: #line 1873 "asmparse.y" { yyval.secAct = dclDemand; } break; case 744: #line 1874 "asmparse.y" { yyval.secAct = dclAssert; } break; case 745: #line 1875 "asmparse.y" { yyval.secAct = dclDeny; } break; case 746: #line 1876 "asmparse.y" { yyval.secAct = dclPermitOnly; } break; case 747: #line 1877 "asmparse.y" { yyval.secAct = dclLinktimeCheck; } break; case 748: #line 1878 "asmparse.y" { yyval.secAct = dclInheritanceCheck; } break; case 749: #line 1879 "asmparse.y" { yyval.secAct = dclRequestMinimum; } break; case 750: #line 1880 "asmparse.y" { yyval.secAct = dclRequestOptional; } break; case 751: #line 1881 "asmparse.y" { yyval.secAct = dclRequestRefuse; } break; case 752: #line 1882 "asmparse.y" { yyval.secAct = dclPrejitGrant; } break; case 753: #line 1883 "asmparse.y" { yyval.secAct = dclPrejitDenied; } break; case 754: #line 1884 "asmparse.y" { yyval.secAct = dclNonCasDemand; } break; case 755: #line 1885 "asmparse.y" { yyval.secAct = dclNonCasLinkDemand; } break; case 756: #line 1886 "asmparse.y" { yyval.secAct = dclNonCasInheritance; } break; case 757: #line 1890 "asmparse.y" { PASM->ResetLineNumbers(); nCurrPC = PASM->m_CurPC; PENV->bExternSource = TRUE; PENV->bExternSourceAutoincrement = FALSE; } break; case 758: #line 1891 "asmparse.y" { PASM->ResetLineNumbers(); nCurrPC = PASM->m_CurPC; PENV->bExternSource = TRUE; PENV->bExternSourceAutoincrement = TRUE; } break; case 759: #line 1894 "asmparse.y" { PENV->nExtLine = PENV->nExtLineEnd = yypvt[-1].int32; PENV->nExtCol = 0; PENV->nExtColEnd = static_cast<unsigned>(-1); PASM->SetSourceFileName(yypvt[-0].string);} break; case 760: #line 1897 "asmparse.y" { PENV->nExtLine = PENV->nExtLineEnd = yypvt[-0].int32; PENV->nExtCol = 0; PENV->nExtColEnd = static_cast<unsigned>(-1); } break; case 761: #line 1899 "asmparse.y" { PENV->nExtLine = PENV->nExtLineEnd = yypvt[-3].int32; PENV->nExtCol=yypvt[-1].int32; PENV->nExtColEnd = static_cast<unsigned>(-1); PASM->SetSourceFileName(yypvt[-0].string);} break; case 762: #line 1902 "asmparse.y" { PENV->nExtLine = PENV->nExtLineEnd = yypvt[-2].int32; PENV->nExtCol=yypvt[-0].int32; PENV->nExtColEnd = static_cast<unsigned>(-1);} break; case 763: #line 1905 "asmparse.y" { PENV->nExtLine = PENV->nExtLineEnd = yypvt[-5].int32; PENV->nExtCol=yypvt[-3].int32; PENV->nExtColEnd = yypvt[-1].int32; PASM->SetSourceFileName(yypvt[-0].string);} break; case 764: #line 1909 "asmparse.y" { PENV->nExtLine = PENV->nExtLineEnd = yypvt[-4].int32; PENV->nExtCol=yypvt[-2].int32; PENV->nExtColEnd = yypvt[-0].int32; } break; case 765: #line 1912 "asmparse.y" { PENV->nExtLine = yypvt[-5].int32; PENV->nExtLineEnd = yypvt[-3].int32; PENV->nExtCol=yypvt[-1].int32; PENV->nExtColEnd = static_cast<unsigned>(-1); PASM->SetSourceFileName(yypvt[-0].string);} break; case 766: #line 1916 "asmparse.y" { PENV->nExtLine = yypvt[-4].int32; PENV->nExtLineEnd = yypvt[-2].int32; PENV->nExtCol=yypvt[-0].int32; PENV->nExtColEnd = static_cast<unsigned>(-1); } break; case 767: #line 1919 "asmparse.y" { PENV->nExtLine = yypvt[-7].int32; PENV->nExtLineEnd = yypvt[-5].int32; PENV->nExtCol=yypvt[-3].int32; PENV->nExtColEnd = yypvt[-1].int32; PASM->SetSourceFileName(yypvt[-0].string);} break; case 768: #line 1923 "asmparse.y" { PENV->nExtLine = yypvt[-6].int32; PENV->nExtLineEnd = yypvt[-4].int32; PENV->nExtCol=yypvt[-2].int32; PENV->nExtColEnd = yypvt[-0].int32; } break; case 769: #line 1925 "asmparse.y" { PENV->nExtLine = PENV->nExtLineEnd = yypvt[-1].int32 - 1; PENV->nExtCol = 0; PENV->nExtColEnd = static_cast<unsigned>(-1); PASM->SetSourceFileName(yypvt[-0].binstr);} break; case 770: #line 1932 "asmparse.y" { PASMM->AddFile(yypvt[-5].string, yypvt[-6].fileAttr|yypvt[-4].fileAttr|yypvt[-0].fileAttr, yypvt[-2].binstr); } break; case 771: #line 1933 "asmparse.y" { PASMM->AddFile(yypvt[-1].string, yypvt[-2].fileAttr|yypvt[-0].fileAttr, NULL); } break; case 772: #line 1936 "asmparse.y" { yyval.fileAttr = (CorFileFlags) 0; } break; case 773: #line 1937 "asmparse.y" { yyval.fileAttr = (CorFileFlags) (yypvt[-1].fileAttr | ffContainsNoMetaData); } break; case 774: #line 1940 "asmparse.y" { yyval.fileAttr = (CorFileFlags) 0; } break; case 775: #line 1941 "asmparse.y" { yyval.fileAttr = (CorFileFlags) 0x80000000; } break; case 776: #line 1944 "asmparse.y" { bParsingByteArray = TRUE; } break; case 777: #line 1947 "asmparse.y" { PASMM->StartAssembly(yypvt[-0].string, NULL, (DWORD)yypvt[-1].asmAttr, FALSE); } break; case 778: #line 1950 "asmparse.y" { yyval.asmAttr = (CorAssemblyFlags) 0; } break; case 779: #line 1951 "asmparse.y" { yyval.asmAttr = (CorAssemblyFlags) (yypvt[-1].asmAttr | afRetargetable); } break; case 780: #line 1952 "asmparse.y" { yyval.asmAttr = (CorAssemblyFlags) (yypvt[-1].asmAttr | afContentType_WindowsRuntime); } break; case 781: #line 1953 "asmparse.y" { yyval.asmAttr = (CorAssemblyFlags) (yypvt[-1].asmAttr | afPA_NoPlatform); } break; case 782: #line 1954 "asmparse.y" { yyval.asmAttr = yypvt[-2].asmAttr; } break; case 783: #line 1955 "asmparse.y" { SET_PA(yyval.asmAttr,yypvt[-1].asmAttr,afPA_MSIL); } break; case 784: #line 1956 "asmparse.y" { SET_PA(yyval.asmAttr,yypvt[-1].asmAttr,afPA_x86); } break; case 785: #line 1957 "asmparse.y" { SET_PA(yyval.asmAttr,yypvt[-1].asmAttr,afPA_AMD64); } break; case 786: #line 1958 "asmparse.y" { SET_PA(yyval.asmAttr,yypvt[-1].asmAttr,afPA_ARM); } break; case 787: #line 1959 "asmparse.y" { SET_PA(yyval.asmAttr,yypvt[-1].asmAttr,afPA_ARM64); } break; case 790: #line 1966 "asmparse.y" { PASMM->SetAssemblyHashAlg(yypvt[-0].int32); } break; case 793: #line 1971 "asmparse.y" { yyval.int32 = yypvt[-0].int32; } break; case 794: #line 1972 "asmparse.y" { yyval.int32 = 0xFFFF; } break; case 795: #line 1975 "asmparse.y" { PASMM->SetAssemblyPublicKey(yypvt[-1].binstr); } break; case 796: #line 1977 "asmparse.y" { PASMM->SetAssemblyVer((USHORT)yypvt[-6].int32, (USHORT)yypvt[-4].int32, (USHORT)yypvt[-2].int32, (USHORT)yypvt[-0].int32); } break; case 797: #line 1978 "asmparse.y" { yypvt[-0].binstr->appendInt8(0); PASMM->SetAssemblyLocale(yypvt[-0].binstr,TRUE); } break; case 798: #line 1979 "asmparse.y" { PASMM->SetAssemblyLocale(yypvt[-1].binstr,FALSE); } break; case 801: #line 1984 "asmparse.y" { bParsingByteArray = TRUE; } break; case 802: #line 1987 "asmparse.y" { bParsingByteArray = TRUE; } break; case 803: #line 1990 "asmparse.y" { bParsingByteArray = TRUE; } break; case 804: #line 1994 "asmparse.y" { PASMM->StartAssembly(yypvt[-0].string, NULL, yypvt[-1].asmAttr, TRUE); } break; case 805: #line 1996 "asmparse.y" { PASMM->StartAssembly(yypvt[-2].string, yypvt[-0].string, yypvt[-3].asmAttr, TRUE); } break; case 808: #line 2003 "asmparse.y" { PASMM->SetAssemblyHashBlob(yypvt[-1].binstr); } break; case 810: #line 2005 "asmparse.y" { PASMM->SetAssemblyPublicKeyToken(yypvt[-1].binstr); } break; case 811: #line 2006 "asmparse.y" { PASMM->SetAssemblyAutodetect(); } break; case 812: #line 2009 "asmparse.y" { PASMM->StartComType(yypvt[-0].string, yypvt[-1].exptAttr);} break; case 813: #line 2012 "asmparse.y" { PASMM->StartComType(yypvt[-0].string, yypvt[-1].exptAttr); } break; case 814: #line 2015 "asmparse.y" { yyval.exptAttr = (CorTypeAttr) 0; } break; case 815: #line 2016 "asmparse.y" { yyval.exptAttr = (CorTypeAttr) (yypvt[-1].exptAttr | tdNotPublic); } break; case 816: #line 2017 "asmparse.y" { yyval.exptAttr = (CorTypeAttr) (yypvt[-1].exptAttr | tdPublic); } break; case 817: #line 2018 "asmparse.y" { yyval.exptAttr = (CorTypeAttr) (yypvt[-1].exptAttr | tdForwarder); } break; case 818: #line 2019 "asmparse.y" { yyval.exptAttr = (CorTypeAttr) (yypvt[-2].exptAttr | tdNestedPublic); } break; case 819: #line 2020 "asmparse.y" { yyval.exptAttr = (CorTypeAttr) (yypvt[-2].exptAttr | tdNestedPrivate); } break; case 820: #line 2021 "asmparse.y" { yyval.exptAttr = (CorTypeAttr) (yypvt[-2].exptAttr | tdNestedFamily); } break; case 821: #line 2022 "asmparse.y" { yyval.exptAttr = (CorTypeAttr) (yypvt[-2].exptAttr | tdNestedAssembly); } break; case 822: #line 2023 "asmparse.y" { yyval.exptAttr = (CorTypeAttr) (yypvt[-2].exptAttr | tdNestedFamANDAssem); } break; case 823: #line 2024 "asmparse.y" { yyval.exptAttr = (CorTypeAttr) (yypvt[-2].exptAttr | tdNestedFamORAssem); } break; case 826: #line 2031 "asmparse.y" { PASMM->SetComTypeFile(yypvt[-0].string); } break; case 827: #line 2032 "asmparse.y" { PASMM->SetComTypeComType(yypvt[-0].string); } break; case 828: #line 2033 "asmparse.y" { PASMM->SetComTypeAsmRef(yypvt[-0].string); } break; case 829: #line 2034 "asmparse.y" { if(!PASMM->SetComTypeImplementationTok(yypvt[-1].int32)) PASM->report->error("Invalid implementation of exported type\n"); } break; case 830: #line 2036 "asmparse.y" { if(!PASMM->SetComTypeClassTok(yypvt[-0].int32)) PASM->report->error("Invalid TypeDefID of exported type\n"); } break; case 833: #line 2042 "asmparse.y" { PASMM->StartManifestRes(yypvt[-0].string, yypvt[-0].string, yypvt[-1].manresAttr); } break; case 834: #line 2044 "asmparse.y" { PASMM->StartManifestRes(yypvt[-2].string, yypvt[-0].string, yypvt[-3].manresAttr); } break; case 835: #line 2047 "asmparse.y" { yyval.manresAttr = (CorManifestResourceFlags) 0; } break; case 836: #line 2048 "asmparse.y" { yyval.manresAttr = (CorManifestResourceFlags) (yypvt[-1].manresAttr | mrPublic); } break; case 837: #line 2049 "asmparse.y" { yyval.manresAttr = (CorManifestResourceFlags) (yypvt[-1].manresAttr | mrPrivate); } break; case 840: #line 2056 "asmparse.y" { PASMM->SetManifestResFile(yypvt[-2].string, (ULONG)yypvt[-0].int32); } break; case 841: #line 2057 "asmparse.y" { PASMM->SetManifestResAsmRef(yypvt[-0].string); } break;/* End of actions */ #line 329 "F:\\NetFXDev1\\src\\tools\\devdiv\\amd64\\yypars.c" } } goto yystack; /* stack new state and value */ } #pragma warning(default:102) #ifdef YYDUMP YYLOCAL void YYNEAR YYPASCAL yydumpinfo(void) { short stackindex; short valindex; //dump yys printf("short yys[%d] {\n", YYMAXDEPTH); for (stackindex = 0; stackindex < YYMAXDEPTH; stackindex++){ if (stackindex) printf(", %s", stackindex % 10 ? "\0" : "\n"); printf("%6d", yys[stackindex]); } printf("\n};\n"); //dump yyv printf("YYSTYPE yyv[%d] {\n", YYMAXDEPTH); for (valindex = 0; valindex < YYMAXDEPTH; valindex++){ if (valindex) printf(", %s", valindex % 5 ? "\0" : "\n"); printf("%#*x", 3+sizeof(YYSTYPE), yyv[valindex]); } printf("\n};\n"); } #endif
/* * Created by Microsoft VCBU Internal YACC from "asmparse.y" */ #line 2 "asmparse.y" // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // File asmparse.y // #include "ilasmpch.h" #include "grammar_before.cpp" #line 16 "asmparse.y" #define UNION 1 typedef union { CorRegTypeAttr classAttr; CorMethodAttr methAttr; CorFieldAttr fieldAttr; CorMethodImpl implAttr; CorEventAttr eventAttr; CorPropertyAttr propAttr; CorPinvokeMap pinvAttr; CorDeclSecurity secAct; CorFileFlags fileAttr; CorAssemblyFlags asmAttr; CorAssemblyFlags asmRefAttr; CorTypeAttr exptAttr; CorManifestResourceFlags manresAttr; double* float64; __int64* int64; __int32 int32; char* string; BinStr* binstr; Labels* labels; Instr* instr; // instruction opcode NVPair* pair; pTyParList typarlist; mdToken token; TypeDefDescr* tdd; CustomDescr* cad; unsigned short opcode; } YYSTYPE; # define ERROR_ 257 # define BAD_COMMENT_ 258 # define BAD_LITERAL_ 259 # define ID 260 # define DOTTEDNAME 261 # define QSTRING 262 # define SQSTRING 263 # define INT32 264 # define INT64 265 # define FLOAT64 266 # define HEXBYTE 267 # define TYPEDEF_T 268 # define TYPEDEF_M 269 # define TYPEDEF_F 270 # define TYPEDEF_TS 271 # define TYPEDEF_MR 272 # define TYPEDEF_CA 273 # define DCOLON 274 # define ELIPSIS 275 # define VOID_ 276 # define BOOL_ 277 # define CHAR_ 278 # define UNSIGNED_ 279 # define INT_ 280 # define INT8_ 281 # define INT16_ 282 # define INT32_ 283 # define INT64_ 284 # define FLOAT_ 285 # define FLOAT32_ 286 # define FLOAT64_ 287 # define BYTEARRAY_ 288 # define UINT_ 289 # define UINT8_ 290 # define UINT16_ 291 # define UINT32_ 292 # define UINT64_ 293 # define FLAGS_ 294 # define CALLCONV_ 295 # define MDTOKEN_ 296 # define OBJECT_ 297 # define STRING_ 298 # define NULLREF_ 299 # define DEFAULT_ 300 # define CDECL_ 301 # define VARARG_ 302 # define STDCALL_ 303 # define THISCALL_ 304 # define FASTCALL_ 305 # define CLASS_ 306 # define TYPEDREF_ 307 # define UNMANAGED_ 308 # define FINALLY_ 309 # define HANDLER_ 310 # define CATCH_ 311 # define FILTER_ 312 # define FAULT_ 313 # define EXTENDS_ 314 # define IMPLEMENTS_ 315 # define TO_ 316 # define AT_ 317 # define TLS_ 318 # define TRUE_ 319 # define FALSE_ 320 # define _INTERFACEIMPL 321 # define VALUE_ 322 # define VALUETYPE_ 323 # define NATIVE_ 324 # define INSTANCE_ 325 # define SPECIALNAME_ 326 # define FORWARDER_ 327 # define STATIC_ 328 # define PUBLIC_ 329 # define PRIVATE_ 330 # define FAMILY_ 331 # define FINAL_ 332 # define SYNCHRONIZED_ 333 # define INTERFACE_ 334 # define SEALED_ 335 # define NESTED_ 336 # define ABSTRACT_ 337 # define AUTO_ 338 # define SEQUENTIAL_ 339 # define EXPLICIT_ 340 # define ANSI_ 341 # define UNICODE_ 342 # define AUTOCHAR_ 343 # define IMPORT_ 344 # define ENUM_ 345 # define VIRTUAL_ 346 # define NOINLINING_ 347 # define AGGRESSIVEINLINING_ 348 # define NOOPTIMIZATION_ 349 # define AGGRESSIVEOPTIMIZATION_ 350 # define UNMANAGEDEXP_ 351 # define BEFOREFIELDINIT_ 352 # define STRICT_ 353 # define RETARGETABLE_ 354 # define WINDOWSRUNTIME_ 355 # define NOPLATFORM_ 356 # define METHOD_ 357 # define FIELD_ 358 # define PINNED_ 359 # define MODREQ_ 360 # define MODOPT_ 361 # define SERIALIZABLE_ 362 # define PROPERTY_ 363 # define TYPE_ 364 # define ASSEMBLY_ 365 # define FAMANDASSEM_ 366 # define FAMORASSEM_ 367 # define PRIVATESCOPE_ 368 # define HIDEBYSIG_ 369 # define NEWSLOT_ 370 # define RTSPECIALNAME_ 371 # define PINVOKEIMPL_ 372 # define _CTOR 373 # define _CCTOR 374 # define LITERAL_ 375 # define NOTSERIALIZED_ 376 # define INITONLY_ 377 # define REQSECOBJ_ 378 # define CIL_ 379 # define OPTIL_ 380 # define MANAGED_ 381 # define FORWARDREF_ 382 # define PRESERVESIG_ 383 # define RUNTIME_ 384 # define INTERNALCALL_ 385 # define _IMPORT 386 # define NOMANGLE_ 387 # define LASTERR_ 388 # define WINAPI_ 389 # define AS_ 390 # define BESTFIT_ 391 # define ON_ 392 # define OFF_ 393 # define CHARMAPERROR_ 394 # define INSTR_NONE 395 # define INSTR_VAR 396 # define INSTR_I 397 # define INSTR_I8 398 # define INSTR_R 399 # define INSTR_BRTARGET 400 # define INSTR_METHOD 401 # define INSTR_FIELD 402 # define INSTR_TYPE 403 # define INSTR_STRING 404 # define INSTR_SIG 405 # define INSTR_TOK 406 # define INSTR_SWITCH 407 # define _CLASS 408 # define _NAMESPACE 409 # define _METHOD 410 # define _FIELD 411 # define _DATA 412 # define _THIS 413 # define _BASE 414 # define _NESTER 415 # define _EMITBYTE 416 # define _TRY 417 # define _MAXSTACK 418 # define _LOCALS 419 # define _ENTRYPOINT 420 # define _ZEROINIT 421 # define _EVENT 422 # define _ADDON 423 # define _REMOVEON 424 # define _FIRE 425 # define _OTHER 426 # define _PROPERTY 427 # define _SET 428 # define _GET 429 # define _PERMISSION 430 # define _PERMISSIONSET 431 # define REQUEST_ 432 # define DEMAND_ 433 # define ASSERT_ 434 # define DENY_ 435 # define PERMITONLY_ 436 # define LINKCHECK_ 437 # define INHERITCHECK_ 438 # define REQMIN_ 439 # define REQOPT_ 440 # define REQREFUSE_ 441 # define PREJITGRANT_ 442 # define PREJITDENY_ 443 # define NONCASDEMAND_ 444 # define NONCASLINKDEMAND_ 445 # define NONCASINHERITANCE_ 446 # define _LINE 447 # define P_LINE 448 # define _LANGUAGE 449 # define _CUSTOM 450 # define INIT_ 451 # define _SIZE 452 # define _PACK 453 # define _VTABLE 454 # define _VTFIXUP 455 # define FROMUNMANAGED_ 456 # define CALLMOSTDERIVED_ 457 # define _VTENTRY 458 # define RETAINAPPDOMAIN_ 459 # define _FILE 460 # define NOMETADATA_ 461 # define _HASH 462 # define _ASSEMBLY 463 # define _PUBLICKEY 464 # define _PUBLICKEYTOKEN 465 # define ALGORITHM_ 466 # define _VER 467 # define _LOCALE 468 # define EXTERN_ 469 # define _MRESOURCE 470 # define _MODULE 471 # define _EXPORT 472 # define LEGACY_ 473 # define LIBRARY_ 474 # define X86_ 475 # define AMD64_ 476 # define ARM_ 477 # define ARM64_ 478 # define MARSHAL_ 479 # define CUSTOM_ 480 # define SYSSTRING_ 481 # define FIXED_ 482 # define VARIANT_ 483 # define CURRENCY_ 484 # define SYSCHAR_ 485 # define DECIMAL_ 486 # define DATE_ 487 # define BSTR_ 488 # define TBSTR_ 489 # define LPSTR_ 490 # define LPWSTR_ 491 # define LPTSTR_ 492 # define OBJECTREF_ 493 # define IUNKNOWN_ 494 # define IDISPATCH_ 495 # define STRUCT_ 496 # define SAFEARRAY_ 497 # define BYVALSTR_ 498 # define LPVOID_ 499 # define ANY_ 500 # define ARRAY_ 501 # define LPSTRUCT_ 502 # define IIDPARAM_ 503 # define IN_ 504 # define OUT_ 505 # define OPT_ 506 # define _PARAM 507 # define _OVERRIDE 508 # define WITH_ 509 # define NULL_ 510 # define HRESULT_ 511 # define CARRAY_ 512 # define USERDEFINED_ 513 # define RECORD_ 514 # define FILETIME_ 515 # define BLOB_ 516 # define STREAM_ 517 # define STORAGE_ 518 # define STREAMED_OBJECT_ 519 # define STORED_OBJECT_ 520 # define BLOB_OBJECT_ 521 # define CF_ 522 # define CLSID_ 523 # define VECTOR_ 524 # define _SUBSYSTEM 525 # define _CORFLAGS 526 # define ALIGNMENT_ 527 # define _IMAGEBASE 528 # define _STACKRESERVE 529 # define _TYPEDEF 530 # define _TEMPLATE 531 # define _TYPELIST 532 # define _MSCORLIB 533 # define P_DEFINE 534 # define P_UNDEF 535 # define P_IFDEF 536 # define P_IFNDEF 537 # define P_ELSE 538 # define P_ENDIF 539 # define P_INCLUDE 540 # define CONSTRAINT_ 541 #define yyclearin yychar = -1 #define yyerrok yyerrflag = 0 #ifndef YYMAXDEPTH #define YYMAXDEPTH 150 #endif YYSTYPE yylval, yyval; #ifndef YYFARDATA #define YYFARDATA /*nothing*/ #endif #if ! defined YYSTATIC #define YYSTATIC /*nothing*/ #endif #if ! defined YYCONST #define YYCONST /*nothing*/ #endif #ifndef YYACT #define YYACT yyact #endif #ifndef YYPACT #define YYPACT yypact #endif #ifndef YYPGO #define YYPGO yypgo #endif #ifndef YYR1 #define YYR1 yyr1 #endif #ifndef YYR2 #define YYR2 yyr2 #endif #ifndef YYCHK #define YYCHK yychk #endif #ifndef YYDEF #define YYDEF yydef #endif #ifndef YYV #define YYV yyv #endif #ifndef YYS #define YYS yys #endif #ifndef YYLOCAL #define YYLOCAL #endif #ifndef YYR_T #define YYR_T int #endif typedef YYR_T yyr_t; #ifndef YYEXIND_T #define YYEXIND_T unsigned int #endif typedef YYEXIND_T yyexind_t; #ifndef YYOPTTIME #define YYOPTTIME 0 #endif # define YYERRCODE 256 #line 2062 "asmparse.y" #include "grammar_after.cpp" YYSTATIC YYCONST short yyexca[] = { #if !(YYOPTTIME) -1, 1, #endif 0, -1, -2, 0, #if !(YYOPTTIME) -1, 452, #endif 41, 538, -2, 311, #if !(YYOPTTIME) -1, 622, #endif 274, 555, 47, 555, -2, 230, #if !(YYOPTTIME) -1, 643, #endif 40, 310, 60, 310, -2, 555, #if !(YYOPTTIME) -1, 665, #endif 41, 538, -2, 311, #if !(YYOPTTIME) -1, 690, #endif 274, 555, 47, 555, -2, 516, #if !(YYOPTTIME) -1, 809, #endif 123, 235, -2, 555, #if !(YYOPTTIME) -1, 836, #endif 41, 538, -2, 311, #if !(YYOPTTIME) -1, 961, #endif 41, 538, -2, 311, #if !(YYOPTTIME) -1, 994, #endif 41, 538, -2, 311, #if !(YYOPTTIME) -1, 995, #endif 41, 538, -2, 311, #if !(YYOPTTIME) -1, 1323, #endif 41, 538, -2, 311, #if !(YYOPTTIME) -1, 1324, #endif 41, 538, -2, 311, #if !(YYOPTTIME) -1, 1331, #endif 41, 538, -2, 311, #if !(YYOPTTIME) -1, 1339, #endif 41, 538, -2, 311, #if !(YYOPTTIME) -1, 1465, #endif 41, 538, -2, 311, #if !(YYOPTTIME) -1, 1497, #endif 41, 538, -2, 311, #if !(YYOPTTIME) -1, 1564, #endif 41, 538, -2, 311, #if !(YYOPTTIME) -1, 1581, #endif 41, 538, -2, 311, }; # define YYNPROD 844 #if YYOPTTIME YYSTATIC YYCONST yyexind_t yyexcaind[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 30, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 34, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 38, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 42, 46, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 50, 54, 0, 0, 0, 0, 0, 0, 58, 0, 0, 0, 0, 0, 0, 0, 62, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 70, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 74, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 78 }; #endif # define YYLAST 3922 YYSTATIC YYCONST short YYFARDATA YYACT[] = { 703, 1484, 414, 1416, 1133, 640, 660, 191, 1482, 1485, 886, 1036, 971, 1483, 702, 788, 779, 885, 974, 729, 73, 75, 150, 625, 1521, 536, 1417, 792, 755, 190, 760, 757, 478, 176, 107, 972, 1146, 110, 106, 694, 1077, 275, 860, 604, 662, 599, 273, 78, 81, 219, 44, 24, 780, 262, 516, 214, 204, 7, 301, 188, 654, 76, 6, 991, 85, 5, 1569, 3, 1206, 1253, 220, 1125, 18, 1257, 115, 677, 1069, 264, 153, 1254, 307, 133, 74, 178, 179, 180, 181, 272, 1123, 218, 136, 10, 221, 300, 26, 137, 1070, 98, 278, 139, 217, 1124, 17, 202, 203, 581, 269, 74, 719, 716, 322, 265, 461, 113, 112, 700, 520, 939, 940, 352, 343, 88, 87, 353, 89, 462, 1255, 452, 1025, 268, 676, 338, 56, 537, 68, 1243, 1244, 305, 591, 88, 87, 357, 89, 277, 225, 327, 277, 368, 339, 1031, 342, 938, 361, 366, 185, 154, 1241, 1242, 98, 360, 359, 358, 277, 56, 88, 87, 345, 89, 656, 1573, 192, 782, 351, 783, 348, 365, 1537, 277, 86, 1039, 369, 310, 312, 314, 316, 318, 374, 277, 362, 198, 1038, 364, 699, 373, 199, 271, 200, 698, 1432, 84, 105, 379, 201, 417, 418, 363, 376, 1138, 1139, 450, 387, 451, 615, 88, 87, 186, 89, 388, 480, 195, 814, 1071, 663, 1505, 456, 767, 1279, 457, 1578, 999, 258, 473, 475, 416, 196, 1496, 484, 655, 481, 482, 470, 491, 468, 472, 471, 501, 346, 216, 495, 1329, 597, 1214, 192, 493, 441, 24, 833, 476, 479, 375, 433, 7, 1278, 56, 801, 813, 486, 432, 664, 74, 428, 492, 429, 483, 541, 436, 18, 641, 642, 487, 586, 376, 585, 584, 544, 56, 1354, 1355, 1356, 587, 941, 942, 267, 943, 435, 10, 154, 442, 26, 1337, 1336, 1335, 1334, 494, 791, 434, 17, 777, 542, 572, 74, 545, 714, 668, 575, 268, 576, 1249, 577, 1517, 499, 600, 862, 863, 864, 579, 580, 371, 370, 1009, 116, 511, 511, 528, 534, 108, 574, 372, 258, 571, 266, 549, 573, 192, 488, 367, 88, 87, 154, 89, 321, 1559, 601, 512, 512, 529, 535, 80, 79, 480, 198, 505, 152, 410, 1435, 199, 74, 200, 613, 1560, 348, 582, 583, 201, 74, 1130, 480, 46, 498, 481, 482, 375, 621, 88, 596, 459, 89, 624, 80, 79, 195, 1563, 607, 608, 609, 610, 481, 482, 1562, 606, 420, 614, 421, 422, 423, 196, 745, 1368, 612, 474, 611, 619, 620, 622, 485, 340, 341, 678, 1352, 639, 644, 74, 1561, 500, 88, 87, 1248, 89, 1128, 955, 56, 1153, 600, 595, 784, 135, 1154, 759, 649, 650, 354, 355, 356, 652, 635, 1507, 1536, 348, 884, 182, 643, 785, 56, 704, 1138, 1139, 666, 1408, 855, 321, 177, 88, 674, 1140, 89, 74, 669, 1531, 970, 1514, 685, 682, 951, 347, 566, 88, 1246, 46, 89, 74, 538, 1506, 1267, 569, 1528, 867, 1362, 747, 88, 87, 689, 89, 74, 671, 673, 1192, 1358, 1142, 696, 88, 87, 786, 89, 990, 989, 988, 588, 983, 982, 981, 980, 758, 978, 979, 105, 706, 987, 986, 985, 984, 537, 690, 1468, 977, 975, 651, 715, 1001, 1002, 1003, 1004, 88, 87, 692, 954, 177, 376, 693, 453, 155, 648, 705, 80, 79, 480, 683, 701, 546, 727, 707, 805, 61, 62, 47, 63, 709, 803, 710, 713, 1256, 861, 539, 460, 645, 481, 482, 718, 177, 1520, 647, 56, 1530, 88, 87, 225, 89, 74, 723, 1191, 659, 728, 646, 967, 730, 277, 1529, 724, 597, 725, 675, 976, 720, 80, 79, 1129, 762, 679, 680, 681, 413, 734, 82, 506, 1526, 56, 768, 769, 49, 50, 51, 52, 53, 54, 55, 74, 639, 1262, 1258, 1259, 1260, 1261, 74, 754, 1524, 601, 744, 733, 748, 749, 750, 1013, 98, 1011, 1012, 787, 543, 502, 72, 49, 50, 51, 52, 53, 54, 55, 74, 643, 74, 684, 1522, 477, 61, 62, 47, 63, 88, 87, 542, 89, 807, 808, 802, 71, 751, 752, 753, 812, 793, 821, 74, 514, 825, 819, 826, 822, 74, 695, 216, 70, 830, 1184, 1183, 1182, 1181, 156, 157, 158, 831, 804, 806, 74, 809, 74, 815, 480, 773, 774, 775, 790, 325, 841, 842, 823, 797, 69, 800, 818, 80, 79, 67, 377, 824, 832, 324, 481, 482, 348, 348, 854, 88, 87, 225, 89, 834, 858, 88, 87, 865, 89, 1153, 375, 672, 66, 930, 1154, 627, 628, 629, 49, 50, 51, 52, 53, 54, 55, 192, 944, 945, 868, 56, 853, 1153, 277, 856, 88, 87, 1154, 89, 74, 857, 49, 50, 51, 52, 53, 54, 55, 601, 957, 600, 1457, 630, 631, 632, 950, 1076, 1072, 1073, 1074, 1075, 1455, 946, 152, 1344, 46, 382, 383, 384, 385, 111, 177, 80, 79, 852, 74, 88, 87, 993, 89, 859, 348, 773, 88, 87, 1021, 89, 1022, 1019, 74, 1453, 362, 963, 956, 960, 966, 1018, 1451, 932, 46, 933, 934, 935, 936, 937, 216, 823, 74, 1032, 1434, 593, 1035, 637, 276, 1343, 968, 823, 606, 766, 997, 696, 696, 496, 1026, 1044, 1020, 1425, 74, 441, 1007, 1016, 1424, 1422, 1407, 433, 1027, 962, 1049, 829, 1024, 1047, 432, 1029, 1028, 428, 517, 429, 1051, 1042, 436, 1006, 1014, 528, 74, 1405, 80, 79, 480, 840, 1045, 1046, 1395, 145, 973, 519, 1411, 670, 765, 435, 1005, 1015, 442, 1008, 1017, 529, 823, 1062, 481, 482, 434, 1057, 88, 87, 337, 89, 1393, 49, 50, 51, 52, 53, 54, 55, 592, 277, 636, 277, 1391, 326, 323, 56, 152, 1389, 1067, 1387, 1385, 277, 1383, 49, 50, 51, 52, 53, 54, 55, 1381, 1379, 1376, 1373, 962, 1371, 1367, 41, 43, 1351, 1327, 1209, 1208, 1056, 996, 1055, 1134, 88, 87, 1315, 89, 762, 1079, 1054, 1080, 155, 776, 63, 722, 46, 1053, 543, 1034, 1033, 1144, 828, 1150, 1252, 616, 504, 820, 513, 737, 1131, 508, 509, 618, 1136, 617, 1141, 578, 522, 527, 177, 565, 1065, 1251, 308, 455, 1313, 109, 63, 1137, 1197, 92, 1145, 1198, 1195, 1196, 964, 1316, 770, 1037, 520, 1311, 513, 521, 1349, 508, 509, 1309, 1187, 1143, 695, 695, 992, 1194, 1193, 145, 1207, 1190, 953, 1210, 1185, 1, 1418, 1189, 1199, 1200, 1201, 1202, 1179, 1177, 1175, 1066, 589, 1234, 1203, 1204, 1205, 1314, 49, 50, 51, 52, 53, 54, 55, 712, 348, 88, 87, 1217, 89, 626, 1312, 590, 1211, 1245, 1063, 1152, 1310, 1188, 1247, 152, 1218, 1239, 1173, 1171, 1169, 145, 1238, 1237, 1240, 1186, 49, 50, 51, 52, 53, 54, 55, 1180, 1178, 1176, 88, 87, 348, 89, 74, 1167, 1165, 205, 155, 525, 352, 1250, 711, 708, 353, 156, 157, 158, 1163, 192, 192, 192, 192, 1135, 634, 277, 1161, 277, 1127, 192, 192, 192, 357, 1174, 1172, 1170, 177, 591, 412, 378, 1433, 626, 1263, 192, 46, 1159, 187, 794, 97, 88, 87, 63, 89, 1157, 1430, 949, 1168, 1166, 1508, 1138, 1139, 524, 1155, 351, 526, 317, 1266, 527, 1280, 1164, 1284, 315, 1286, 1288, 1289, 1270, 1292, 1162, 1294, 1295, 1296, 1297, 1298, 1299, 1300, 1274, 1302, 1303, 1304, 1305, 1306, 1307, 1308, 1269, 1429, 313, 1160, 1317, 1318, 1291, 1320, 1293, 1428, 1319, 1158, 1287, 1285, 1290, 152, 1301, 311, 1419, 1236, 1156, 309, 1282, 308, 1060, 1322, 1212, 306, 1213, 308, 1059, 844, 1328, 746, 667, 1233, 1333, 352, 1332, 45, 94, 353, 49, 50, 51, 52, 53, 54, 55, 454, 328, 329, 330, 308, 415, 88, 87, 277, 89, 357, 156, 157, 158, 155, 591, 1558, 823, 1345, 308, 1338, 1347, 1348, 308, 352, 1331, 332, 1330, 353, 308, 56, 277, 152, 1272, 1353, 1357, 1147, 525, 277, 140, 1215, 351, 177, 952, 1360, 1283, 357, 948, 1023, 1359, 277, 827, 1281, 277, 138, 1350, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 1470, 839, 591, 1469, 838, 1361, 351, 817, 63, 1397, 1398, 1399, 1400, 1401, 1402, 1403, 591, 1346, 524, 771, 764, 526, 1364, 258, 721, 796, 567, 117, 1409, 1410, 349, 1414, 1396, 1413, 352, 1571, 1415, 591, 772, 1043, 591, 591, 56, 1421, 1420, 931, 1583, 591, 1426, 331, 303, 333, 334, 335, 336, 1574, 357, 1152, 1572, 1565, 1541, 823, 1504, 1503, 88, 87, 1502, 89, 1412, 1472, 1467, 134, 155, 1464, 1341, 96, 1423, 1461, 104, 103, 102, 101, 1460, 99, 100, 105, 1456, 351, 156, 157, 158, 1454, 49, 50, 51, 52, 53, 54, 55, 1452, 177, 1450, 1437, 1509, 1431, 1427, 258, 1581, 697, 1406, 1510, 1404, 1394, 1462, 1392, 1463, 1390, 1388, 354, 355, 356, 97, 352, 1386, 836, 56, 353, 1473, 1474, 1475, 88, 87, 1466, 89, 1471, 1384, 531, 1382, 155, 88, 87, 1380, 89, 1378, 357, 1377, 1375, 1374, 1488, 350, 1152, 1372, 1370, 1486, 56, 1369, 1366, 1489, 1494, 1487, 88, 1365, 1566, 89, 1342, 1340, 177, 1476, 1326, 1325, 1499, 1321, 1271, 46, 1498, 351, 1363, 1268, 1235, 1516, 56, 1126, 1523, 1525, 1527, 1064, 1523, 1525, 1527, 258, 1050, 206, 1534, 1525, 1048, 1041, 1040, 1532, 1538, 1501, 1539, 1535, 1540, 1533, 1519, 1030, 969, 959, 958, 947, 866, 1515, 1518, 1513, 849, 848, 846, 156, 157, 158, 449, 843, 193, 1511, 837, 194, 835, 816, 823, 795, 778, 742, 1523, 1525, 1527, 741, 740, 739, 354, 355, 356, 738, 736, 88, 735, 688, 89, 638, 198, 177, 570, 425, 424, 199, 344, 200, 46, 320, 1564, 1497, 1493, 201, 1492, 1491, 1490, 1570, 1465, 1459, 1458, 1568, 1449, 1448, 1447, 1446, 354, 355, 356, 1577, 195, 1575, 1445, 1580, 1579, 156, 157, 158, 1582, 1444, 1567, 1443, 1442, 1441, 1440, 196, 1439, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 1438, 1436, 823, 1315, 59, 523, 1313, 1576, 208, 259, 210, 228, 212, 213, 1311, 1309, 1339, 56, 88, 882, 1187, 89, 41, 43, 56, 1185, 876, 1179, 877, 878, 879, 46, 1177, 1175, 1173, 1171, 515, 1169, 1167, 61, 62, 47, 63, 1165, 1163, 1161, 1324, 354, 355, 356, 223, 1323, 1265, 96, 1264, 56, 104, 103, 102, 101, 46, 99, 100, 105, 222, 1078, 871, 872, 873, 1068, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 998, 1061, 1052, 46, 59, 995, 994, 426, 208, 259, 210, 228, 212, 213, 961, 851, 226, 224, 1058, 850, 847, 845, 41, 43, 732, 731, 717, 691, 687, 870, 874, 875, 686, 880, 665, 633, 881, 603, 530, 61, 62, 47, 63, 49, 50, 51, 52, 53, 54, 55, 223, 602, 354, 355, 356, 594, 568, 548, 547, 497, 419, 411, 386, 319, 222, 304, 518, 302, 510, 507, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 503, 36, 184, 93, 59, 33, 469, 467, 208, 259, 210, 228, 212, 213, 466, 465, 226, 224, 95, 464, 244, 463, 41, 43, 227, 243, 215, 209, 1098, 38, 30, 58, 32, 59, 207, 211, 887, 31, 1010, 61, 62, 47, 63, 49, 50, 51, 52, 53, 54, 55, 223, 41, 43, 1000, 439, 38, 30, 58, 32, 59, 869, 799, 431, 798, 222, 46, 430, 427, 61, 62, 47, 63, 46, 540, 270, 60, 35, 41, 43, 83, 29, 21, 57, 34, 37, 25, 16, 263, 15, 189, 14, 39, 40, 261, 61, 62, 47, 63, 13, 226, 224, 60, 35, 46, 260, 12, 11, 21, 9, 8, 37, 4, 2, 444, 234, 242, 241, 39, 40, 240, 444, 239, 238, 237, 236, 235, 49, 50, 51, 52, 53, 54, 55, 233, 232, 231, 230, 229, 114, 77, 42, 756, 658, 657, 1500, 299, 19, 20, 90, 22, 23, 48, 183, 27, 28, 49, 50, 51, 52, 53, 54, 55, 1151, 761, 789, 1273, 965, 1149, 1148, 605, 1479, 1478, 19, 20, 1477, 22, 23, 48, 1495, 27, 28, 49, 50, 51, 52, 53, 54, 55, 882, 1481, 1480, 1216, 1132, 598, 661, 876, 781, 877, 878, 879, 448, 91, 58, 32, 59, 1081, 743, 448, 65, 58, 32, 59, 64, 197, 445, 883, 0, 0, 0, 446, 0, 445, 41, 43, 929, 0, 446, 0, 0, 41, 43, 0, 0, 0, 0, 871, 872, 873, 0, 61, 62, 47, 63, 1109, 437, 438, 61, 62, 47, 63, 0, 437, 438, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1085, 1086, 447, 1093, 1107, 1087, 1088, 1089, 1090, 447, 1091, 1092, 0, 1108, 1094, 1095, 1096, 1097, 63, 870, 874, 875, 0, 880, 0, 0, 881, 0, 532, 0, 0, 533, 0, 0, 0, 0, 0, 443, 440, 0, 0, 0, 0, 0, 443, 440, 0, 0, 0, 0, 0, 882, 0, 0, 0, 0, 193, 0, 876, 194, 877, 878, 879, 0, 49, 50, 51, 52, 53, 54, 55, 49, 50, 51, 52, 53, 54, 55, 0, 0, 0, 0, 198, 177, 0, 0, 0, 199, 0, 200, 0, 0, 0, 0, 0, 201, 901, 0, 871, 872, 873, 0, 49, 50, 51, 52, 53, 54, 55, 146, 928, 0, 195, 0, 0, 893, 894, 0, 902, 919, 895, 896, 897, 898, 0, 899, 900, 196, 920, 903, 904, 905, 906, 0, 0, 0, 0, 348, 0, 0, 0, 0, 0, 0, 870, 874, 875, 0, 880, 0, 0, 881, 1232, 1231, 1226, 0, 1225, 1224, 1223, 1222, 0, 1220, 1221, 105, 0, 1230, 1229, 1228, 1227, 0, 0, 0, 0, 917, 1219, 921, 0, 990, 989, 988, 923, 983, 982, 981, 980, 0, 978, 979, 105, 0, 987, 986, 985, 984, 0, 0, 925, 977, 975, 0, 1542, 0, 0, 0, 0, 0, 0, 1083, 1084, 0, 1099, 1100, 1101, 0, 1102, 1103, 0, 0, 1104, 1105, 0, 1106, 0, 0, 0, 0, 0, 0, 0, 926, 0, 0, 0, 0, 1082, 1110, 1111, 1112, 1113, 1114, 1115, 1116, 1117, 1118, 1119, 1120, 1121, 1122, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 901, 0, 0, 976, 0, 0, 1512, 0, 0, 0, 0, 0, 0, 0, 928, 0, 0, 0, 0, 893, 894, 0, 902, 919, 895, 896, 897, 898, 0, 899, 900, 0, 920, 903, 904, 905, 906, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 146, 0, 0, 0, 0, 888, 0, 889, 890, 891, 892, 907, 908, 909, 924, 910, 911, 912, 913, 914, 915, 916, 918, 922, 917, 0, 921, 927, 0, 0, 0, 923, 0, 175, 0, 0, 0, 151, 148, 163, 161, 170, 0, 164, 165, 166, 167, 925, 168, 169, 0, 0, 171, 172, 173, 174, 564, 1557, 152, 142, 162, 0, 0, 0, 0, 0, 0, 0, 141, 147, 0, 1547, 0, 0, 0, 0, 0, 0, 0, 0, 926, 0, 0, 0, 143, 144, 149, 1543, 556, 0, 550, 551, 552, 553, 0, 0, 1552, 0, 0, 146, 0, 0, 0, 0, 352, 0, 0, 0, 772, 0, 1553, 1554, 1555, 1556, 0, 0, 0, 0, 0, 160, 0, 0, 0, 0, 0, 0, 357, 558, 559, 560, 561, 0, 0, 555, 0, 0, 0, 562, 563, 554, 0, 0, 1544, 1545, 1546, 1548, 1549, 1550, 1551, 0, 0, 0, 0, 0, 0, 0, 0, 623, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 888, 0, 889, 890, 891, 892, 907, 908, 909, 924, 910, 911, 912, 913, 914, 915, 916, 918, 922, 990, 989, 988, 927, 983, 982, 981, 980, 0, 978, 979, 105, 0, 987, 986, 985, 984, 0, 0, 0, 977, 975, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 88, 87, 0, 89, 0, 0, 0, 0, 155, 0, 0, 175, 0, 0, 557, 151, 148, 163, 161, 170, 0, 164, 165, 166, 167, 0, 168, 169, 0, 0, 171, 172, 173, 174, 146, 0, 177, 142, 162, 352, 0, 0, 0, 353, 0, 0, 141, 147, 0, 976, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 357, 143, 144, 149, 0, 0, 175, 0, 0, 0, 0, 0, 163, 161, 170, 0, 164, 165, 166, 167, 0, 168, 169, 0, 0, 171, 172, 173, 174, 0, 0, 623, 1276, 162, 0, 0, 160, 159, 88, 87, 0, 89, 0, 0, 0, 0, 155, 0, 0, 175, 0, 0, 0, 151, 148, 163, 161, 170, 0, 164, 165, 166, 167, 0, 168, 169, 0, 0, 171, 172, 173, 174, 0, 0, 177, 142, 162, 0, 0, 0, 1277, 0, 0, 0, 141, 147, 0, 0, 0, 0, 297, 198, 156, 157, 158, 0, 199, 0, 200, 1275, 143, 144, 149, 0, 201, 0, 0, 0, 0, 0, 0, 0, 0, 0, 146, 0, 0, 0, 0, 352, 0, 195, 284, 353, 279, 280, 281, 282, 283, 63, 0, 0, 0, 287, 0, 160, 196, 354, 355, 356, 0, 357, 285, 0, 0, 0, 0, 295, 0, 286, 0, 641, 642, 0, 0, 0, 0, 0, 0, 0, 0, 288, 289, 290, 291, 292, 293, 294, 298, 0, 0, 0, 623, 0, 296, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 156, 157, 158, 0, 0, 0, 0, 0, 0, 88, 87, 0, 89, 0, 0, 0, 0, 155, 146, 0, 175, 0, 0, 0, 151, 148, 163, 161, 170, 0, 164, 165, 166, 167, 0, 168, 169, 0, 0, 171, 172, 173, 174, 0, 0, 177, 142, 162, 0, 0, 0, 0, 0, 0, 0, 141, 147, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 143, 144, 149, 0, 0, 274, 0, 0, 0, 0, 0, 0, 0, 0, 0, 146, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 160, 0, 354, 355, 356, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 641, 642, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 274, 0, 0, 0, 0, 0, 88, 87, 0, 89, 0, 0, 0, 0, 155, 0, 0, 175, 156, 157, 158, 151, 148, 163, 161, 170, 0, 164, 165, 166, 167, 0, 168, 169, 0, 0, 171, 172, 173, 174, 0, 146, 177, 142, 162, 0, 0, 0, 0, 0, 0, 0, 141, 147, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 143, 144, 149, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 274, 0, 88, 87, 160, 89, 354, 355, 356, 0, 155, 146, 0, 175, 0, 0, 0, 151, 148, 163, 161, 170, 0, 164, 165, 166, 167, 0, 168, 169, 0, 0, 171, 172, 173, 174, 0, 0, 177, 142, 162, 0, 0, 0, 0, 0, 0, 0, 141, 147, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 156, 157, 158, 0, 143, 144, 149, 0, 811, 274, 88, 87, 0, 89, 0, 0, 0, 0, 155, 0, 0, 175, 0, 146, 0, 151, 148, 163, 161, 170, 0, 164, 165, 166, 167, 0, 168, 169, 0, 160, 171, 172, 173, 174, 0, 0, 177, 142, 162, 0, 0, 0, 0, 810, 0, 0, 141, 147, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 143, 144, 149, 0, 0, 0, 0, 0, 0, 274, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 146, 0, 0, 156, 157, 158, 0, 0, 0, 0, 0, 0, 0, 0, 0, 160, 159, 88, 87, 0, 89, 0, 0, 0, 0, 155, 0, 0, 175, 0, 0, 0, 151, 148, 163, 161, 170, 0, 164, 165, 166, 167, 0, 168, 169, 0, 0, 171, 172, 173, 174, 0, 0, 177, 142, 162, 0, 0, 274, 0, 0, 0, 0, 141, 147, 0, 0, 0, 0, 0, 0, 156, 157, 158, 0, 0, 0, 0, 0, 143, 144, 149, 0, 0, 0, 0, 88, 87, 0, 89, 0, 0, 0, 0, 155, 0, 0, 175, 0, 0, 0, 151, 148, 163, 161, 170, 0, 164, 165, 166, 167, 0, 168, 169, 160, 0, 171, 172, 173, 174, 0, 0, 177, 142, 162, 0, 0, 0, 0, 0, 0, 0, 763, 147, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 146, 0, 143, 144, 149, 0, 0, 0, 0, 0, 0, 0, 88, 87, 0, 89, 0, 0, 0, 0, 155, 0, 0, 175, 156, 157, 158, 151, 148, 163, 161, 170, 0, 164, 165, 166, 167, 160, 168, 169, 0, 0, 171, 172, 173, 174, 0, 0, 177, 142, 162, 0, 0, 0, 0, 146, 0, 0, 141, 147, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 143, 144, 149, 0, 0, 0, 0, 88, 87, 0, 89, 0, 0, 0, 0, 155, 0, 0, 175, 156, 157, 158, 151, 148, 163, 161, 170, 0, 164, 165, 166, 167, 0, 168, 169, 653, 146, 171, 172, 173, 174, 0, 0, 177, 142, 162, 88, 87, 0, 89, 0, 0, 0, 141, 147, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 143, 144, 149, 0, 0, 0, 0, 0, 0, 0, 0, 409, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 156, 157, 158, 996, 0, 0, 146, 0, 0, 0, 0, 0, 0, 458, 0, 0, 0, 391, 0, 0, 0, 407, 0, 0, 389, 390, 0, 0, 0, 393, 394, 405, 395, 396, 397, 398, 399, 400, 401, 402, 392, 0, 0, 0, 0, 0, 0, 406, 0, 0, 404, 0, 0, 0, 0, 0, 0, 403, 0, 0, 146, 0, 0, 0, 726, 0, 408, 0, 0, 156, 157, 158, 489, 175, 490, 0, 0, 151, 148, 163, 161, 170, 0, 164, 165, 166, 167, 0, 168, 169, 0, 0, 171, 172, 173, 174, 0, 0, 177, 142, 162, 0, 0, 0, 0, 0, 0, 0, 141, 147, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 143, 144, 149, 380, 175, 381, 0, 0, 151, 148, 163, 161, 170, 0, 164, 165, 166, 167, 0, 168, 169, 0, 0, 171, 172, 173, 174, 0, 0, 0, 142, 162, 0, 0, 0, 160, 0, 0, 0, 141, 147, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 143, 144, 149, 0, 175, 0, 0, 0, 151, 148, 163, 161, 170, 0, 164, 165, 166, 167, 0, 168, 169, 0, 0, 171, 172, 173, 174, 0, 0, 0, 142, 162, 0, 0, 0, 160, 0, 0, 0, 141, 147, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 143, 144, 149, 0, 0, 0, 0, 0, 0, 0, 175, 0, 0, 0, 151, 148, 163, 161, 170, 0, 164, 165, 166, 167, 0, 168, 169, 0, 0, 171, 172, 173, 174, 0, 0, 160, 142, 162, 0, 0, 0, 0, 0, 0, 0, 141, 147, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 143, 144, 149, 175, 0, 0, 0, 151, 148, 163, 161, 170, 0, 164, 165, 166, 167, 0, 168, 169, 0, 0, 171, 172, 173, 174, 0, 0, 0, 142, 162, 0, 0, 0, 0, 160, 0, 0, 141, 147, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 143, 144, 149, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 160 }; YYSTATIC YYCONST short YYFARDATA YYPACT[] = { -1000, 1423,-1000, 609, 586,-1000,-1000,-1000,-1000,-1000, -1000,-1000, 581, 555, 539, 514,-1000,-1000,-1000, 102, 102, -466, 124, 124,-1000,-1000,-1000, 478,-1000, -115, 535,-1000, 907, 1099, 68, 903, 102, -355, -356,-1000, -139, 855, 68, 855,-1000,-1000,-1000, 172, 2319, 535, 535, 535, 535,-1000,-1000, 187,-1000,-1000,-1000, -164, 1074,-1000,-1000, 1825, 68, 68,-1000,-1000, 1368,-1000, -1000,-1000,-1000,-1000,-1000,-1000, 102, -121,-1000,-1000, -1000,-1000, 691, -120, 2983, 1193,-1000,-1000,-1000,-1000, 2436,-1000, 102,-1000, 1385,-1000, 1310, 1718, 68, 1169, 1163, 1159, 1144, 1120, 1114, 1716, 1518, 83,-1000, 102, 655, 878,-1000,-1000, 86, 1193, 535, 2983,-1000,-1000, -1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000, -1000,-1000,-1000, 1515, 185, 1288, 1061, -229, -230, -231, -238, 691,-1000, -101, 691, 1255, 312,-1000,-1000, 48, -1000, 3564, 239, 1081,-1000,-1000,-1000,-1000,-1000, 3394, -1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000, 504,-1000,-1000,-1000,-1000,-1000, 1193, 1715, 538, 1193, 1193, 1193,-1000, 3232, 123,-1000,-1000, 1714, 1066, 2884, -1000, 3564,-1000,-1000,-1000, 65, 65,-1000, 1713,-1000, -1000, 99, 1513, 1512, 1575, 1397,-1000,-1000, 102,-1000, 102, 87,-1000,-1000,-1000,-1000, 1173,-1000,-1000,-1000, -1000,-1000, 901, 102, 3193,-1000, 21, -69,-1000,-1000, 201, 102, 124, 610, 68, 201, 1255, 3339, 2983, -88, 65, 2884, 1712,-1000, 215,-1000,-1000,-1000,-1000,-1000, -1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000, 511, 545, 860, 1606,-1000, 100,-1000, 355, 691,-1000, -1000, 2983,-1000,-1000, 164, 1217, 65, 535,-1000,-1000, -1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000, -1000,-1000,-1000,-1000,-1000,-1000,-1000, 1711, 1710, 2114, 895, 349, 1284, 1709, 123, 1511, -48,-1000, 102, -48, -1000, 124,-1000, 102,-1000, 102,-1000, 102,-1000,-1000, -1000,-1000, 891,-1000, 102, 102,-1000, 1193,-1000,-1000, -1000, -369,-1000,-1000,-1000,-1000,-1000, 878, -47, 116, -1000,-1000, 1193, 999,-1000, 1299, 789, 1708,-1000, 170, 535, 157,-1000,-1000,-1000, 1704, 1690, 3564, 535, 535, 535, 535,-1000, 691,-1000,-1000, 3564, 228,-1000, 1193, -1000, -68,-1000, 1217, 879, 889, 887, 535, 535, 2721, -1000,-1000,-1000,-1000,-1000,-1000, 102, 1299, 1070,-1000, -1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000, -1000,-1000,-1000,-1000,-1000, 406,-1000,-1000,-1000, 1688, 1052,-1000, 791, 1508,-1000,-1000, 2580,-1000,-1000, 102, -1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000, 458, 446, 417,-1000,-1000,-1000,-1000,-1000, 102, 102, 402, 3124,-1000,-1000, -304, -196,-1000,-1000,-1000,-1000,-1000, -1000,-1000, -53, 1687,-1000, 102, 1158, 39, 65, 794, 640, 102,-1000, -69, 107, 107, 107, 107, 2983, 215, -1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000, -1000, 1685, 1681, 1506,-1000,-1000,-1000, 2721,-1000,-1000, -1000,-1000, 1299, 1680, 68, 3564,-1000, 201, 1285,-1000, -119, -124,-1000,-1000, -351,-1000,-1000, 68, 411, 454, 68,-1000,-1000, 1041,-1000,-1000, 68,-1000, 68,-1000, 1040, 991,-1000,-1000, 535, -157, -360, 1679,-1000,-1000, -1000,-1000, 535, -361,-1000,-1000, -346,-1000,-1000,-1000, 1282,-1000, 869, 535, 3564, 1193, 3510, 102, 108, 1181, -1000,-1000,-1000,-1000,-1000,-1000,-1000, 1678,-1000,-1000, -1000,-1000,-1000,-1000, 1677,-1000,-1000, 1385, 108, 1505, -1000, 1503, 883, 1502, 1498, 1497, 1496, 1492,-1000, 362, 1157,-1000, 97, 1193,-1000,-1000,-1000, 298, 535, 108, 388, 175, 3052,-1000,-1000, 1278, 1193,-1000, 793,-1000, -1000, -50, 2983, 2983, 943, 1277, 1217, 1193, 1193, 1193, 1193,-1000, 2418,-1000, 1193,-1000, 535, 535, 535, 867, 1193, 33, 1193, 494, 1491,-1000, 128,-1000,-1000,-1000, -1000,-1000,-1000, 102,-1000, 1299,-1000,-1000, 1255, 30, 1076,-1000,-1000, 1193, 1490, 1202,-1000,-1000,-1000,-1000, -1000,-1000, -10, 65, 465, 459, 2983, 2816, -106, -47, 1488, 1265,-1000,-1000, 3510, -53, 881, 102, -96, 3564, 102, 1193, 102, 1238, 876,-1000,-1000,-1000, 201,-1000, -1000,-1000,-1000,-1000,-1000,-1000, 102, 124,-1000, -18, 1193, 108, 1487, 1386, 1485, 1262, 1259,-1000, 123, 102, 102, 1482, 1155,-1000,-1000, 1299, 1674, 1477, 1673, 1476, 1475, 1672, 1668, 1193, 535,-1000, 535, 102, 141, 535, 68, 2983, 535, 706, 1298, 81, -182, 1471, 95, 1795, 131, 1877, 102,-1000, 1306,-1000, 900,-1000, 900, 900, 900, 900, 900, -166,-1000, 102, 102, 535,-1000,-1000, -1000,-1000,-1000,-1000, 1193, 1470, 1234, 1083,-1000,-1000, 347, 1230, 964, 271, 166,-1000, 46, 102, 1469, 1468, -1000, 3564, 1667, 1081, 1081, 1081, 535, 535,-1000, 941, 542, 128,-1000,-1000,-1000,-1000,-1000, 1467, 343, 226, 958, -96, 1659, 1658, 3449,-1000,-1000, 1568, 104, 204, 690, -96, 3564, 102, 1193, 102, 1235, -322, 535, 1193, -1000,-1000, 3564,-1000,-1000, 1193,-1000, -53, 81, 1466, -241,-1000,-1000, 1193, 2721, 874, 873, 2983, 945, -126, -137, 1457, 1456, 535, 1300,-1000, -53,-1000, 201, 201, -1000,-1000,-1000,-1000, 411,-1000,-1000,-1000,-1000,-1000, -1000,-1000, 1081, 1193, 1455, 102, 1193, 1451,-1000, 535, -96, 1655, 871, 864, 856, 854,-1000, 108, 1670,-1000, -1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000, 1154, 1148, 1654, 945, 123, 1446, 947, 68, 1639, -405, -56,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000, -1000,-1000, 495,-1000,-1000,-1000,-1000,-1000,-1000,-1000, -1000,-1000,-1000,-1000, 1635, 1635,-1000, 1635, 1762,-1000, -1000, -408,-1000, -387,-1000,-1000, -429,-1000,-1000,-1000, 1442,-1000,-1000,-1000,-1000,-1000,-1000,-1000, 123,-1000, -1000,-1000,-1000,-1000, 165, 331, 1193,-1000, 108, 829, 338,-1000, 3052, 374, 955,-1000,-1000,-1000,-1000,-1000, 1217, -53, 1081, 1193,-1000, 535, 1223, 2983,-1000,-1000, -1000, 393,-1000,-1000,-1000, 1111, 1102, 1094, 1075, 1067, 1055, 1054, 1033, 1032, 1031, 997, 996, 995, 399, 987, 975, 68, 455, 1076, -53, -53, 102, 938,-1000,-1000, -1000, 1255, 1255, 1255, 1255,-1000,-1000,-1000,-1000,-1000, -1000, 1255, 1255, 1255,-1000,-1000,-1000,-1000,-1000, -441, 2721, 853, 852, 2983,-1000, 1255, 1193, 1181,-1000, 123, -1000, 123, -23,-1000, 1227,-1000,-1000, 1913, 123, 102, -1000,-1000, 1193,-1000, 1439,-1000,-1000, 1143,-1000,-1000, -287, 998, 1877,-1000,-1000,-1000,-1000, 1299,-1000, -236, -257, 102,-1000,-1000,-1000,-1000, 383, 192, 108, 899, 880,-1000,-1000,-1000,-1000,-1000,-1000,-1000, -434,-1000, -1000, 35,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000, -1000,-1000,-1000, 336,-1000,-1000,-1000,-1000,-1000,-1000, -1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000, -1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000, -1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000, 102,-1000,-1000,-1000,-1000, 1624, 1299, 1622,-1000,-1000, -1000,-1000,-1000, 359, 1438, 1223,-1000, 128, 1433, 1220, -1000, 2375,-1000,-1000,-1000, -37, 102, 977, 102, 1938, 102, 110, 102, 93, 102, 124, 102, 102, 102, 102, 102, 102, 102, 124, 102, 102, 102, 102, 102, 102, 102, 974, 968, 953, 913, 102, 102, -112, 102, 1432, 1299,-1000,-1000, 1621, 1616, 1430, 1429, 851,-1000,-1000, -1000,-1000,-1000,-1000,-1000,-1000, 65, -25,-1000, 1214, -1000, 1216,-1000,-1000, -96, 2983,-1000,-1000, 1299,-1000, 1615, 1614, 1613, 1608, 1607, 1605, 18, 1604, 1603, 1602, 1597, 1595, 1590,-1000,-1000,-1000, 411,-1000, 1586, 1426, 1335,-1000,-1000,-1000,-1000, 1425,-1000, 740, 102,-1000, 1275, 102, 102, 950, 108, 850,-1000,-1000,-1000,-1000, -1000,-1000,-1000, 155, 102, 5, 371,-1000,-1000,-1000, -1000,-1000, 2983, 395,-1000,-1000,-1000, 1172, 1422, 1417, 847, 144, 1416, 1413, 846, 1412, 844, 1408, 1407, 843, 1406, 1404, 842, 1402, 841, 1398, 833, 1396, 831, 1384, 830, 1378, 828, 1377, 823, 1375, 811, 1373, 787, 124, 102, 102, 102, 102, 102, 102, 102, 1372, 780, 1370, 759,-1000, 332, -53, -53,-1000,-1000, 822, 3564, -96, 2983, -53, 969,-1000, 1585, 1584, 1576, 1573, 1142, -53, -1000,-1000,-1000,-1000, 102, 758, 108, 757, 752, 102, 1299,-1000,-1000, 1366, 1133, 1125, 1085, 1365,-1000, 73, -1000, 1068, 735, 101,-1000,-1000,-1000, 1571, 1363,-1000, -1000, 1570,-1000, 1556,-1000,-1000, 1554,-1000,-1000, 1553, -1000, 1552,-1000, 1551,-1000, 1549,-1000, 1542,-1000, 1535, -1000, 1534,-1000, 1533,-1000, 1532, 1362, 723, 1360, 716, 1352, 687, 1347, 677,-1000, 1530,-1000, 1529,-1000, 1343, 1338,-1000, 2721, 969,-1000, 1334, 1528,-1000, 857, 411, 1331, 429,-1000, 1261,-1000, 2042, 1330,-1000, 102, 102, 102,-1000,-1000, 1938,-1000,-1000,-1000,-1000,-1000,-1000, -1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000, -1000, 1526,-1000, 1525,-1000, 1524,-1000, 1522,-1000,-1000, -1000,-1000, -39, 1521, 945, -53,-1000,-1000,-1000, 108, -1000, 947,-1000, 1327, 1324, 1323,-1000, 182, 1106, 2264, 428, 278, 527, 608, 582, 562, 443, 544, 530, 426, -1000,-1000,-1000,-1000, 405, 135, -96, -53,-1000, 1321, 2115, 1203,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000, 88,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000, -1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000, -1000,-1000, 328, 381, 357, 350,-1000,-1000,-1000, 1520, 1320,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000, -1000,-1000,-1000,-1000,-1000,-1000,-1000, 1424, 108,-1000, -1000,-1000,-1000,-1000, -53, -443, 102, 1296, 1319, -188, 1316,-1000,-1000, 65,-1000, 3564, 2721, -46, -96, 969, 1369, -53, 1307,-1000 }; YYSTATIC YYCONST short YYFARDATA YYPGO[] = { 0, 33, 178, 5, 1991, 78, 39, 7, 1989, 0, 1988, 1984, 1982, 268, 80, 1981, 1977, 4, 1972, 52, 40, 3, 26, 32, 24, 6, 1970, 44, 41, 45, 1969, 38, 34, 10, 17, 11, 31, 1968, 42, 1967, 35, 18, 1966, 1965, 9, 1, 13, 8, 1954, 1950, 1947, 1946, 22, 27, 43, 1945, 1944, 1943, 1942, 15, 1941, 1940, 12, 1939, 30, 1938, 14, 36, 16, 23, 46, 2, 599, 59, 1236, 29, 106, 1928, 1924, 1921, 1920, 1919, 1918, 19, 28, 1917, 1329, 1916, 1915, 25, 789, 131, 1914, 50, 1221, 1913, 1912, 1911, 1910, 1909, 1901, 1900, 1899, 1898, 1897, 1895, 1892, 1891, 1890, 1028, 1888, 67, 56, 1887, 65, 134, 62, 55, 1885, 1884, 89, 1882, 1881, 1880, 1874, 1869, 1866, 53, 1864, 1863, 1862, 100, 70, 49, 1861, 92, 292, 1859, 1858, 1856, 1855, 1850, 1849, 1843, 1842, 1839, 1838, 1837, 1830, 832, 1829, 1814, 1813, 1812, 1811, 1810, 1803, 1802, 75, 1801, 1800, 125, 1797, 1796, 1795, 130, 1791, 1790, 1783, 1782, 1781, 1779, 1778, 58, 1760, 63, 1777, 54, 1776, 602, 1762, 1761, 1759, 1646, 1615, 1438 }; YYSTATIC YYCONST yyr_t YYFARDATA YYR1[]={ 0, 109, 109, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 136, 136, 36, 36, 133, 133, 133, 2, 2, 1, 1, 1, 9, 24, 24, 23, 23, 23, 134, 134, 134, 134, 134, 135, 135, 135, 135, 135, 135, 135, 135, 135, 93, 93, 93, 93, 94, 94, 94, 94, 10, 11, 73, 72, 72, 59, 61, 61, 61, 62, 62, 62, 65, 65, 132, 132, 132, 60, 60, 60, 60, 60, 60, 130, 130, 130, 119, 12, 12, 12, 12, 12, 12, 118, 137, 113, 138, 139, 111, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 140, 140, 141, 141, 112, 112, 142, 142, 56, 56, 57, 57, 69, 69, 18, 18, 18, 18, 18, 19, 19, 68, 68, 67, 67, 58, 21, 21, 22, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 116, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 4, 4, 35, 35, 16, 16, 75, 75, 75, 75, 75, 75, 75, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 76, 74, 74, 74, 74, 74, 74, 144, 144, 81, 81, 81, 145, 145, 150, 150, 150, 150, 150, 150, 150, 150, 146, 82, 82, 82, 147, 147, 151, 151, 151, 151, 151, 151, 151, 152, 38, 38, 34, 34, 153, 114, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 83, 83, 83, 83, 83, 83, 83, 83, 83, 83, 83, 83, 83, 83, 83, 83, 3, 3, 3, 13, 13, 13, 13, 13, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 154, 115, 115, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 158, 159, 156, 161, 161, 160, 160, 160, 163, 162, 162, 162, 162, 166, 166, 166, 169, 164, 167, 168, 165, 165, 165, 117, 170, 170, 172, 172, 172, 171, 171, 173, 173, 14, 14, 174, 174, 174, 174, 174, 174, 174, 174, 174, 174, 174, 174, 174, 174, 174, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 175, 31, 31, 32, 32, 39, 39, 39, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 42, 42, 42, 43, 43, 43, 47, 47, 46, 46, 45, 45, 44, 44, 48, 48, 49, 49, 49, 50, 50, 50, 50, 51, 51, 149, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 6, 6, 6, 6, 6, 53, 53, 54, 54, 55, 55, 25, 25, 26, 26, 27, 27, 27, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 5, 5, 71, 71, 71, 71, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 20, 20, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 30, 30, 29, 29, 29, 29, 29, 131, 131, 131, 131, 131, 131, 64, 64, 64, 63, 63, 87, 87, 84, 84, 85, 17, 17, 37, 37, 37, 37, 37, 37, 37, 37, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 176, 176, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 121, 121, 88, 88, 89, 89, 177, 122, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 123, 123, 178, 178, 178, 66, 66, 179, 179, 179, 179, 179, 179, 180, 182, 181, 124, 124, 125, 125, 183, 183, 183, 183, 126, 148, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 127, 127, 184, 184, 184, 184, 184, 184, 184, 128, 128, 92, 92, 92, 129, 129, 185, 185, 185, 185 }; YYSTATIC YYCONST yyr_t YYFARDATA YYR2[]={ 0, 0, 2, 4, 4, 3, 1, 1, 1, 1, 1, 1, 4, 4, 4, 4, 1, 1, 1, 2, 2, 3, 2, 2, 1, 1, 1, 4, 1, 0, 2, 1, 3, 2, 4, 6, 1, 1, 1, 1, 3, 1, 1, 1, 1, 4, 4, 4, 4, 4, 4, 4, 2, 3, 2, 2, 2, 1, 1, 2, 1, 2, 4, 6, 3, 5, 7, 9, 3, 4, 7, 1, 1, 1, 2, 0, 2, 2, 0, 6, 2, 1, 1, 1, 1, 1, 1, 1, 1, 3, 2, 3, 1, 2, 3, 7, 0, 2, 2, 2, 2, 2, 3, 3, 2, 1, 4, 3, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 2, 2, 2, 5, 0, 2, 0, 2, 0, 2, 3, 1, 0, 1, 1, 3, 0, 3, 1, 1, 1, 1, 1, 0, 2, 4, 3, 0, 2, 3, 0, 1, 5, 3, 4, 4, 4, 1, 1, 1, 1, 1, 2, 2, 4, 13, 22, 1, 1, 5, 3, 7, 5, 4, 7, 0, 2, 2, 2, 2, 2, 2, 2, 5, 2, 2, 2, 2, 2, 2, 5, 0, 2, 0, 2, 0, 3, 9, 9, 7, 7, 1, 1, 1, 2, 2, 1, 4, 0, 1, 1, 2, 2, 2, 2, 1, 4, 2, 5, 3, 2, 2, 1, 4, 3, 0, 2, 2, 0, 2, 2, 2, 2, 2, 1, 1, 1, 1, 9, 0, 2, 2, 0, 2, 2, 2, 2, 1, 1, 1, 1, 1, 0, 4, 1, 3, 1, 13, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 8, 6, 5, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 4, 4, 4, 4, 5, 1, 1, 1, 0, 4, 4, 4, 4, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 1, 0, 2, 2, 1, 2, 4, 5, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 4, 6, 4, 4, 11, 1, 5, 3, 7, 5, 5, 3, 1, 2, 2, 1, 2, 4, 4, 1, 2, 2, 2, 2, 2, 2, 2, 1, 2, 1, 1, 1, 4, 4, 2, 4, 2, 0, 1, 1, 3, 1, 3, 1, 0, 3, 5, 4, 3, 5, 5, 5, 5, 5, 5, 2, 2, 2, 2, 2, 2, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 0, 1, 1, 2, 1, 1, 1, 1, 4, 4, 5, 4, 4, 4, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 0, 2, 2, 0, 2, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 2, 0, 2, 3, 2, 0, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 2, 2, 2, 2, 2, 2, 3, 2, 2, 2, 5, 3, 2, 2, 2, 2, 2, 5, 4, 6, 2, 4, 0, 3, 3, 1, 1, 0, 3, 0, 1, 1, 3, 0, 1, 1, 3, 1, 3, 4, 4, 4, 4, 5, 1, 1, 1, 1, 1, 1, 1, 3, 1, 3, 4, 1, 0, 10, 6, 5, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 1, 1, 2, 3, 4, 6, 5, 1, 1, 1, 1, 1, 1, 1, 2, 2, 1, 2, 2, 4, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 1, 0, 5, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 1, 1, 1, 3, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 3, 2, 3, 4, 2, 2, 2, 5, 5, 7, 4, 3, 2, 3, 2, 1, 1, 2, 3, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 3, 0, 1, 1, 3, 2, 6, 7, 3, 3, 3, 6, 0, 1, 3, 5, 6, 4, 4, 1, 3, 3, 1, 1, 1, 1, 4, 1, 6, 6, 6, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 2, 5, 4, 7, 6, 7, 6, 9, 8, 3, 8, 4, 0, 2, 0, 1, 3, 3, 0, 2, 2, 2, 3, 2, 2, 2, 2, 2, 0, 2, 3, 1, 1, 1, 1, 3, 8, 2, 3, 1, 1, 3, 3, 3, 4, 6, 0, 2, 3, 1, 3, 1, 4, 3, 0, 2, 2, 2, 3, 3, 3, 3, 3, 3, 0, 2, 2, 3, 3, 4, 2, 1, 1, 3, 5, 0, 2, 2, 0, 2, 4, 3, 1, 1 }; YYSTATIC YYCONST short YYFARDATA YYCHK[]={ -1000,-109,-110,-111,-113,-114,-116,-117,-118,-119, -120,-121,-122,-124,-126,-128,-130,-131,-132, 525, 526, 460, 528, 529,-133,-134,-135, 532, 533,-139, 409,-152, 411,-170,-137, 455,-176, 463, 408, 470, 471, 430, -87, 431, -93, -94, 273, 449, 530, 534, 535, 536, 537, 538, 539, 540, 59,-138, 410, 412, 454, 447, 448, 450, -10, -11, 123, 123,-115, 123, 123, 123, 123, -9, 264, -9, 527, -88, -24, 265, 264, -24, 123,-140, 314, -1, -2, 261, 260, 263, -78, -16, 91,-171, 123,-174, 278, 38,-175, 286, 287, 284, 283, 282, 281, 288, -31, -32, 267, 91, -9, -90, 469, 469, -92, -1, 469, -86, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 445, 446, -31, -86, 263, -28, -70, -74, -93, -94, 306, 297, 322, 323,-149, 33, 307, 276, 324, -52, 275, 91, -5, -76, 268, 413, 414, 415, 358, 357, 278, 298, 277, 281, 282, 283, 284, 286, 287, 279, 290, 291, 292, 293, 271, -1, 296, -1, -1, -1, -1, 262, -77,-172, 318, 379, 61, -73, 40, -75, -7, -76, 269, 272, 325, 340, -8, 295, 300, 302, 308, -31, -31,-112,-109, 125,-155, 416,-156, 418,-154, 420, 421,-117,-157, -2,-131,-120,-133, -132,-135, 472, 458, 508,-158, 507,-160, 419, -95, -96, -97, -98, -99,-108,-100,-101,-102,-103,-104, -105,-106,-107,-159,-163, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 123, 417, -123,-125,-127,-129, -9, -1, 461,-136, -70, -76, -141, 315, -71, -70, 91, -28,-149, 46, -7, 328, 329, 330, 331, 332, 326, 346, 353, 337, 365, 366, 367, 368, 369, 370, 371, 351, 378, 294, 372, -79, -9,-173,-174, 42, 40, -31, 40, -14, 91, 40, -14, 40, -14, 40, -14, 40, -14, 40, -14, 40, 41, 267, -9, 263, 58, 44, 262, -1, 354, 355, 356, 473, 379, 475, 476, 477, 478, -90, -91, -1, 329, 330, -1, -71, 41, -36, 61, 288, 262, 44, 390, 91, 38, 42, 359, 360, 361, 60, 390, 390, 390, 390, -70, 306, -70, -75, -7, 33, -9, -1, 280, 279, 289, -28, -1, -76, 42, 471, 47, -28, 270, 272, 281, 282, 283, 284, 40, -36, -1, 329, 330, 322, 345, 334, 335, 337, 338, 339, 340, 341, 342, 343, 344, 362, 355, 336, 352, 326, 371, 294, -2, 40, 61, -72, -71, -74, -28, -7, -7, 40, 301, 303, 304, 305, 41, 41, 125,-143,-114,-111, -144,-146,-116,-117,-131,-120,-132, 452, 453,-148, 508,-133,-135, 507, 321, 422, 427, 472, 408, 125, -9, -9, 40, 451, 58, 91, -9, -71, 357, 364, 541, 91,-161,-162,-164,-166,-167,-168, 311,-169, 309, 313, 312, -9, -2, -9, -24, 40, -23, -24, 266, 286, 287, -31, -9, -2, -75, -28, -76, 270, 272, -71, -36, 341,-175, -7, -72, 40,-115,-158, -2, -9, 125,-178, 462,-131,-179,-180, 467, 468, -181,-132,-135, 464, 125,-183,-177,-179,-182, 338, 462, 465, 125,-184, 460, 408, 463, 296,-132,-135, 125,-185, 460, 463,-132,-135, -89, 420, 125,-136, -142, -71, -1, 471, -7, -1, -13, 40, 40, -28, 328, 329, 330, 331, 377, 371, 326, 479, 365, 366, 367, 368, 375, 376, 294, 93, 125, 44, 40, -2, 41, -23, -9, -23, -24, -9, -9, -9, 93, -9, -9, 474, -1, -1, 330, 329, 327, 336, 390, 40, 61, 43, 123, 40, 40, 263, -1, 93, -30, -29, 275, -9, 40, 40, -54, -55, -28, -1, -1, -1, -1, -70, -28, -9, -1, 280, 93, 93, 93, -1, -1, -71, -1, 91, -9, -69, 60, 329, 330, 331, 365, 366, 367, 40, 61, -36, 123, 40, 41, -71, -3, 373, 374, -1, -9,-115, 123, 123, 123, -9, -9, 123, -71, 357, 364, 541, 364, -81, -82, -91, -25, -26, -27, 275, -13, 40, -9, 58, 274, -7, 91, -1, 91, -1, -9,-161,-165,-158, 310,-165, -165,-165, -71,-158, -2, -9, 40, 40, 41, -71, -1, 40, -31, -28, -6, -2, -9, 125, 316, 316, 466, -31, -66, -9, 42, -36, 61, -31, 61, -31, -31, 61, 61, -1, 469, -9, 469, 40, -1, 469, -177, 44, 93, -1, -28, -28, 91, -9, -36, -83, -1, 40, 40,-173, -36, 41, 41, 93, 41, 41, 41, 41, 41, -12, 263, 44, 58, 390, 329, 330, 331, 365, 366, 367, -1, -84, -85, -36, 123, 262, -64, -63, -71, 306, 44, 93, 44, 275, -71, -71, 62, 44, 42, -5, -5, -5, 93, 274, 41, -68, -19, -18, 43, 45, 306, 323, 373, -9, -59, -61, -73, 274, -53, -22, 60, 41, 125,-112,-145,-147, -127, 274, -7, 91, -1, 91, -1, -71, -71, -1, 371, 326, -7, 371, 326, -1, 41, 44, -28, -25, 93, -9, -3, -1, -28, -9, -9, 44, 93, -2, -9, -9, -24, 274, -36, 41, 40, 41, 44, 44, -2, -9, -9, 41, 58, 40, 41, 40, 41, 41, 40, 40, -5, -1, -9, 317, -1, -31, -71, 93, -38, 479, 504, 505, 506, -9, 41, 390, -83, 41, 387, 341, 342, 343, 388, 389, 301, 303, 304, 305, 391, 394, 294, -4, 317, -34, -33,-153, 480, 482, 483, 484, 485, 276, 277, 281, 282, 283, 284, 286, 287, 257, 279, 290, 291, 292, 293, 486, 487, 488, 490, 491, 492, 493, 494, 495, 496, 334, 497, 280, 289, 336, 498, 341, 489, 357, 390, 502, 271, 123, -9, 41, -14, -14, -14, -14, -14, -14, 317, 283, 284, 456, 457, 459, -9, -9, -1, 41, 44, 61, -59, 125, 44, 61, 263, 263, -29, -9, 41, 41, -28, 40, -5, -1, 62, -58, -1, 40, -19, 41, 125, -62, -40,-135, -41, 298, 364, 297, 286, 287, 284, 283, 282, 281, 293, 292, 291, 290, 279, 278, 277,-175, 61, -3, 40, 40, 91, -54, 125, 125, -150, 423, 424, 425, 426,-120,-132,-133,-135, 125, -151, 428, 429, 426,-132,-120,-133,-135, 125, -3, -28, -9, -9, 44, -93, 450, -1, -28, -27, -38, 41, 390, -71, 93, 93, -71, -35, 61, 316, 316, 41, 41, -1, 41, -25, -6, -6, -66, 41, -9, 41, -3, 40, 93, 93, 93, 93, -36, 41, 58, 58, 40, -35, -2, 41, 42, 91, -32, 40, 481, 501, 277, 281, 282, 283, 284, 280, -20, 40, -20, -20, -15, 510, 483, 484, 276, 277, 281, 282, 283, 284, 286, 287, 279, 290, 291, 292, 293, 42, 486, 487, 488, 490, 491, 494, 495, 497, 280, 289, 257, 511, 512, 513, 514, 515, 516, 517, 518, 519, 520, 521, 522, 523, 496, 488, 500, 41, -2, 263, 263, 44, -84, -37, -17, -9, 283, -36, -70, 319, 320, 125, -64, 123, 61, -25, -1, -67, 44, -56, -57, -71, -65,-135, 358, 363, 40, 91, 40, 91, 40, 91, 40, 91, 40, 91, 40, 91, 40, 91, 40, 91, 40, 91, 40, 91, 40, 91, 40, 91, 40, 91, 284, 283, 282, 281, 40, 91, 40, 91, -31, -36, 123, 40, -53, -22, -25, -25, -9, 62, -75, -75, -75, -75, -75, -75, -75, 509, -71, 93, 93, -71, -1, -2, -2, 274, 44, -39, -41, -36, 299, 286, 287, 284, 283, 282, 281, 279, 293, 292, 291, 290, 278, 277, -2, -9, 41, 58, -89, -69, -34, -83, 392, 393, 392, 393, -9, 93, -9, 43, 125, -36, 91, 91, 503, 44, 91, 524, 38, 281, 282, 283, 284, 280, -9, 40, 40, -62, 123, 41, -67, -68, 41, 44, -60, -52, 364, 297, 345, 299, 263, -9, 306, -70, 299, -9, -40, -9, -23, -9, -9, -23, -24, -9, -24, -9, -9, -9, -9, -9, -9, -9, -24, -9, -9, -9, -9, -9, -9, -9, 40, 91, 40, 91, 40, 91, 40, 91, -9, -9, -17, -9, 41, -59, 40, 40, 41, 41, 93, -7, 274, 44, 40, -3, -71, 284, 283, 282, 281, -66, 40, 41, 41, 41, 93, 43, -9, 44, -9, -9, 61, -36, 93, 263, -9, 281, 282, 283, -9, 125, -62, -71, -1, 91, 306, -70, 41, 41, 93, 263, 41, 41, 93, 41, 93, 41, 41, 93, 41, 41, 93, 41, 93, 41, 93, 41, 93, 41, 93, 41, 93, 41, 93, 41, 93, 41, 93, -24, -9, -9, -9, -9, -9, -9, -9, 41, 93, 41, 93, 125, -25, -25, 62, -28, -3, -71, -25, -21, -22, 60, 58, -25, -9, 93, -36, 93, 93, -9, 41, 58, 58, 58, 41, 125, 61, 93, 263, 40, 41, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 41, 93, 41, 93, 41, 93, 41, 93, 40, 40, 41, 41, -71, -21, 41, 40, -66, 41, 93, 44, 41, -33, 41, -9, -9, -9, -40, -49, -50, -51, -42, -43, -47, -46, -45, -44, -47, -46, -45, -44, 40, 40, 40, 40, -45, -48, 274, 40, -35, -25, -80, -36, 41, 41, 41, 41, 299, 263, 41, 299, 306, -70, 41, -40, 41, -23, -9, 41, -23, -24, 41, -24, 41, -9, 41, -9, 41, -9, 41, 41, 41, 41, -47, -46, -45, -44, 41, 41, -17, -3, -25, 41, 123, 324, 379, 380, 381, 308, 382, 383, 384, 385, 333, 347, 348, 349, 350, 294, 44, 263, 41, 41, 41, 41, 40, 41, 40, -36, -25, 509, -9, 41, 41, 357, 41, -7, -28, -71, 274, -3, -21, 40, -25, 41 }; YYSTATIC YYCONST short YYFARDATA YYDEF[]={ 1, -2, 2, 0, 0, 333, 6, 7, 8, 9, 10, 11, 0, 0, 0, 0, 16, 17, 18, 0, 0, 772, 0, 0, 24, 25, 26, 0, 28, 135, 0, 269, 206, 0, 431, 0, 0, 778, 105, 835, 92, 0, 431, 0, 83, 84, 85, 0, 0, 0, 0, 0, 0, 57, 58, 0, 60, 108, 262, 387, 0, 757, 758, 219, 431, 431, 139, 1, 0, 788, 806, 824, 838, 19, 41, 20, 0, 0, 22, 42, 43, 23, 29, 137, 0, 104, 38, 39, 36, 37, 219, 186, 0, 384, 0, 391, 0, 0, 431, 394, 394, 394, 394, 394, 394, 0, 0, 432, 433, 0, 760, 0, 778, 814, 0, 93, 0, 0, 742, 743, 744, 745, 746, 747, 748, 749, 750, 751, 752, 753, 754, 755, 756, 0, 0, 33, 0, 0, 0, 0, 0, 0, 668, 0, 0, 219, 0, 684, 685, 0, 689, 0, 0, 549, 233, 551, 552, 553, 554, 0, 489, 691, 692, 693, 694, 695, 696, 697, 698, 699, 0, 704, 705, 706, 707, 708, 555, 0, 52, 54, 55, 56, 59, 0, 386, 388, 389, 0, 61, 0, 71, 0, 212, 213, 214, 219, 219, 217, 0, 220, 221, 226, 0, 0, 0, 0, 5, 334, 0, 336, 0, 0, 340, 341, 342, 343, 0, 345, 346, 347, 348, 349, 0, 0, 0, 355, 0, 0, 332, 504, 0, 0, 0, 0, 431, 0, 219, 0, 0, 0, 219, 0, 0, 333, 0, 490, 491, 492, 493, 494, 495, 496, 497, 498, 499, 500, 501, 502, 362, 369, 0, 0, 0, 0, 21, 774, 773, 0, 29, 550, 107, 0, 136, 557, 0, 560, 219, 0, 311, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 0, 0, 0, 0, 0, 393, 0, 0, 0, 0, 405, 0, 0, 406, 0, 407, 0, 408, 0, 409, 0, 410, 430, 102, 434, 0, 759, 0, 0, 769, 777, 779, 780, 781, 0, 783, 784, 785, 786, 787, 0, 0, 833, 836, 837, 94, 718, 719, 720, 0, 0, 31, 0, 0, 711, 673, 674, 675, 0, 0, 534, 0, 0, 0, 0, 667, 0, 670, 228, 0, 0, 681, 683, 686, 0, 688, 690, 0, 0, 0, 0, 0, 0, 231, 232, 700, 701, 702, 703, 0, 53, 147, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 0, 131, 132, 133, 0, 0, 103, 0, 0, 72, 73, 0, 215, 216, 0, 222, 223, 224, 225, 64, 68, 3, 140, 333, 0, 0, 0, 168, 169, 170, 171, 172, 0, 0, 0, 0, 178, 179, 0, 0, 236, 250, 814, 105, 4, 335, 337, -2, 0, 344, 0, 0, 0, 219, 0, 0, 0, 363, 365, 0, 0, 0, 0, 0, 0, 379, 380, 377, 505, 506, 507, 508, 503, 509, 510, 44, 0, 0, 0, 512, 513, 514, 0, 517, 518, 519, 520, 521, 0, 431, 0, 525, 527, 0, 366, 0, 0, 12, 789, 0, 791, 792, 431, 0, 0, 431, 799, 800, 0, 13, 807, 431, 809, 431, 811, 0, 0, 14, 825, 0, 0, 0, 0, 831, 832, 15, 839, 0, 0, 842, 843, 771, 775, 27, 30, 138, 142, 0, 0, 0, 40, 0, 0, 292, 0, 187, 188, 189, 190, 191, 192, 193, 0, 195, 196, 197, 198, 199, 200, 0, 207, 390, 0, 0, 0, 398, 0, 0, 0, 0, 0, 0, 0, 96, 762, 0, 782, 804, 812, 815, 816, 817, 0, 0, 0, 0, 0, 722, 727, 728, 34, 47, 671, 0, 709, 712, 713, 0, 0, 0, 535, 536, 48, 49, 50, 51, 669, 0, 680, 682, 687, 0, 0, 0, 0, 556, 0, -2, 711, 0, 106, 154, 125, 126, 127, 128, 129, 130, 0, 385, 62, 75, 69, 219, 0, 532, 308, 309, -2, 0, 0, 139, 239, 253, 173, 174, 824, 0, 219, 0, 0, 0, 0, 219, 0, 0, 539, 540, 542, 0, -2, 0, 0, 0, 0, 0, 357, 0, 0, 0, 364, 370, 381, 0, 371, 372, 373, 378, 374, 375, 376, 0, 0, 511, 0, -2, 0, 0, 0, 0, 530, 531, 361, 0, 0, 0, 0, 0, 793, 794, 797, 0, 0, 0, 0, 0, 0, 0, 826, 0, 830, 0, 0, 0, 0, 431, 0, 558, 0, 0, 263, 0, 0, 292, 0, 202, 561, 0, 392, 0, 397, 394, 395, 394, 394, 394, 394, 394, 0, 761, 0, 0, 0, 818, 819, 820, 821, 822, 823, 834, 0, 729, 0, 75, 32, 0, 723, 0, 0, 0, 672, 711, 715, 0, 0, 679, 0, 674, 545, 546, 547, 0, 0, 227, 0, 0, 154, 149, 150, 151, 152, 153, 0, 0, 78, 65, 0, 0, 0, 534, 218, 164, 0, 0, 0, 0, 0, 0, 0, 181, 0, 0, 0, 0, -2, 237, 238, 0, 251, 252, 813, 338, 311, 263, 0, 350, 352, 353, 310, 0, 0, 0, 0, 204, 0, 0, 0, 0, 0, 0, 523, -2, 526, 527, 527, 367, 368, 790, 795, 0, 803, 798, 801, 808, 810, 776, 802, 827, 828, 0, 0, 841, 0, 141, 559, 0, 0, 0, 0, 0, 0, 288, 0, 0, 291, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 0, 0, 0, 204, 0, 0, 265, 0, 0, 0, 566, 567, 568, 569, 570, 571, 572, 573, 574, 575, 576, 577, 0, 582, 583, 584, 585, 591, 592, 593, 594, 595, 596, 597, 616, 616, 600, 616, 618, 604, 606, 0, 608, 0, 610, 612, 0, 614, 615, 267, 0, 396, 399, 400, 401, 402, 403, 404, 0, 97, 98, 99, 100, 101, 764, 766, 805, 716, 0, 0, 0, 721, 722, 0, 37, 35, 710, 714, 676, 677, 537, -2, 548, 229, 148, 0, 158, 143, 155, 134, 63, 74, 76, 77, 438, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 431, 0, 532, -2, -2, 0, 0, 165, 166, 240, 219, 219, 219, 219, 245, 246, 247, 248, 167, 254, 219, 219, 219, 258, 259, 260, 261, 175, 0, 0, 0, 0, 0, 184, 219, 234, 0, 541, 543, 339, 0, 0, 356, 0, 359, 360, 0, 0, 0, 45, 46, 515, 522, 0, 528, 529, 0, 829, 840, 774, 147, 561, 312, 313, 314, 315, 292, 290, 0, 0, 0, 185, 203, 194, 586, 0, 0, 0, 0, 0, 611, 578, 579, 580, 581, 605, 598, 0, 599, 601, 602, 619, 620, 621, 622, 623, 624, 625, 626, 627, 628, 629, 0, 634, 635, 636, 637, 638, 642, 643, 644, 645, 646, 647, 648, 649, 650, 652, 653, 654, 655, 656, 657, 658, 659, 660, 661, 662, 663, 664, 665, 666, 607, 609, 613, 201, 95, 763, 765, 0, 730, 731, 734, 735, 0, 737, 0, 732, 733, 717, 724, 78, 0, 0, 158, 157, 154, 0, 144, 145, 0, 80, 81, 82, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 66, 75, 70, 0, 0, 0, 0, 0, 533, 241, 242, 243, 244, 255, 256, 257, 219, 0, 180, 0, 183, 0, 544, 351, 0, 0, 205, 435, 436, 437, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 382, 383, 524, 0, 770, 0, 0, 0, 303, 304, 305, 306, 0, 587, 0, 0, 266, 0, 0, 0, 0, 0, 0, 640, 641, 630, 631, 632, 633, 651, 768, 0, 0, 0, 78, 678, 156, 159, 160, 0, 0, 86, 87, 88, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 429, 0, -2, -2, 210, 211, 0, 0, 0, 0, -2, 161, 358, 0, 0, 0, 0, 0, -2, 264, 289, 307, 588, 0, 0, 0, 0, 0, 0, 603, 639, 767, 0, 0, 0, 0, 0, 725, 0, 146, 0, 0, 0, 90, 439, 440, 0, 0, 442, 443, 0, 444, 0, 411, 413, 0, 412, 414, 0, 415, 0, 416, 0, 417, 0, 418, 0, 423, 0, 424, 0, 425, 0, 426, 0, 0, 0, 0, 0, 0, 0, 0, 0, 427, 0, 428, 0, 67, 0, 0, 163, 0, 161, 182, 0, 0, 162, 0, 0, 0, 0, 590, 0, 564, 561, 0, 736, 0, 0, 0, 741, 726, 0, 91, 89, 480, 441, 483, 487, 464, 467, 470, 472, 474, 476, 470, 472, 474, 476, 419, 0, 420, 0, 421, 0, 422, 0, 474, 478, 208, 209, 0, 0, 204, -2, 796, 316, 589, 0, 563, 565, 617, 0, 0, 0, 79, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 470, 472, 474, 476, 0, 0, 0, -2, 249, 0, 0, 0, 738, 739, 740, 461, 481, 482, 462, 484, 0, 486, 463, 488, 445, 465, 466, 446, 468, 469, 447, 471, 448, 473, 449, 475, 450, 477, 451, 452, 453, 454, 0, 0, 0, 0, 459, 460, 479, 0, 0, 354, 268, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 0, 0, 485, 455, 456, 457, 458, -2, 0, 0, 0, 0, 0, 0, 562, 176, 219, 331, 0, 0, 0, 0, 161, 0, -2, 0, 177 }; #ifdef YYRECOVER YYSTATIC YYCONST short yyrecover[] = { -1000 }; #endif /* SCCSWHAT( "@(#)yypars.c 3.1 88/11/16 22:00:49 " ) */ #line 3 "F:\\NetFXDev1\\src\\tools\\devdiv\\amd64\\yypars.c" #if ! defined(YYAPI_PACKAGE) /* ** YYAPI_TOKENNAME : name used for return value of yylex ** YYAPI_TOKENTYPE : type of the token ** YYAPI_TOKENEME(t) : the value of the token that the parser should see ** YYAPI_TOKENNONE : the representation when there is no token ** YYAPI_VALUENAME : the name of the value of the token ** YYAPI_VALUETYPE : the type of the value of the token (if null, then the value is derivable from the token itself) ** YYAPI_VALUEOF(v) : how to get the value of the token. */ #define YYAPI_TOKENNAME yychar #define YYAPI_TOKENTYPE int #define YYAPI_TOKENEME(t) (t) #define YYAPI_TOKENNONE -1 #define YYAPI_TOKENSTR(t) (sprintf_s(yytokbuf, ARRAY_SIZE(yytokbuf), "%d", t), yytokbuf) #define YYAPI_VALUENAME yylval #define YYAPI_VALUETYPE YYSTYPE #define YYAPI_VALUEOF(v) (v) #endif #if ! defined(YYAPI_CALLAFTERYYLEX) #define YYAPI_CALLAFTERYYLEX #endif # define YYFLAG -1000 # define YYERROR goto yyerrlab # define YYACCEPT return(0) # define YYABORT return(1) #ifdef YYDEBUG /* RRR - 10/9/85 */ char yytokbuf[20]; # ifndef YYDBFLG # define YYDBFLG (yydebug) # endif # define yyprintf(a, b, c, d) if (YYDBFLG) YYPRINT(a, b, c, d) #else # define yyprintf(a, b, c, d) #endif #ifndef YYPRINT #define YYPRINT printf #endif /* parser for yacc output */ #ifdef YYDUMP int yydump = 1; /* 1 for dumping */ void yydumpinfo(void); #endif #ifdef YYDEBUG YYSTATIC int yydebug = 0; /* 1 for debugging */ #endif YYSTATIC YYSTYPE yyv[YYMAXDEPTH]; /* where the values are stored */ YYSTATIC short yys[YYMAXDEPTH]; /* the parse stack */ #if ! defined(YYRECURSIVE) YYSTATIC YYAPI_TOKENTYPE YYAPI_TOKENNAME = YYAPI_TOKENNONE; #if defined(YYAPI_VALUETYPE) // YYSTATIC YYAPI_VALUETYPE YYAPI_VALUENAME; FIX #endif YYSTATIC int yynerrs = 0; /* number of errors */ YYSTATIC short yyerrflag = 0; /* error recovery flag */ #endif #ifdef YYRECOVER /* ** yyscpy : copy f onto t and return a ptr to the null terminator at the ** end of t. */ YYSTATIC char *yyscpy(register char*t, register char*f) { while(*t = *f++) t++; return(t); /* ptr to the null char */ } #endif #ifndef YYNEAR #define YYNEAR #endif #ifndef YYPASCAL #define YYPASCAL #endif #ifndef YYLOCAL #define YYLOCAL #endif #if ! defined YYPARSER #define YYPARSER yyparse #endif #if ! defined YYLEX #define YYLEX yylex #endif #if defined(YYRECURSIVE) YYSTATIC YYAPI_TOKENTYPE YYAPI_TOKENNAME = YYAPI_TOKENNONE; #if defined(YYAPI_VALUETYPE) YYSTATIC YYAPI_VALUETYPE YYAPI_VALUENAME; #endif YYSTATIC int yynerrs = 0; /* number of errors */ YYSTATIC short yyerrflag = 0; /* error recovery flag */ YYSTATIC short yyn; YYSTATIC short yystate = 0; YYSTATIC short *yyps= &yys[-1]; YYSTATIC YYSTYPE *yypv= &yyv[-1]; YYSTATIC short yyj; YYSTATIC short yym; #endif #pragma warning(disable:102) YYLOCAL YYNEAR YYPASCAL YYPARSER() { #if ! defined(YYRECURSIVE) register short yyn; short yystate, *yyps; YYSTYPE *yypv; short yyj, yym; YYAPI_TOKENNAME = YYAPI_TOKENNONE; yystate = 0; #ifdef _PREFAST_ #pragma warning(push) #pragma warning(disable:6200) // Index '-1' is out of valid index range...for non-stack buffer... #endif yyps= &yys[-1]; yypv= &yyv[-1]; #ifdef _PREFAST_ #pragma warning(pop) #endif #endif #ifdef YYDUMP yydumpinfo(); #endif yystack: /* put a state and value onto the stack */ #ifdef YYDEBUG if(YYAPI_TOKENNAME == YYAPI_TOKENNONE) { yyprintf( "state %d, token # '%d'\n", yystate, -1, 0 ); } else { yyprintf( "state %d, token # '%s'\n", yystate, YYAPI_TOKENSTR(YYAPI_TOKENNAME), 0 ); } #endif if( ++yyps > &yys[YYMAXDEPTH] ) { yyerror( "yacc stack overflow" ); return(1); } *yyps = yystate; ++yypv; *yypv = yyval; yynewstate: yyn = YYPACT[yystate]; if( yyn <= YYFLAG ) { /* simple state, no lookahead */ goto yydefault; } if( YYAPI_TOKENNAME == YYAPI_TOKENNONE ) { /* need a lookahead */ YYAPI_TOKENNAME = YYLEX(); YYAPI_CALLAFTERYYLEX(YYAPI_TOKENNAME); } if( ((yyn += YYAPI_TOKENEME(YYAPI_TOKENNAME)) < 0) || (yyn >= YYLAST) ) { goto yydefault; } if( YYCHK[ yyn = YYACT[ yyn ] ] == YYAPI_TOKENEME(YYAPI_TOKENNAME) ) { /* valid shift */ yyval = YYAPI_VALUEOF(YYAPI_VALUENAME); yystate = yyn; yyprintf( "SHIFT: saw token '%s', now in state %4d\n", YYAPI_TOKENSTR(YYAPI_TOKENNAME), yystate, 0 ); YYAPI_TOKENNAME = YYAPI_TOKENNONE; if( yyerrflag > 0 ) { --yyerrflag; } goto yystack; } yydefault: /* default state action */ if( (yyn = YYDEF[yystate]) == -2 ) { register YYCONST short *yyxi; if( YYAPI_TOKENNAME == YYAPI_TOKENNONE ) { YYAPI_TOKENNAME = YYLEX(); YYAPI_CALLAFTERYYLEX(YYAPI_TOKENNAME); yyprintf("LOOKAHEAD: token '%s'\n", YYAPI_TOKENSTR(YYAPI_TOKENNAME), 0, 0); } /* ** search exception table, we find a -1 followed by the current state. ** if we find one, we'll look through terminal,state pairs. if we find ** a terminal which matches the current one, we have a match. ** the exception table is when we have a reduce on a terminal. */ #if YYOPTTIME yyxi = yyexca + yyexcaind[yystate]; while(( *yyxi != YYAPI_TOKENEME(YYAPI_TOKENNAME) ) && ( *yyxi >= 0 )){ yyxi += 2; } #else for(yyxi = yyexca; (*yyxi != (-1)) || (yyxi[1] != yystate); yyxi += 2 ) { ; /* VOID */ } while( *(yyxi += 2) >= 0 ){ if( *yyxi == YYAPI_TOKENEME(YYAPI_TOKENNAME) ) { break; } } #endif if( (yyn = yyxi[1]) < 0 ) { return(0); /* accept */ } } if( yyn == 0 ){ /* error */ /* error ... attempt to resume parsing */ switch( yyerrflag ){ case 0: /* brand new error */ #ifdef YYRECOVER { register int i,j; for(i = 0; (yyrecover[i] != -1000) && (yystate > yyrecover[i]); i += 3 ) { ; } if(yystate == yyrecover[i]) { yyprintf("recovered, from state %d to state %d on token # %d\n", yystate,yyrecover[i+2],yyrecover[i+1] ); j = yyrecover[i + 1]; if(j < 0) { /* ** here we have one of the injection set, so we're not quite ** sure that the next valid thing will be a shift. so we'll ** count it as an error and continue. ** actually we're not absolutely sure that the next token ** we were supposed to get is the one when j > 0. for example, ** for(+) {;} error recovery with yyerrflag always set, stops ** after inserting one ; before the +. at the point of the +, ** we're pretty sure the caller wants a 'for' loop. without ** setting the flag, when we're almost absolutely sure, we'll ** give them one, since the only thing we can shift on this ** error is after finding an expression followed by a + */ yyerrflag++; j = -j; } if(yyerrflag <= 1) { /* only on first insertion */ yyrecerr(YYAPI_TOKENNAME, j); /* what was, what should be first */ } yyval = yyeval(j); yystate = yyrecover[i + 2]; goto yystack; } } #endif yyerror("syntax error"); yyerrlab: ++yynerrs; FALLTHROUGH; case 1: case 2: /* incompletely recovered error ... try again */ yyerrflag = 3; /* find a state where "error" is a legal shift action */ while ( yyps >= yys ) { yyn = YYPACT[*yyps] + YYERRCODE; if( yyn>= 0 && yyn < YYLAST && YYCHK[YYACT[yyn]] == YYERRCODE ){ yystate = YYACT[yyn]; /* simulate a shift of "error" */ yyprintf( "SHIFT 'error': now in state %4d\n", yystate, 0, 0 ); goto yystack; } yyn = YYPACT[*yyps]; /* the current yyps has no shift onn "error", pop stack */ yyprintf( "error recovery pops state %4d, uncovers %4d\n", *yyps, yyps[-1], 0 ); --yyps; --yypv; } /* there is no state on the stack with an error shift ... abort */ yyabort: return(1); case 3: /* no shift yet; clobber input char */ yyprintf( "error recovery discards token '%s'\n", YYAPI_TOKENSTR(YYAPI_TOKENNAME), 0, 0 ); if( YYAPI_TOKENEME(YYAPI_TOKENNAME) == 0 ) goto yyabort; /* don't discard EOF, quit */ YYAPI_TOKENNAME = YYAPI_TOKENNONE; goto yynewstate; /* try again in the same state */ } } /* reduction by production yyn */ yyreduce: { register YYSTYPE *yypvt; yypvt = yypv; yyps -= YYR2[yyn]; yypv -= YYR2[yyn]; yyval = yypv[1]; yyprintf("REDUCE: rule %4d, popped %2d tokens, uncovered state %4d, ",yyn, YYR2[yyn], *yyps); yym = yyn; yyn = YYR1[yyn]; /* consult goto table to find next state */ yyj = YYPGO[yyn] + *yyps + 1; if( (yyj >= YYLAST) || (YYCHK[ yystate = YYACT[yyj] ] != -yyn) ) { yystate = YYACT[YYPGO[yyn]]; } yyprintf("goto state %4d\n", yystate, 0, 0); #ifdef YYDUMP yydumpinfo(); #endif switch(yym){ case 3: #line 194 "asmparse.y" { PASM->EndClass(); } break; case 4: #line 195 "asmparse.y" { PASM->EndNameSpace(); } break; case 5: #line 196 "asmparse.y" { if(PASM->m_pCurMethod->m_ulLines[1] ==0) { PASM->m_pCurMethod->m_ulLines[1] = PASM->m_ulCurLine; PASM->m_pCurMethod->m_ulColumns[1]=PASM->m_ulCurColumn;} PASM->EndMethod(); } break; case 12: #line 206 "asmparse.y" { PASMM->EndAssembly(); } break; case 13: #line 207 "asmparse.y" { PASMM->EndAssembly(); } break; case 14: #line 208 "asmparse.y" { PASMM->EndComType(); } break; case 15: #line 209 "asmparse.y" { PASMM->EndManifestRes(); } break; case 19: #line 213 "asmparse.y" { #ifdef _PREFAST_ #pragma warning(push) #pragma warning(disable:22011) // Suppress PREFast warning about integer overflow/underflow #endif PASM->m_dwSubsystem = yypvt[-0].int32; #ifdef _PREFAST_ #pragma warning(pop) #endif } break; case 20: #line 223 "asmparse.y" { PASM->m_dwComImageFlags = yypvt[-0].int32; } break; case 21: #line 224 "asmparse.y" { PASM->m_dwFileAlignment = yypvt[-0].int32; if((yypvt[-0].int32 & (yypvt[-0].int32 - 1))||(yypvt[-0].int32 < 0x200)||(yypvt[-0].int32 > 0x10000)) PASM->report->error("Invalid file alignment, must be power of 2 from 0x200 to 0x10000\n");} break; case 22: #line 227 "asmparse.y" { PASM->m_stBaseAddress = (ULONGLONG)(*(yypvt[-0].int64)); delete yypvt[-0].int64; if(PASM->m_stBaseAddress & 0xFFFF) PASM->report->error("Invalid image base, must be 0x10000-aligned\n");} break; case 23: #line 230 "asmparse.y" { PASM->m_stSizeOfStackReserve = (size_t)(*(yypvt[-0].int64)); delete yypvt[-0].int64; } break; case 28: #line 235 "asmparse.y" { PASM->m_fIsMscorlib = TRUE; } break; case 31: #line 242 "asmparse.y" { yyval.binstr = yypvt[-0].binstr; } break; case 32: #line 243 "asmparse.y" { yyval.binstr = yypvt[-2].binstr; yyval.binstr->append(yypvt[-0].binstr); delete yypvt[-0].binstr; } break; case 33: #line 246 "asmparse.y" { LPCSTRToGuid(yypvt[-0].string,&(PASM->m_guidLang)); } break; case 34: #line 247 "asmparse.y" { LPCSTRToGuid(yypvt[-2].string,&(PASM->m_guidLang)); LPCSTRToGuid(yypvt[-0].string,&(PASM->m_guidLangVendor));} break; case 35: #line 249 "asmparse.y" { LPCSTRToGuid(yypvt[-4].string,&(PASM->m_guidLang)); LPCSTRToGuid(yypvt[-2].string,&(PASM->m_guidLangVendor)); LPCSTRToGuid(yypvt[-2].string,&(PASM->m_guidDoc));} break; case 36: #line 254 "asmparse.y" { yyval.string = yypvt[-0].string; } break; case 37: #line 255 "asmparse.y" { yyval.string = yypvt[-0].string; } break; case 38: #line 258 "asmparse.y" { yyval.string = yypvt[-0].string; } break; case 39: #line 259 "asmparse.y" { yyval.string = yypvt[-0].string; } break; case 40: #line 260 "asmparse.y" { yyval.string = newStringWDel(yypvt[-2].string, '.', yypvt[-0].string); } break; case 41: #line 263 "asmparse.y" { yyval.int32 = yypvt[-0].int32; } break; case 42: #line 266 "asmparse.y" { yyval.int64 = yypvt[-0].int64; } break; case 43: #line 267 "asmparse.y" { yyval.int64 = neg ? new __int64(yypvt[-0].int32) : new __int64((unsigned)yypvt[-0].int32); } break; case 44: #line 270 "asmparse.y" { yyval.float64 = yypvt[-0].float64; } break; case 45: #line 271 "asmparse.y" { float f; *((__int32*) (&f)) = yypvt[-1].int32; yyval.float64 = new double(f); } break; case 46: #line 272 "asmparse.y" { yyval.float64 = (double*) yypvt[-1].int64; } break; case 47: #line 276 "asmparse.y" { PASM->AddTypeDef(yypvt[-2].binstr,yypvt[-0].string); } break; case 48: #line 277 "asmparse.y" { PASM->AddTypeDef(yypvt[-2].token,yypvt[-0].string); } break; case 49: #line 278 "asmparse.y" { PASM->AddTypeDef(yypvt[-2].token,yypvt[-0].string); } break; case 50: #line 279 "asmparse.y" { yypvt[-2].cad->tkOwner = 0; PASM->AddTypeDef(yypvt[-2].cad,yypvt[-0].string); } break; case 51: #line 280 "asmparse.y" { PASM->AddTypeDef(yypvt[-2].cad,yypvt[-0].string); } break; case 52: #line 285 "asmparse.y" { DefineVar(yypvt[-0].string, NULL); } break; case 53: #line 286 "asmparse.y" { DefineVar(yypvt[-1].string, yypvt[-0].binstr); } break; case 54: #line 287 "asmparse.y" { UndefVar(yypvt[-0].string); } break; case 55: #line 288 "asmparse.y" { SkipToken = !IsVarDefined(yypvt[-0].string); IfEndif++; } break; case 56: #line 291 "asmparse.y" { SkipToken = IsVarDefined(yypvt[-0].string); IfEndif++; } break; case 57: #line 294 "asmparse.y" { if(IfEndif == 1) SkipToken = !SkipToken;} break; case 58: #line 295 "asmparse.y" { if(IfEndif == 0) PASM->report->error("Unmatched #endif\n"); else IfEndif--; } break; case 59: #line 299 "asmparse.y" { _ASSERTE(!"yylex should have dealt with this"); } break; case 60: #line 300 "asmparse.y" { } break; case 61: #line 304 "asmparse.y" { yyval.cad = new CustomDescr(PASM->m_tkCurrentCVOwner, yypvt[-0].token, NULL); } break; case 62: #line 305 "asmparse.y" { yyval.cad = new CustomDescr(PASM->m_tkCurrentCVOwner, yypvt[-2].token, yypvt[-0].binstr); } break; case 63: #line 306 "asmparse.y" { yyval.cad = new CustomDescr(PASM->m_tkCurrentCVOwner, yypvt[-4].token, yypvt[-1].binstr); } break; case 64: #line 307 "asmparse.y" { yyval.cad = new CustomDescr(PASM->m_tkCurrentCVOwner, yypvt[-2].int32, yypvt[-1].binstr); } break; case 65: #line 310 "asmparse.y" { yyval.cad = new CustomDescr(yypvt[-2].token, yypvt[-0].token, NULL); } break; case 66: #line 311 "asmparse.y" { yyval.cad = new CustomDescr(yypvt[-4].token, yypvt[-2].token, yypvt[-0].binstr); } break; case 67: #line 313 "asmparse.y" { yyval.cad = new CustomDescr(yypvt[-6].token, yypvt[-4].token, yypvt[-1].binstr); } break; case 68: #line 314 "asmparse.y" { yyval.cad = new CustomDescr(PASM->m_tkCurrentCVOwner, yypvt[-2].int32, yypvt[-1].binstr); } break; case 69: #line 317 "asmparse.y" { yyval.int32 = yypvt[-2].token; bParsingByteArray = TRUE; } break; case 70: #line 321 "asmparse.y" { PASM->m_pCustomDescrList = NULL; PASM->m_tkCurrentCVOwner = yypvt[-4].token; yyval.int32 = yypvt[-2].token; bParsingByteArray = TRUE; } break; case 71: #line 326 "asmparse.y" { yyval.token = yypvt[-0].token; } break; case 72: #line 329 "asmparse.y" { yyval.token = yypvt[-0].token; } break; case 73: #line 330 "asmparse.y" { yyval.token = yypvt[-0].token; } break; case 74: #line 334 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->appendInt16(VAL16(nCustomBlobNVPairs)); yyval.binstr->append(yypvt[-0].binstr); nCustomBlobNVPairs = 0; } break; case 75: #line 340 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt16(VAL16(0x0001)); } break; case 76: #line 341 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; AppendFieldToCustomBlob(yyval.binstr,yypvt[-0].binstr); } break; case 77: #line 343 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; } break; case 78: #line 346 "asmparse.y" { yyval.binstr = new BinStr(); } break; case 79: #line 348 "asmparse.y" { yyval.binstr = yypvt[-5].binstr; yyval.binstr->appendInt8(yypvt[-4].int32); yyval.binstr->append(yypvt[-3].binstr); AppendStringWithLength(yyval.binstr,yypvt[-2].string); AppendFieldToCustomBlob(yyval.binstr,yypvt[-0].binstr); nCustomBlobNVPairs++; } break; case 80: #line 353 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; } break; case 81: #line 356 "asmparse.y" { yyval.int32 = SERIALIZATION_TYPE_FIELD; } break; case 82: #line 357 "asmparse.y" { yyval.int32 = SERIALIZATION_TYPE_PROPERTY; } break; case 83: #line 360 "asmparse.y" { if(yypvt[-0].cad->tkOwner && !yypvt[-0].cad->tkInterfacePair) PASM->DefineCV(yypvt[-0].cad); else if(PASM->m_pCustomDescrList) PASM->m_pCustomDescrList->PUSH(yypvt[-0].cad); } break; case 84: #line 364 "asmparse.y" { PASM->DefineCV(yypvt[-0].cad); } break; case 85: #line 365 "asmparse.y" { CustomDescr* pNew = new CustomDescr(yypvt[-0].tdd->m_pCA); if(pNew->tkOwner == 0) pNew->tkOwner = PASM->m_tkCurrentCVOwner; if(pNew->tkOwner) PASM->DefineCV(pNew); else if(PASM->m_pCustomDescrList) PASM->m_pCustomDescrList->PUSH(pNew); } break; case 86: #line 373 "asmparse.y" { yyval.binstr = yypvt[-0].binstr; } break; case 87: #line 374 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(SERIALIZATION_TYPE_TYPE); } break; case 88: #line 375 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(SERIALIZATION_TYPE_TAGGED_OBJECT); } break; case 89: #line 376 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(SERIALIZATION_TYPE_ENUM); AppendStringWithLength(yyval.binstr,yypvt[-0].string); } break; case 90: #line 378 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(SERIALIZATION_TYPE_ENUM); AppendStringWithLength(yyval.binstr,PASM->ReflectionNotation(yypvt[-0].token)); } break; case 91: #line 380 "asmparse.y" { yyval.binstr = yypvt[-2].binstr; yyval.binstr->insertInt8(ELEMENT_TYPE_SZARRAY); } break; case 92: #line 385 "asmparse.y" { PASMM->SetModuleName(NULL); PASM->m_tkCurrentCVOwner=1; } break; case 93: #line 386 "asmparse.y" { PASMM->SetModuleName(yypvt[-0].string); PASM->m_tkCurrentCVOwner=1; } break; case 94: #line 387 "asmparse.y" { BinStr* pbs = new BinStr(); unsigned L = (unsigned)strlen(yypvt[-0].string); memcpy((char*)(pbs->getBuff(L)),yypvt[-0].string,L); PASM->EmitImport(pbs); delete pbs;} break; case 95: #line 394 "asmparse.y" { /*PASM->SetDataSection(); PASM->EmitDataLabel($7);*/ PASM->m_VTFList.PUSH(new VTFEntry((USHORT)yypvt[-4].int32, (USHORT)yypvt[-2].int32, yypvt[-0].string)); } break; case 96: #line 398 "asmparse.y" { yyval.int32 = 0; } break; case 97: #line 399 "asmparse.y" { yyval.int32 = yypvt[-1].int32 | COR_VTABLE_32BIT; } break; case 98: #line 400 "asmparse.y" { yyval.int32 = yypvt[-1].int32 | COR_VTABLE_64BIT; } break; case 99: #line 401 "asmparse.y" { yyval.int32 = yypvt[-1].int32 | COR_VTABLE_FROM_UNMANAGED; } break; case 100: #line 402 "asmparse.y" { yyval.int32 = yypvt[-1].int32 | COR_VTABLE_CALL_MOST_DERIVED; } break; case 101: #line 403 "asmparse.y" { yyval.int32 = yypvt[-1].int32 | COR_VTABLE_FROM_UNMANAGED_RETAIN_APPDOMAIN; } break; case 102: #line 406 "asmparse.y" { PASM->m_pVTable = yypvt[-1].binstr; } break; case 103: #line 409 "asmparse.y" { bParsingByteArray = TRUE; } break; case 104: #line 413 "asmparse.y" { PASM->StartNameSpace(yypvt[-0].string); } break; case 105: #line 416 "asmparse.y" { newclass = TRUE; } break; case 106: #line 419 "asmparse.y" { if(yypvt[-0].typarlist) FixupConstraints(); PASM->StartClass(yypvt[-1].string, yypvt[-2].classAttr, yypvt[-0].typarlist); TyParFixupList.RESET(false); newclass = FALSE; } break; case 107: #line 425 "asmparse.y" { PASM->AddClass(); } break; case 108: #line 428 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) 0; } break; case 109: #line 429 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) ((yypvt[-1].classAttr & ~tdVisibilityMask) | tdPublic); } break; case 110: #line 430 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) ((yypvt[-1].classAttr & ~tdVisibilityMask) | tdNotPublic); } break; case 111: #line 431 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) (yypvt[-1].classAttr | 0x80000000 | tdSealed); } break; case 112: #line 432 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) (yypvt[-1].classAttr | 0x40000000); } break; case 113: #line 433 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) (yypvt[-1].classAttr | tdInterface | tdAbstract); } break; case 114: #line 434 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) (yypvt[-1].classAttr | tdSealed); } break; case 115: #line 435 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) (yypvt[-1].classAttr | tdAbstract); } break; case 116: #line 436 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) ((yypvt[-1].classAttr & ~tdLayoutMask) | tdAutoLayout); } break; case 117: #line 437 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) ((yypvt[-1].classAttr & ~tdLayoutMask) | tdSequentialLayout); } break; case 118: #line 438 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) ((yypvt[-1].classAttr & ~tdLayoutMask) | tdExplicitLayout); } break; case 119: #line 439 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) ((yypvt[-1].classAttr & ~tdStringFormatMask) | tdAnsiClass); } break; case 120: #line 440 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) ((yypvt[-1].classAttr & ~tdStringFormatMask) | tdUnicodeClass); } break; case 121: #line 441 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) ((yypvt[-1].classAttr & ~tdStringFormatMask) | tdAutoClass); } break; case 122: #line 442 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) (yypvt[-1].classAttr | tdImport); } break; case 123: #line 443 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) (yypvt[-1].classAttr | tdSerializable); } break; case 124: #line 444 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) (yypvt[-1].classAttr | tdWindowsRuntime); } break; case 125: #line 445 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) ((yypvt[-2].classAttr & ~tdVisibilityMask) | tdNestedPublic); } break; case 126: #line 446 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) ((yypvt[-2].classAttr & ~tdVisibilityMask) | tdNestedPrivate); } break; case 127: #line 447 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) ((yypvt[-2].classAttr & ~tdVisibilityMask) | tdNestedFamily); } break; case 128: #line 448 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) ((yypvt[-2].classAttr & ~tdVisibilityMask) | tdNestedAssembly); } break; case 129: #line 449 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) ((yypvt[-2].classAttr & ~tdVisibilityMask) | tdNestedFamANDAssem); } break; case 130: #line 450 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) ((yypvt[-2].classAttr & ~tdVisibilityMask) | tdNestedFamORAssem); } break; case 131: #line 451 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) (yypvt[-1].classAttr | tdBeforeFieldInit); } break; case 132: #line 452 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) (yypvt[-1].classAttr | tdSpecialName); } break; case 133: #line 453 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) (yypvt[-1].classAttr); } break; case 134: #line 454 "asmparse.y" { yyval.classAttr = (CorRegTypeAttr) (yypvt[-1].int32); } break; case 136: #line 458 "asmparse.y" { PASM->m_crExtends = yypvt[-0].token; } break; case 141: #line 469 "asmparse.y" { PASM->AddToImplList(yypvt[-0].token); } break; case 142: #line 470 "asmparse.y" { PASM->AddToImplList(yypvt[-0].token); } break; case 143: #line 474 "asmparse.y" { yyval.binstr = new BinStr(); } break; case 144: #line 475 "asmparse.y" { yyval.binstr = yypvt[-0].binstr; } break; case 145: #line 478 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt32(yypvt[-0].token); } break; case 146: #line 479 "asmparse.y" { yyval.binstr = yypvt[-2].binstr; yyval.binstr->appendInt32(yypvt[-0].token); } break; case 147: #line 482 "asmparse.y" { yyval.typarlist = NULL; PASM->m_TyParList = NULL;} break; case 148: #line 483 "asmparse.y" { yyval.typarlist = yypvt[-1].typarlist; PASM->m_TyParList = yypvt[-1].typarlist;} break; case 149: #line 486 "asmparse.y" { yyval.int32 = gpCovariant; } break; case 150: #line 487 "asmparse.y" { yyval.int32 = gpContravariant; } break; case 151: #line 488 "asmparse.y" { yyval.int32 = gpReferenceTypeConstraint; } break; case 152: #line 489 "asmparse.y" { yyval.int32 = gpNotNullableValueTypeConstraint; } break; case 153: #line 490 "asmparse.y" { yyval.int32 = gpDefaultConstructorConstraint; } break; case 154: #line 493 "asmparse.y" { yyval.int32 = 0; } break; case 155: #line 494 "asmparse.y" { yyval.int32 = yypvt[-1].int32 | yypvt[-0].int32; } break; case 156: #line 497 "asmparse.y" {yyval.typarlist = new TyParList(yypvt[-3].int32, yypvt[-2].binstr, yypvt[-1].string, yypvt[-0].typarlist);} break; case 157: #line 498 "asmparse.y" {yyval.typarlist = new TyParList(yypvt[-2].int32, NULL, yypvt[-1].string, yypvt[-0].typarlist);} break; case 158: #line 501 "asmparse.y" { yyval.typarlist = NULL; } break; case 159: #line 502 "asmparse.y" { yyval.typarlist = yypvt[-0].typarlist; } break; case 160: #line 505 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; } break; case 161: #line 508 "asmparse.y" { yyval.int32= 0; } break; case 162: #line 509 "asmparse.y" { yyval.int32 = yypvt[-0].int32; } break; case 163: #line 512 "asmparse.y" { yyval.int32 = yypvt[-2].int32; } break; case 164: #line 516 "asmparse.y" { if(PASM->m_pCurMethod->m_ulLines[1] ==0) { PASM->m_pCurMethod->m_ulLines[1] = PASM->m_ulCurLine; PASM->m_pCurMethod->m_ulColumns[1]=PASM->m_ulCurColumn;} PASM->EndMethod(); } break; case 165: #line 520 "asmparse.y" { PASM->EndClass(); } break; case 166: #line 521 "asmparse.y" { PASM->EndEvent(); } break; case 167: #line 522 "asmparse.y" { PASM->EndProp(); } break; case 173: #line 528 "asmparse.y" { PASM->m_pCurClass->m_ulSize = yypvt[-0].int32; } break; case 174: #line 529 "asmparse.y" { PASM->m_pCurClass->m_ulPack = yypvt[-0].int32; } break; case 175: #line 530 "asmparse.y" { PASMM->EndComType(); } break; case 176: #line 532 "asmparse.y" { BinStr *sig1 = parser->MakeSig(yypvt[-7].int32, yypvt[-6].binstr, yypvt[-1].binstr); BinStr *sig2 = new BinStr(); sig2->append(sig1); PASM->AddMethodImpl(yypvt[-11].token,yypvt[-9].string,sig1,yypvt[-5].token,yypvt[-3].string,sig2); PASM->ResetArgNameList(); } break; case 177: #line 538 "asmparse.y" { PASM->AddMethodImpl(yypvt[-17].token,yypvt[-15].string, (yypvt[-14].int32==0 ? parser->MakeSig(yypvt[-19].int32,yypvt[-18].binstr,yypvt[-12].binstr) : parser->MakeSig(yypvt[-19].int32| IMAGE_CEE_CS_CALLCONV_GENERIC,yypvt[-18].binstr,yypvt[-12].binstr,yypvt[-14].int32)), yypvt[-6].token,yypvt[-4].string, (yypvt[-3].int32==0 ? parser->MakeSig(yypvt[-8].int32,yypvt[-7].binstr,yypvt[-1].binstr) : parser->MakeSig(yypvt[-8].int32| IMAGE_CEE_CS_CALLCONV_GENERIC,yypvt[-7].binstr,yypvt[-1].binstr,yypvt[-3].int32))); PASM->ResetArgNameList(); } break; case 180: #line 548 "asmparse.y" { if((yypvt[-1].int32 > 0) && (yypvt[-1].int32 <= (int)PASM->m_pCurClass->m_NumTyPars)) PASM->m_pCustomDescrList = PASM->m_pCurClass->m_TyPars[yypvt[-1].int32-1].CAList(); else PASM->report->error("Type parameter index out of range\n"); } break; case 181: #line 553 "asmparse.y" { int n = PASM->m_pCurClass->FindTyPar(yypvt[-0].string); if(n >= 0) PASM->m_pCustomDescrList = PASM->m_pCurClass->m_TyPars[n].CAList(); else PASM->report->error("Type parameter '%s' undefined\n",yypvt[-0].string); } break; case 182: #line 559 "asmparse.y" { PASM->AddGenericParamConstraint(yypvt[-3].int32, 0, yypvt[-0].token); } break; case 183: #line 560 "asmparse.y" { PASM->AddGenericParamConstraint(0, yypvt[-2].string, yypvt[-0].token); } break; case 184: #line 561 "asmparse.y" { yypvt[-0].cad->tkInterfacePair = yypvt[-1].token; if(PASM->m_pCustomDescrList) PASM->m_pCustomDescrList->PUSH(yypvt[-0].cad); } break; case 185: #line 569 "asmparse.y" { yypvt[-3].binstr->insertInt8(IMAGE_CEE_CS_CALLCONV_FIELD); PASM->AddField(yypvt[-2].string, yypvt[-3].binstr, yypvt[-4].fieldAttr, yypvt[-1].string, yypvt[-0].binstr, yypvt[-5].int32); } break; case 186: #line 573 "asmparse.y" { yyval.fieldAttr = (CorFieldAttr) 0; } break; case 187: #line 574 "asmparse.y" { yyval.fieldAttr = (CorFieldAttr) (yypvt[-1].fieldAttr | fdStatic); } break; case 188: #line 575 "asmparse.y" { yyval.fieldAttr = (CorFieldAttr) ((yypvt[-1].fieldAttr & ~mdMemberAccessMask) | fdPublic); } break; case 189: #line 576 "asmparse.y" { yyval.fieldAttr = (CorFieldAttr) ((yypvt[-1].fieldAttr & ~mdMemberAccessMask) | fdPrivate); } break; case 190: #line 577 "asmparse.y" { yyval.fieldAttr = (CorFieldAttr) ((yypvt[-1].fieldAttr & ~mdMemberAccessMask) | fdFamily); } break; case 191: #line 578 "asmparse.y" { yyval.fieldAttr = (CorFieldAttr) (yypvt[-1].fieldAttr | fdInitOnly); } break; case 192: #line 579 "asmparse.y" { yyval.fieldAttr = yypvt[-1].fieldAttr; } break; case 193: #line 580 "asmparse.y" { yyval.fieldAttr = (CorFieldAttr) (yypvt[-1].fieldAttr | fdSpecialName); } break; case 194: #line 593 "asmparse.y" { PASM->m_pMarshal = yypvt[-1].binstr; } break; case 195: #line 594 "asmparse.y" { yyval.fieldAttr = (CorFieldAttr) ((yypvt[-1].fieldAttr & ~mdMemberAccessMask) | fdAssembly); } break; case 196: #line 595 "asmparse.y" { yyval.fieldAttr = (CorFieldAttr) ((yypvt[-1].fieldAttr & ~mdMemberAccessMask) | fdFamANDAssem); } break; case 197: #line 596 "asmparse.y" { yyval.fieldAttr = (CorFieldAttr) ((yypvt[-1].fieldAttr & ~mdMemberAccessMask) | fdFamORAssem); } break; case 198: #line 597 "asmparse.y" { yyval.fieldAttr = (CorFieldAttr) ((yypvt[-1].fieldAttr & ~mdMemberAccessMask) | fdPrivateScope); } break; case 199: #line 598 "asmparse.y" { yyval.fieldAttr = (CorFieldAttr) (yypvt[-1].fieldAttr | fdLiteral); } break; case 200: #line 599 "asmparse.y" { yyval.fieldAttr = (CorFieldAttr) (yypvt[-1].fieldAttr | fdNotSerialized); } break; case 201: #line 600 "asmparse.y" { yyval.fieldAttr = (CorFieldAttr) (yypvt[-1].int32); } break; case 202: #line 603 "asmparse.y" { yyval.string = 0; } break; case 203: #line 604 "asmparse.y" { yyval.string = yypvt[-0].string; } break; case 204: #line 607 "asmparse.y" { yyval.binstr = NULL; } break; case 205: #line 608 "asmparse.y" { yyval.binstr = yypvt[-0].binstr; } break; case 206: #line 611 "asmparse.y" { yyval.int32 = 0xFFFFFFFF; } break; case 207: #line 612 "asmparse.y" { yyval.int32 = yypvt[-1].int32; } break; case 208: #line 617 "asmparse.y" { PASM->ResetArgNameList(); if (yypvt[-3].binstr == NULL) { if((iCallConv)&&((yypvt[-8].int32 & iCallConv) != iCallConv)) parser->warn("'instance' added to method's calling convention\n"); yyval.token = PASM->MakeMemberRef(yypvt[-6].token, yypvt[-4].string, parser->MakeSig(yypvt[-8].int32|iCallConv, yypvt[-7].binstr, yypvt[-1].binstr)); } else { mdToken mr; if((iCallConv)&&((yypvt[-8].int32 & iCallConv) != iCallConv)) parser->warn("'instance' added to method's calling convention\n"); mr = PASM->MakeMemberRef(yypvt[-6].token, yypvt[-4].string, parser->MakeSig(yypvt[-8].int32 | IMAGE_CEE_CS_CALLCONV_GENERIC|iCallConv, yypvt[-7].binstr, yypvt[-1].binstr, corCountArgs(yypvt[-3].binstr))); yyval.token = PASM->MakeMethodSpec(mr, parser->MakeSig(IMAGE_CEE_CS_CALLCONV_INSTANTIATION, 0, yypvt[-3].binstr)); } } break; case 209: #line 634 "asmparse.y" { PASM->ResetArgNameList(); if((iCallConv)&&((yypvt[-8].int32 & iCallConv) != iCallConv)) parser->warn("'instance' added to method's calling convention\n"); yyval.token = PASM->MakeMemberRef(yypvt[-6].token, yypvt[-4].string, parser->MakeSig(yypvt[-8].int32 | IMAGE_CEE_CS_CALLCONV_GENERIC|iCallConv, yypvt[-7].binstr, yypvt[-1].binstr, yypvt[-3].int32)); } break; case 210: #line 640 "asmparse.y" { PASM->ResetArgNameList(); if (yypvt[-3].binstr == NULL) { if((iCallConv)&&((yypvt[-6].int32 & iCallConv) != iCallConv)) parser->warn("'instance' added to method's calling convention\n"); yyval.token = PASM->MakeMemberRef(mdTokenNil, yypvt[-4].string, parser->MakeSig(yypvt[-6].int32|iCallConv, yypvt[-5].binstr, yypvt[-1].binstr)); } else { mdToken mr; if((iCallConv)&&((yypvt[-6].int32 & iCallConv) != iCallConv)) parser->warn("'instance' added to method's calling convention\n"); mr = PASM->MakeMemberRef(mdTokenNil, yypvt[-4].string, parser->MakeSig(yypvt[-6].int32 | IMAGE_CEE_CS_CALLCONV_GENERIC|iCallConv, yypvt[-5].binstr, yypvt[-1].binstr, corCountArgs(yypvt[-3].binstr))); yyval.token = PASM->MakeMethodSpec(mr, parser->MakeSig(IMAGE_CEE_CS_CALLCONV_INSTANTIATION, 0, yypvt[-3].binstr)); } } break; case 211: #line 656 "asmparse.y" { PASM->ResetArgNameList(); if((iCallConv)&&((yypvt[-6].int32 & iCallConv) != iCallConv)) parser->warn("'instance' added to method's calling convention\n"); yyval.token = PASM->MakeMemberRef(mdTokenNil, yypvt[-4].string, parser->MakeSig(yypvt[-6].int32 | IMAGE_CEE_CS_CALLCONV_GENERIC|iCallConv, yypvt[-5].binstr, yypvt[-1].binstr, yypvt[-3].int32)); } break; case 212: #line 660 "asmparse.y" { yyval.token = yypvt[-0].token; } break; case 213: #line 661 "asmparse.y" { yyval.token = yypvt[-0].tdd->m_tkTypeSpec; } break; case 214: #line 662 "asmparse.y" { yyval.token = yypvt[-0].tdd->m_tkTypeSpec; } break; case 215: #line 665 "asmparse.y" { yyval.int32 = (yypvt[-0].int32 | IMAGE_CEE_CS_CALLCONV_HASTHIS); } break; case 216: #line 666 "asmparse.y" { yyval.int32 = (yypvt[-0].int32 | IMAGE_CEE_CS_CALLCONV_EXPLICITTHIS); } break; case 217: #line 667 "asmparse.y" { yyval.int32 = yypvt[-0].int32; } break; case 218: #line 668 "asmparse.y" { yyval.int32 = yypvt[-1].int32; } break; case 219: #line 671 "asmparse.y" { yyval.int32 = IMAGE_CEE_CS_CALLCONV_DEFAULT; } break; case 220: #line 672 "asmparse.y" { yyval.int32 = IMAGE_CEE_CS_CALLCONV_DEFAULT; } break; case 221: #line 673 "asmparse.y" { yyval.int32 = IMAGE_CEE_CS_CALLCONV_VARARG; } break; case 222: #line 674 "asmparse.y" { yyval.int32 = IMAGE_CEE_CS_CALLCONV_C; } break; case 223: #line 675 "asmparse.y" { yyval.int32 = IMAGE_CEE_CS_CALLCONV_STDCALL; } break; case 224: #line 676 "asmparse.y" { yyval.int32 = IMAGE_CEE_CS_CALLCONV_THISCALL; } break; case 225: #line 677 "asmparse.y" { yyval.int32 = IMAGE_CEE_CS_CALLCONV_FASTCALL; } break; case 226: #line 678 "asmparse.y" { yyval.int32 = IMAGE_CEE_CS_CALLCONV_UNMANAGED; } break; case 227: #line 681 "asmparse.y" { yyval.token = yypvt[-1].int32; } break; case 228: #line 684 "asmparse.y" { yyval.token = yypvt[-0].token; PASM->delArgNameList(PASM->m_firstArgName); PASM->m_firstArgName = parser->m_ANSFirst.POP(); PASM->m_lastArgName = parser->m_ANSLast.POP(); PASM->SetMemberRefFixup(yypvt[-0].token,iOpcodeLen); } break; case 229: #line 690 "asmparse.y" { yypvt[-3].binstr->insertInt8(IMAGE_CEE_CS_CALLCONV_FIELD); yyval.token = PASM->MakeMemberRef(yypvt[-2].token, yypvt[-0].string, yypvt[-3].binstr); PASM->SetMemberRefFixup(yyval.token,iOpcodeLen); } break; case 230: #line 694 "asmparse.y" { yypvt[-1].binstr->insertInt8(IMAGE_CEE_CS_CALLCONV_FIELD); yyval.token = PASM->MakeMemberRef(NULL, yypvt[-0].string, yypvt[-1].binstr); PASM->SetMemberRefFixup(yyval.token,iOpcodeLen); } break; case 231: #line 697 "asmparse.y" { yyval.token = yypvt[-0].tdd->m_tkTypeSpec; PASM->SetMemberRefFixup(yyval.token,iOpcodeLen); } break; case 232: #line 699 "asmparse.y" { yyval.token = yypvt[-0].tdd->m_tkTypeSpec; PASM->SetMemberRefFixup(yyval.token,iOpcodeLen); } break; case 233: #line 701 "asmparse.y" { yyval.token = yypvt[-0].token; PASM->SetMemberRefFixup(yyval.token,iOpcodeLen); } break; case 234: #line 706 "asmparse.y" { PASM->ResetEvent(yypvt[-0].string, yypvt[-1].token, yypvt[-2].eventAttr); } break; case 235: #line 707 "asmparse.y" { PASM->ResetEvent(yypvt[-0].string, mdTypeRefNil, yypvt[-1].eventAttr); } break; case 236: #line 711 "asmparse.y" { yyval.eventAttr = (CorEventAttr) 0; } break; case 237: #line 712 "asmparse.y" { yyval.eventAttr = yypvt[-1].eventAttr; } break; case 238: #line 713 "asmparse.y" { yyval.eventAttr = (CorEventAttr) (yypvt[-1].eventAttr | evSpecialName); } break; case 241: #line 720 "asmparse.y" { PASM->SetEventMethod(0, yypvt[-0].token); } break; case 242: #line 721 "asmparse.y" { PASM->SetEventMethod(1, yypvt[-0].token); } break; case 243: #line 722 "asmparse.y" { PASM->SetEventMethod(2, yypvt[-0].token); } break; case 244: #line 723 "asmparse.y" { PASM->SetEventMethod(3, yypvt[-0].token); } break; case 249: #line 732 "asmparse.y" { PASM->ResetProp(yypvt[-4].string, parser->MakeSig((IMAGE_CEE_CS_CALLCONV_PROPERTY | (yypvt[-6].int32 & IMAGE_CEE_CS_CALLCONV_HASTHIS)),yypvt[-5].binstr,yypvt[-2].binstr), yypvt[-7].propAttr, yypvt[-0].binstr);} break; case 250: #line 737 "asmparse.y" { yyval.propAttr = (CorPropertyAttr) 0; } break; case 251: #line 738 "asmparse.y" { yyval.propAttr = yypvt[-1].propAttr; } break; case 252: #line 739 "asmparse.y" { yyval.propAttr = (CorPropertyAttr) (yypvt[-1].propAttr | prSpecialName); } break; case 255: #line 747 "asmparse.y" { PASM->SetPropMethod(0, yypvt[-0].token); } break; case 256: #line 748 "asmparse.y" { PASM->SetPropMethod(1, yypvt[-0].token); } break; case 257: #line 749 "asmparse.y" { PASM->SetPropMethod(2, yypvt[-0].token); } break; case 262: #line 757 "asmparse.y" { PASM->ResetForNextMethod(); uMethodBeginLine = PASM->m_ulCurLine; uMethodBeginColumn=PASM->m_ulCurColumn; } break; case 263: #line 763 "asmparse.y" { yyval.binstr = NULL; } break; case 264: #line 764 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; } break; case 265: #line 767 "asmparse.y" { yyval.binstr = yypvt[-0].binstr; } break; case 266: #line 768 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; } break; case 267: #line 771 "asmparse.y" { bParsingByteArray = TRUE; } break; case 268: #line 775 "asmparse.y" { BinStr* sig; if (yypvt[-5].typarlist == NULL) sig = parser->MakeSig(yypvt[-10].int32, yypvt[-8].binstr, yypvt[-3].binstr); else { FixupTyPars(yypvt[-8].binstr); sig = parser->MakeSig(yypvt[-10].int32 | IMAGE_CEE_CS_CALLCONV_GENERIC, yypvt[-8].binstr, yypvt[-3].binstr, yypvt[-5].typarlist->Count()); FixupConstraints(); } PASM->StartMethod(yypvt[-6].string, sig, yypvt[-11].methAttr, yypvt[-7].binstr, yypvt[-9].int32, yypvt[-5].typarlist); TyParFixupList.RESET(false); PASM->SetImplAttr((USHORT)yypvt[-1].implAttr); PASM->m_pCurMethod->m_ulLines[0] = uMethodBeginLine; PASM->m_pCurMethod->m_ulColumns[0]=uMethodBeginColumn; } break; case 269: #line 790 "asmparse.y" { yyval.methAttr = (CorMethodAttr) 0; } break; case 270: #line 791 "asmparse.y" { yyval.methAttr = (CorMethodAttr) (yypvt[-1].methAttr | mdStatic); } break; case 271: #line 792 "asmparse.y" { yyval.methAttr = (CorMethodAttr) ((yypvt[-1].methAttr & ~mdMemberAccessMask) | mdPublic); } break; case 272: #line 793 "asmparse.y" { yyval.methAttr = (CorMethodAttr) ((yypvt[-1].methAttr & ~mdMemberAccessMask) | mdPrivate); } break; case 273: #line 794 "asmparse.y" { yyval.methAttr = (CorMethodAttr) ((yypvt[-1].methAttr & ~mdMemberAccessMask) | mdFamily); } break; case 274: #line 795 "asmparse.y" { yyval.methAttr = (CorMethodAttr) (yypvt[-1].methAttr | mdFinal); } break; case 275: #line 796 "asmparse.y" { yyval.methAttr = (CorMethodAttr) (yypvt[-1].methAttr | mdSpecialName); } break; case 276: #line 797 "asmparse.y" { yyval.methAttr = (CorMethodAttr) (yypvt[-1].methAttr | mdVirtual); } break; case 277: #line 798 "asmparse.y" { yyval.methAttr = (CorMethodAttr) (yypvt[-1].methAttr | mdCheckAccessOnOverride); } break; case 278: #line 799 "asmparse.y" { yyval.methAttr = (CorMethodAttr) (yypvt[-1].methAttr | mdAbstract); } break; case 279: #line 800 "asmparse.y" { yyval.methAttr = (CorMethodAttr) ((yypvt[-1].methAttr & ~mdMemberAccessMask) | mdAssem); } break; case 280: #line 801 "asmparse.y" { yyval.methAttr = (CorMethodAttr) ((yypvt[-1].methAttr & ~mdMemberAccessMask) | mdFamANDAssem); } break; case 281: #line 802 "asmparse.y" { yyval.methAttr = (CorMethodAttr) ((yypvt[-1].methAttr & ~mdMemberAccessMask) | mdFamORAssem); } break; case 282: #line 803 "asmparse.y" { yyval.methAttr = (CorMethodAttr) ((yypvt[-1].methAttr & ~mdMemberAccessMask) | mdPrivateScope); } break; case 283: #line 804 "asmparse.y" { yyval.methAttr = (CorMethodAttr) (yypvt[-1].methAttr | mdHideBySig); } break; case 284: #line 805 "asmparse.y" { yyval.methAttr = (CorMethodAttr) (yypvt[-1].methAttr | mdNewSlot); } break; case 285: #line 806 "asmparse.y" { yyval.methAttr = yypvt[-1].methAttr; } break; case 286: #line 807 "asmparse.y" { yyval.methAttr = (CorMethodAttr) (yypvt[-1].methAttr | mdUnmanagedExport); } break; case 287: #line 808 "asmparse.y" { yyval.methAttr = (CorMethodAttr) (yypvt[-1].methAttr | mdRequireSecObject); } break; case 288: #line 809 "asmparse.y" { yyval.methAttr = (CorMethodAttr) (yypvt[-1].int32); } break; case 289: #line 811 "asmparse.y" { PASM->SetPinvoke(yypvt[-4].binstr,0,yypvt[-2].binstr,yypvt[-1].pinvAttr); yyval.methAttr = (CorMethodAttr) (yypvt[-7].methAttr | mdPinvokeImpl); } break; case 290: #line 814 "asmparse.y" { PASM->SetPinvoke(yypvt[-2].binstr,0,NULL,yypvt[-1].pinvAttr); yyval.methAttr = (CorMethodAttr) (yypvt[-5].methAttr | mdPinvokeImpl); } break; case 291: #line 817 "asmparse.y" { PASM->SetPinvoke(new BinStr(),0,NULL,yypvt[-1].pinvAttr); yyval.methAttr = (CorMethodAttr) (yypvt[-4].methAttr | mdPinvokeImpl); } break; case 292: #line 821 "asmparse.y" { yyval.pinvAttr = (CorPinvokeMap) 0; } break; case 293: #line 822 "asmparse.y" { yyval.pinvAttr = (CorPinvokeMap) (yypvt[-1].pinvAttr | pmNoMangle); } break; case 294: #line 823 "asmparse.y" { yyval.pinvAttr = (CorPinvokeMap) (yypvt[-1].pinvAttr | pmCharSetAnsi); } break; case 295: #line 824 "asmparse.y" { yyval.pinvAttr = (CorPinvokeMap) (yypvt[-1].pinvAttr | pmCharSetUnicode); } break; case 296: #line 825 "asmparse.y" { yyval.pinvAttr = (CorPinvokeMap) (yypvt[-1].pinvAttr | pmCharSetAuto); } break; case 297: #line 826 "asmparse.y" { yyval.pinvAttr = (CorPinvokeMap) (yypvt[-1].pinvAttr | pmSupportsLastError); } break; case 298: #line 827 "asmparse.y" { yyval.pinvAttr = (CorPinvokeMap) (yypvt[-1].pinvAttr | pmCallConvWinapi); } break; case 299: #line 828 "asmparse.y" { yyval.pinvAttr = (CorPinvokeMap) (yypvt[-1].pinvAttr | pmCallConvCdecl); } break; case 300: #line 829 "asmparse.y" { yyval.pinvAttr = (CorPinvokeMap) (yypvt[-1].pinvAttr | pmCallConvStdcall); } break; case 301: #line 830 "asmparse.y" { yyval.pinvAttr = (CorPinvokeMap) (yypvt[-1].pinvAttr | pmCallConvThiscall); } break; case 302: #line 831 "asmparse.y" { yyval.pinvAttr = (CorPinvokeMap) (yypvt[-1].pinvAttr | pmCallConvFastcall); } break; case 303: #line 832 "asmparse.y" { yyval.pinvAttr = (CorPinvokeMap) (yypvt[-3].pinvAttr | pmBestFitEnabled); } break; case 304: #line 833 "asmparse.y" { yyval.pinvAttr = (CorPinvokeMap) (yypvt[-3].pinvAttr | pmBestFitDisabled); } break; case 305: #line 834 "asmparse.y" { yyval.pinvAttr = (CorPinvokeMap) (yypvt[-3].pinvAttr | pmThrowOnUnmappableCharEnabled); } break; case 306: #line 835 "asmparse.y" { yyval.pinvAttr = (CorPinvokeMap) (yypvt[-3].pinvAttr | pmThrowOnUnmappableCharDisabled); } break; case 307: #line 836 "asmparse.y" { yyval.pinvAttr = (CorPinvokeMap) (yypvt[-1].int32); } break; case 308: #line 839 "asmparse.y" { yyval.string = newString(COR_CTOR_METHOD_NAME); } break; case 309: #line 840 "asmparse.y" { yyval.string = newString(COR_CCTOR_METHOD_NAME); } break; case 310: #line 841 "asmparse.y" { yyval.string = yypvt[-0].string; } break; case 311: #line 844 "asmparse.y" { yyval.int32 = 0; } break; case 312: #line 845 "asmparse.y" { yyval.int32 = yypvt[-3].int32 | pdIn; } break; case 313: #line 846 "asmparse.y" { yyval.int32 = yypvt[-3].int32 | pdOut; } break; case 314: #line 847 "asmparse.y" { yyval.int32 = yypvt[-3].int32 | pdOptional; } break; case 315: #line 848 "asmparse.y" { yyval.int32 = yypvt[-1].int32 + 1; } break; case 316: #line 851 "asmparse.y" { yyval.implAttr = (CorMethodImpl) (miIL | miManaged); } break; case 317: #line 852 "asmparse.y" { yyval.implAttr = (CorMethodImpl) ((yypvt[-1].implAttr & 0xFFF4) | miNative); } break; case 318: #line 853 "asmparse.y" { yyval.implAttr = (CorMethodImpl) ((yypvt[-1].implAttr & 0xFFF4) | miIL); } break; case 319: #line 854 "asmparse.y" { yyval.implAttr = (CorMethodImpl) ((yypvt[-1].implAttr & 0xFFF4) | miOPTIL); } break; case 320: #line 855 "asmparse.y" { yyval.implAttr = (CorMethodImpl) ((yypvt[-1].implAttr & 0xFFFB) | miManaged); } break; case 321: #line 856 "asmparse.y" { yyval.implAttr = (CorMethodImpl) ((yypvt[-1].implAttr & 0xFFFB) | miUnmanaged); } break; case 322: #line 857 "asmparse.y" { yyval.implAttr = (CorMethodImpl) (yypvt[-1].implAttr | miForwardRef); } break; case 323: #line 858 "asmparse.y" { yyval.implAttr = (CorMethodImpl) (yypvt[-1].implAttr | miPreserveSig); } break; case 324: #line 859 "asmparse.y" { yyval.implAttr = (CorMethodImpl) (yypvt[-1].implAttr | miRuntime); } break; case 325: #line 860 "asmparse.y" { yyval.implAttr = (CorMethodImpl) (yypvt[-1].implAttr | miInternalCall); } break; case 326: #line 861 "asmparse.y" { yyval.implAttr = (CorMethodImpl) (yypvt[-1].implAttr | miSynchronized); } break; case 327: #line 862 "asmparse.y" { yyval.implAttr = (CorMethodImpl) (yypvt[-1].implAttr | miNoInlining); } break; case 328: #line 863 "asmparse.y" { yyval.implAttr = (CorMethodImpl) (yypvt[-1].implAttr | miAggressiveInlining); } break; case 329: #line 864 "asmparse.y" { yyval.implAttr = (CorMethodImpl) (yypvt[-1].implAttr | miNoOptimization); } break; case 330: #line 865 "asmparse.y" { yyval.implAttr = (CorMethodImpl) (yypvt[-1].implAttr | miAggressiveOptimization); } break; case 331: #line 866 "asmparse.y" { yyval.implAttr = (CorMethodImpl) (yypvt[-1].int32); } break; case 332: #line 869 "asmparse.y" { PASM->delArgNameList(PASM->m_firstArgName); PASM->m_firstArgName = NULL;PASM->m_lastArgName = NULL; } break; case 335: #line 877 "asmparse.y" { PASM->EmitByte(yypvt[-0].int32); } break; case 336: #line 878 "asmparse.y" { delete PASM->m_SEHD; PASM->m_SEHD = PASM->m_SEHDstack.POP(); } break; case 337: #line 879 "asmparse.y" { PASM->EmitMaxStack(yypvt[-0].int32); } break; case 338: #line 880 "asmparse.y" { PASM->EmitLocals(parser->MakeSig(IMAGE_CEE_CS_CALLCONV_LOCAL_SIG, 0, yypvt[-1].binstr)); } break; case 339: #line 882 "asmparse.y" { PASM->EmitZeroInit(); PASM->EmitLocals(parser->MakeSig(IMAGE_CEE_CS_CALLCONV_LOCAL_SIG, 0, yypvt[-1].binstr)); } break; case 340: #line 885 "asmparse.y" { PASM->EmitEntryPoint(); } break; case 341: #line 886 "asmparse.y" { PASM->EmitZeroInit(); } break; case 344: #line 889 "asmparse.y" { PASM->AddLabel(PASM->m_CurPC,yypvt[-1].string); /*PASM->EmitLabel($1);*/ } break; case 350: #line 895 "asmparse.y" { if(PASM->m_pCurMethod->m_dwExportOrdinal == 0xFFFFFFFF) { PASM->m_pCurMethod->m_dwExportOrdinal = yypvt[-1].int32; PASM->m_pCurMethod->m_szExportAlias = NULL; if(PASM->m_pCurMethod->m_wVTEntry == 0) PASM->m_pCurMethod->m_wVTEntry = 1; if(PASM->m_pCurMethod->m_wVTSlot == 0) PASM->m_pCurMethod->m_wVTSlot = yypvt[-1].int32 + 0x8000; } else PASM->report->warn("Duplicate .export directive, ignored\n"); } break; case 351: #line 905 "asmparse.y" { if(PASM->m_pCurMethod->m_dwExportOrdinal == 0xFFFFFFFF) { PASM->m_pCurMethod->m_dwExportOrdinal = yypvt[-3].int32; PASM->m_pCurMethod->m_szExportAlias = yypvt[-0].string; if(PASM->m_pCurMethod->m_wVTEntry == 0) PASM->m_pCurMethod->m_wVTEntry = 1; if(PASM->m_pCurMethod->m_wVTSlot == 0) PASM->m_pCurMethod->m_wVTSlot = yypvt[-3].int32 + 0x8000; } else PASM->report->warn("Duplicate .export directive, ignored\n"); } break; case 352: #line 915 "asmparse.y" { PASM->m_pCurMethod->m_wVTEntry = (WORD)yypvt[-2].int32; PASM->m_pCurMethod->m_wVTSlot = (WORD)yypvt[-0].int32; } break; case 353: #line 918 "asmparse.y" { PASM->AddMethodImpl(yypvt[-2].token,yypvt[-0].string,NULL,NULL,NULL,NULL); } break; case 354: #line 921 "asmparse.y" { PASM->AddMethodImpl(yypvt[-6].token,yypvt[-4].string, (yypvt[-3].int32==0 ? parser->MakeSig(yypvt[-8].int32,yypvt[-7].binstr,yypvt[-1].binstr) : parser->MakeSig(yypvt[-8].int32| IMAGE_CEE_CS_CALLCONV_GENERIC,yypvt[-7].binstr,yypvt[-1].binstr,yypvt[-3].int32)) ,NULL,NULL,NULL); PASM->ResetArgNameList(); } break; case 356: #line 928 "asmparse.y" { if((yypvt[-1].int32 > 0) && (yypvt[-1].int32 <= (int)PASM->m_pCurMethod->m_NumTyPars)) PASM->m_pCustomDescrList = PASM->m_pCurMethod->m_TyPars[yypvt[-1].int32-1].CAList(); else PASM->report->error("Type parameter index out of range\n"); } break; case 357: #line 933 "asmparse.y" { int n = PASM->m_pCurMethod->FindTyPar(yypvt[-0].string); if(n >= 0) PASM->m_pCustomDescrList = PASM->m_pCurMethod->m_TyPars[n].CAList(); else PASM->report->error("Type parameter '%s' undefined\n",yypvt[-0].string); } break; case 358: #line 939 "asmparse.y" { PASM->m_pCurMethod->AddGenericParamConstraint(yypvt[-3].int32, 0, yypvt[-0].token); } break; case 359: #line 940 "asmparse.y" { PASM->m_pCurMethod->AddGenericParamConstraint(0, yypvt[-2].string, yypvt[-0].token); } break; case 360: #line 943 "asmparse.y" { if( yypvt[-2].int32 ) { ARG_NAME_LIST* pAN=PASM->findArg(PASM->m_pCurMethod->m_firstArgName, yypvt[-2].int32 - 1); if(pAN) { PASM->m_pCustomDescrList = &(pAN->CustDList); pAN->pValue = yypvt[-0].binstr; } else { PASM->m_pCustomDescrList = NULL; if(yypvt[-0].binstr) delete yypvt[-0].binstr; } } else { PASM->m_pCustomDescrList = &(PASM->m_pCurMethod->m_RetCustDList); PASM->m_pCurMethod->m_pRetValue = yypvt[-0].binstr; } PASM->m_tkCurrentCVOwner = 0; } break; case 361: #line 963 "asmparse.y" { PASM->m_pCurMethod->CloseScope(); } break; case 362: #line 966 "asmparse.y" { PASM->m_pCurMethod->OpenScope(); } break; case 366: #line 977 "asmparse.y" { PASM->m_SEHD->tryTo = PASM->m_CurPC; } break; case 367: #line 978 "asmparse.y" { PASM->SetTryLabels(yypvt[-2].string, yypvt[-0].string); } break; case 368: #line 979 "asmparse.y" { if(PASM->m_SEHD) {PASM->m_SEHD->tryFrom = yypvt[-2].int32; PASM->m_SEHD->tryTo = yypvt[-0].int32;} } break; case 369: #line 983 "asmparse.y" { PASM->NewSEHDescriptor(); PASM->m_SEHD->tryFrom = PASM->m_CurPC; } break; case 370: #line 988 "asmparse.y" { PASM->EmitTry(); } break; case 371: #line 989 "asmparse.y" { PASM->EmitTry(); } break; case 372: #line 990 "asmparse.y" { PASM->EmitTry(); } break; case 373: #line 991 "asmparse.y" { PASM->EmitTry(); } break; case 374: #line 995 "asmparse.y" { PASM->m_SEHD->sehHandler = PASM->m_CurPC; } break; case 375: #line 996 "asmparse.y" { PASM->SetFilterLabel(yypvt[-0].string); PASM->m_SEHD->sehHandler = PASM->m_CurPC; } break; case 376: #line 998 "asmparse.y" { PASM->m_SEHD->sehFilter = yypvt[-0].int32; PASM->m_SEHD->sehHandler = PASM->m_CurPC; } break; case 377: #line 1002 "asmparse.y" { PASM->m_SEHD->sehClause = COR_ILEXCEPTION_CLAUSE_FILTER; PASM->m_SEHD->sehFilter = PASM->m_CurPC; } break; case 378: #line 1006 "asmparse.y" { PASM->m_SEHD->sehClause = COR_ILEXCEPTION_CLAUSE_NONE; PASM->SetCatchClass(yypvt[-0].token); PASM->m_SEHD->sehHandler = PASM->m_CurPC; } break; case 379: #line 1011 "asmparse.y" { PASM->m_SEHD->sehClause = COR_ILEXCEPTION_CLAUSE_FINALLY; PASM->m_SEHD->sehHandler = PASM->m_CurPC; } break; case 380: #line 1015 "asmparse.y" { PASM->m_SEHD->sehClause = COR_ILEXCEPTION_CLAUSE_FAULT; PASM->m_SEHD->sehHandler = PASM->m_CurPC; } break; case 381: #line 1019 "asmparse.y" { PASM->m_SEHD->sehHandlerTo = PASM->m_CurPC; } break; case 382: #line 1020 "asmparse.y" { PASM->SetHandlerLabels(yypvt[-2].string, yypvt[-0].string); } break; case 383: #line 1021 "asmparse.y" { PASM->m_SEHD->sehHandler = yypvt[-2].int32; PASM->m_SEHD->sehHandlerTo = yypvt[-0].int32; } break; case 385: #line 1029 "asmparse.y" { PASM->EmitDataLabel(yypvt[-1].string); } break; case 387: #line 1033 "asmparse.y" { PASM->SetDataSection(); } break; case 388: #line 1034 "asmparse.y" { PASM->SetTLSSection(); } break; case 389: #line 1035 "asmparse.y" { PASM->SetILSection(); } break; case 394: #line 1046 "asmparse.y" { yyval.int32 = 1; } break; case 395: #line 1047 "asmparse.y" { yyval.int32 = yypvt[-1].int32; if(yypvt[-1].int32 <= 0) { PASM->report->error("Illegal item count: %d\n",yypvt[-1].int32); if(!PASM->OnErrGo) yyval.int32 = 1; }} break; case 396: #line 1052 "asmparse.y" { PASM->EmitDataString(yypvt[-1].binstr); } break; case 397: #line 1053 "asmparse.y" { PASM->EmitDD(yypvt[-1].string); } break; case 398: #line 1054 "asmparse.y" { PASM->EmitData(yypvt[-1].binstr->ptr(),yypvt[-1].binstr->length()); } break; case 399: #line 1056 "asmparse.y" { float f = (float) (*yypvt[-2].float64); float* p = new (nothrow) float[yypvt[-0].int32]; if(p != NULL) { for(int i=0; i < yypvt[-0].int32; i++) p[i] = f; PASM->EmitData(p, sizeof(float)*yypvt[-0].int32); delete yypvt[-2].float64; delete [] p; } else PASM->report->error("Out of memory emitting data block %d bytes\n", sizeof(float)*yypvt[-0].int32); } break; case 400: #line 1063 "asmparse.y" { double* p = new (nothrow) double[yypvt[-0].int32]; if(p != NULL) { for(int i=0; i<yypvt[-0].int32; i++) p[i] = *(yypvt[-2].float64); PASM->EmitData(p, sizeof(double)*yypvt[-0].int32); delete yypvt[-2].float64; delete [] p; } else PASM->report->error("Out of memory emitting data block %d bytes\n", sizeof(double)*yypvt[-0].int32); } break; case 401: #line 1070 "asmparse.y" { __int64* p = new (nothrow) __int64[yypvt[-0].int32]; if(p != NULL) { for(int i=0; i<yypvt[-0].int32; i++) p[i] = *(yypvt[-2].int64); PASM->EmitData(p, sizeof(__int64)*yypvt[-0].int32); delete yypvt[-2].int64; delete [] p; } else PASM->report->error("Out of memory emitting data block %d bytes\n", sizeof(__int64)*yypvt[-0].int32); } break; case 402: #line 1077 "asmparse.y" { __int32* p = new (nothrow) __int32[yypvt[-0].int32]; if(p != NULL) { for(int i=0; i<yypvt[-0].int32; i++) p[i] = yypvt[-2].int32; PASM->EmitData(p, sizeof(__int32)*yypvt[-0].int32); delete [] p; } else PASM->report->error("Out of memory emitting data block %d bytes\n", sizeof(__int32)*yypvt[-0].int32); } break; case 403: #line 1084 "asmparse.y" { __int16 i = (__int16) yypvt[-2].int32; FAIL_UNLESS(i == yypvt[-2].int32, ("Value %d too big\n", yypvt[-2].int32)); __int16* p = new (nothrow) __int16[yypvt[-0].int32]; if(p != NULL) { for(int j=0; j<yypvt[-0].int32; j++) p[j] = i; PASM->EmitData(p, sizeof(__int16)*yypvt[-0].int32); delete [] p; } else PASM->report->error("Out of memory emitting data block %d bytes\n", sizeof(__int16)*yypvt[-0].int32); } break; case 404: #line 1092 "asmparse.y" { __int8 i = (__int8) yypvt[-2].int32; FAIL_UNLESS(i == yypvt[-2].int32, ("Value %d too big\n", yypvt[-2].int32)); __int8* p = new (nothrow) __int8[yypvt[-0].int32]; if(p != NULL) { for(int j=0; j<yypvt[-0].int32; j++) p[j] = i; PASM->EmitData(p, sizeof(__int8)*yypvt[-0].int32); delete [] p; } else PASM->report->error("Out of memory emitting data block %d bytes\n", sizeof(__int8)*yypvt[-0].int32); } break; case 405: #line 1099 "asmparse.y" { PASM->EmitData(NULL, sizeof(float)*yypvt[-0].int32); } break; case 406: #line 1100 "asmparse.y" { PASM->EmitData(NULL, sizeof(double)*yypvt[-0].int32); } break; case 407: #line 1101 "asmparse.y" { PASM->EmitData(NULL, sizeof(__int64)*yypvt[-0].int32); } break; case 408: #line 1102 "asmparse.y" { PASM->EmitData(NULL, sizeof(__int32)*yypvt[-0].int32); } break; case 409: #line 1103 "asmparse.y" { PASM->EmitData(NULL, sizeof(__int16)*yypvt[-0].int32); } break; case 410: #line 1104 "asmparse.y" { PASM->EmitData(NULL, sizeof(__int8)*yypvt[-0].int32); } break; case 411: #line 1108 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_R4); float f = (float)(*yypvt[-1].float64); yyval.binstr->appendInt32(*((__int32*)&f)); delete yypvt[-1].float64; } break; case 412: #line 1111 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_R8); yyval.binstr->appendInt64((__int64 *)yypvt[-1].float64); delete yypvt[-1].float64; } break; case 413: #line 1113 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_R4); yyval.binstr->appendInt32(yypvt[-1].int32); } break; case 414: #line 1115 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_R8); yyval.binstr->appendInt64((__int64 *)yypvt[-1].int64); delete yypvt[-1].int64; } break; case 415: #line 1117 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_I8); yyval.binstr->appendInt64((__int64 *)yypvt[-1].int64); delete yypvt[-1].int64; } break; case 416: #line 1119 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_I4); yyval.binstr->appendInt32(yypvt[-1].int32); } break; case 417: #line 1121 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_I2); yyval.binstr->appendInt16(yypvt[-1].int32); } break; case 418: #line 1123 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_I1); yyval.binstr->appendInt8(yypvt[-1].int32); } break; case 419: #line 1125 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_U8); yyval.binstr->appendInt64((__int64 *)yypvt[-1].int64); delete yypvt[-1].int64; } break; case 420: #line 1127 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_U4); yyval.binstr->appendInt32(yypvt[-1].int32); } break; case 421: #line 1129 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_U2); yyval.binstr->appendInt16(yypvt[-1].int32); } break; case 422: #line 1131 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_U1); yyval.binstr->appendInt8(yypvt[-1].int32); } break; case 423: #line 1133 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_U8); yyval.binstr->appendInt64((__int64 *)yypvt[-1].int64); delete yypvt[-1].int64; } break; case 424: #line 1135 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_U4); yyval.binstr->appendInt32(yypvt[-1].int32); } break; case 425: #line 1137 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_U2); yyval.binstr->appendInt16(yypvt[-1].int32); } break; case 426: #line 1139 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_U1); yyval.binstr->appendInt8(yypvt[-1].int32); } break; case 427: #line 1141 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_CHAR); yyval.binstr->appendInt16(yypvt[-1].int32); } break; case 428: #line 1143 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_BOOLEAN); yyval.binstr->appendInt8(yypvt[-1].int32);} break; case 429: #line 1145 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_STRING); yyval.binstr->append(yypvt[-1].binstr); delete yypvt[-1].binstr;} break; case 430: #line 1149 "asmparse.y" { bParsingByteArray = TRUE; } break; case 431: #line 1152 "asmparse.y" { yyval.binstr = new BinStr(); } break; case 432: #line 1153 "asmparse.y" { yyval.binstr = yypvt[-0].binstr; } break; case 433: #line 1156 "asmparse.y" { __int8 i = (__int8) yypvt[-0].int32; yyval.binstr = new BinStr(); yyval.binstr->appendInt8(i); } break; case 434: #line 1157 "asmparse.y" { __int8 i = (__int8) yypvt[-0].int32; yyval.binstr = yypvt[-1].binstr; yyval.binstr->appendInt8(i); } break; case 435: #line 1161 "asmparse.y" { yyval.binstr = yypvt[-0].binstr; } break; case 436: #line 1162 "asmparse.y" { yyval.binstr = BinStrToUnicode(yypvt[-0].binstr,true); yyval.binstr->insertInt8(ELEMENT_TYPE_STRING);} break; case 437: #line 1163 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_CLASS); yyval.binstr->appendInt32(0); } break; case 438: #line 1168 "asmparse.y" { yyval.binstr = yypvt[-0].binstr; } break; case 439: #line 1169 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_STRING); yyval.binstr->appendInt8(0xFF); } break; case 440: #line 1170 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_STRING); AppendStringWithLength(yyval.binstr,yypvt[-1].string); delete [] yypvt[-1].string;} break; case 441: #line 1172 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(SERIALIZATION_TYPE_TYPE); AppendStringWithLength(yyval.binstr,yypvt[-1].string); delete [] yypvt[-1].string;} break; case 442: #line 1174 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(SERIALIZATION_TYPE_TYPE); AppendStringWithLength(yyval.binstr,PASM->ReflectionNotation(yypvt[-1].token));} break; case 443: #line 1176 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(SERIALIZATION_TYPE_TYPE); yyval.binstr->appendInt8(0xFF); } break; case 444: #line 1177 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->insertInt8(SERIALIZATION_TYPE_TAGGED_OBJECT);} break; case 445: #line 1179 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->insertInt32(yypvt[-4].int32); yyval.binstr->insertInt8(ELEMENT_TYPE_R4); yyval.binstr->insertInt8(ELEMENT_TYPE_SZARRAY); } break; case 446: #line 1183 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->insertInt32(yypvt[-4].int32); yyval.binstr->insertInt8(ELEMENT_TYPE_R8); yyval.binstr->insertInt8(ELEMENT_TYPE_SZARRAY); } break; case 447: #line 1187 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->insertInt32(yypvt[-4].int32); yyval.binstr->insertInt8(ELEMENT_TYPE_I8); yyval.binstr->insertInt8(ELEMENT_TYPE_SZARRAY); } break; case 448: #line 1191 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->insertInt32(yypvt[-4].int32); yyval.binstr->insertInt8(ELEMENT_TYPE_I4); yyval.binstr->insertInt8(ELEMENT_TYPE_SZARRAY); } break; case 449: #line 1195 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->insertInt32(yypvt[-4].int32); yyval.binstr->insertInt8(ELEMENT_TYPE_I2); yyval.binstr->insertInt8(ELEMENT_TYPE_SZARRAY); } break; case 450: #line 1199 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->insertInt32(yypvt[-4].int32); yyval.binstr->insertInt8(ELEMENT_TYPE_I1); yyval.binstr->insertInt8(ELEMENT_TYPE_SZARRAY); } break; case 451: #line 1203 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->insertInt32(yypvt[-4].int32); yyval.binstr->insertInt8(ELEMENT_TYPE_U8); yyval.binstr->insertInt8(ELEMENT_TYPE_SZARRAY); } break; case 452: #line 1207 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->insertInt32(yypvt[-4].int32); yyval.binstr->insertInt8(ELEMENT_TYPE_U4); yyval.binstr->insertInt8(ELEMENT_TYPE_SZARRAY); } break; case 453: #line 1211 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->insertInt32(yypvt[-4].int32); yyval.binstr->insertInt8(ELEMENT_TYPE_U2); yyval.binstr->insertInt8(ELEMENT_TYPE_SZARRAY); } break; case 454: #line 1215 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->insertInt32(yypvt[-4].int32); yyval.binstr->insertInt8(ELEMENT_TYPE_U1); yyval.binstr->insertInt8(ELEMENT_TYPE_SZARRAY); } break; case 455: #line 1219 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->insertInt32(yypvt[-4].int32); yyval.binstr->insertInt8(ELEMENT_TYPE_U8); yyval.binstr->insertInt8(ELEMENT_TYPE_SZARRAY); } break; case 456: #line 1223 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->insertInt32(yypvt[-4].int32); yyval.binstr->insertInt8(ELEMENT_TYPE_U4); yyval.binstr->insertInt8(ELEMENT_TYPE_SZARRAY); } break; case 457: #line 1227 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->insertInt32(yypvt[-4].int32); yyval.binstr->insertInt8(ELEMENT_TYPE_U2); yyval.binstr->insertInt8(ELEMENT_TYPE_SZARRAY); } break; case 458: #line 1231 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->insertInt32(yypvt[-4].int32); yyval.binstr->insertInt8(ELEMENT_TYPE_U1); yyval.binstr->insertInt8(ELEMENT_TYPE_SZARRAY); } break; case 459: #line 1235 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->insertInt32(yypvt[-4].int32); yyval.binstr->insertInt8(ELEMENT_TYPE_CHAR); yyval.binstr->insertInt8(ELEMENT_TYPE_SZARRAY); } break; case 460: #line 1239 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->insertInt32(yypvt[-4].int32); yyval.binstr->insertInt8(ELEMENT_TYPE_BOOLEAN); yyval.binstr->insertInt8(ELEMENT_TYPE_SZARRAY); } break; case 461: #line 1243 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->insertInt32(yypvt[-4].int32); yyval.binstr->insertInt8(ELEMENT_TYPE_STRING); yyval.binstr->insertInt8(ELEMENT_TYPE_SZARRAY); } break; case 462: #line 1247 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->insertInt32(yypvt[-4].int32); yyval.binstr->insertInt8(SERIALIZATION_TYPE_TYPE); yyval.binstr->insertInt8(ELEMENT_TYPE_SZARRAY); } break; case 463: #line 1251 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->insertInt32(yypvt[-4].int32); yyval.binstr->insertInt8(SERIALIZATION_TYPE_TAGGED_OBJECT); yyval.binstr->insertInt8(ELEMENT_TYPE_SZARRAY); } break; case 464: #line 1257 "asmparse.y" { yyval.binstr = new BinStr(); } break; case 465: #line 1258 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; float f = (float) (*yypvt[-0].float64); yyval.binstr->appendInt32(*((__int32*)&f)); delete yypvt[-0].float64; } break; case 466: #line 1260 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->appendInt32(yypvt[-0].int32); } break; case 467: #line 1264 "asmparse.y" { yyval.binstr = new BinStr(); } break; case 468: #line 1265 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->appendInt64((__int64 *)yypvt[-0].float64); delete yypvt[-0].float64; } break; case 469: #line 1267 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->appendInt64((__int64 *)yypvt[-0].int64); delete yypvt[-0].int64; } break; case 470: #line 1271 "asmparse.y" { yyval.binstr = new BinStr(); } break; case 471: #line 1272 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->appendInt64((__int64 *)yypvt[-0].int64); delete yypvt[-0].int64; } break; case 472: #line 1276 "asmparse.y" { yyval.binstr = new BinStr(); } break; case 473: #line 1277 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->appendInt32(yypvt[-0].int32);} break; case 474: #line 1280 "asmparse.y" { yyval.binstr = new BinStr(); } break; case 475: #line 1281 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->appendInt16(yypvt[-0].int32);} break; case 476: #line 1284 "asmparse.y" { yyval.binstr = new BinStr(); } break; case 477: #line 1285 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->appendInt8(yypvt[-0].int32); } break; case 478: #line 1288 "asmparse.y" { yyval.binstr = new BinStr(); } break; case 479: #line 1289 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->appendInt8(yypvt[-0].int32);} break; case 480: #line 1293 "asmparse.y" { yyval.binstr = new BinStr(); } break; case 481: #line 1294 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->appendInt8(0xFF); } break; case 482: #line 1295 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; AppendStringWithLength(yyval.binstr,yypvt[-0].string); delete [] yypvt[-0].string;} break; case 483: #line 1299 "asmparse.y" { yyval.binstr = new BinStr(); } break; case 484: #line 1300 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->appendInt8(0xFF); } break; case 485: #line 1301 "asmparse.y" { yyval.binstr = yypvt[-2].binstr; AppendStringWithLength(yyval.binstr,yypvt[-0].string); delete [] yypvt[-0].string;} break; case 486: #line 1303 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; AppendStringWithLength(yyval.binstr,PASM->ReflectionNotation(yypvt[-0].token));} break; case 487: #line 1307 "asmparse.y" { yyval.binstr = new BinStr(); } break; case 488: #line 1308 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->append(yypvt[-0].binstr); delete yypvt[-0].binstr; } break; case 489: #line 1312 "asmparse.y" { parser->m_ANSFirst.PUSH(PASM->m_firstArgName); parser->m_ANSLast.PUSH(PASM->m_lastArgName); PASM->m_firstArgName = NULL; PASM->m_lastArgName = NULL; } break; case 490: #line 1318 "asmparse.y" { yyval.instr = SetupInstr(yypvt[-0].opcode); } break; case 491: #line 1321 "asmparse.y" { yyval.instr = SetupInstr(yypvt[-0].opcode); } break; case 492: #line 1324 "asmparse.y" { yyval.instr = SetupInstr(yypvt[-0].opcode); } break; case 493: #line 1327 "asmparse.y" { yyval.instr = SetupInstr(yypvt[-0].opcode); } break; case 494: #line 1330 "asmparse.y" { yyval.instr = SetupInstr(yypvt[-0].opcode); } break; case 495: #line 1333 "asmparse.y" { yyval.instr = SetupInstr(yypvt[-0].opcode); } break; case 496: #line 1336 "asmparse.y" { yyval.instr = SetupInstr(yypvt[-0].opcode); if((!PASM->OnErrGo)&& ((yypvt[-0].opcode == CEE_NEWOBJ)|| (yypvt[-0].opcode == CEE_CALLVIRT))) iCallConv = IMAGE_CEE_CS_CALLCONV_HASTHIS; } break; case 497: #line 1344 "asmparse.y" { yyval.instr = SetupInstr(yypvt[-0].opcode); } break; case 498: #line 1347 "asmparse.y" { yyval.instr = SetupInstr(yypvt[-0].opcode); } break; case 499: #line 1350 "asmparse.y" { yyval.instr = SetupInstr(yypvt[-0].opcode); } break; case 500: #line 1353 "asmparse.y" { yyval.instr = SetupInstr(yypvt[-0].opcode); } break; case 501: #line 1356 "asmparse.y" { yyval.instr = SetupInstr(yypvt[-0].opcode); iOpcodeLen = PASM->OpcodeLen(yyval.instr); } break; case 502: #line 1359 "asmparse.y" { yyval.instr = SetupInstr(yypvt[-0].opcode); } break; case 503: #line 1362 "asmparse.y" { yyval.instr = yypvt[-1].instr; bParsingByteArray = TRUE; } break; case 504: #line 1366 "asmparse.y" { PASM->EmitOpcode(yypvt[-0].instr); } break; case 505: #line 1367 "asmparse.y" { PASM->EmitInstrVar(yypvt[-1].instr, yypvt[-0].int32); } break; case 506: #line 1368 "asmparse.y" { PASM->EmitInstrVarByName(yypvt[-1].instr, yypvt[-0].string); } break; case 507: #line 1369 "asmparse.y" { PASM->EmitInstrI(yypvt[-1].instr, yypvt[-0].int32); } break; case 508: #line 1370 "asmparse.y" { PASM->EmitInstrI8(yypvt[-1].instr, yypvt[-0].int64); } break; case 509: #line 1371 "asmparse.y" { PASM->EmitInstrR(yypvt[-1].instr, yypvt[-0].float64); delete (yypvt[-0].float64);} break; case 510: #line 1372 "asmparse.y" { double f = (double) (*yypvt[-0].int64); PASM->EmitInstrR(yypvt[-1].instr, &f); } break; case 511: #line 1373 "asmparse.y" { unsigned L = yypvt[-1].binstr->length(); FAIL_UNLESS(L >= sizeof(float), ("%d hexbytes, must be at least %d\n", L,sizeof(float))); if(L < sizeof(float)) {YYERROR; } else { double f = (L >= sizeof(double)) ? *((double *)(yypvt[-1].binstr->ptr())) : (double)(*(float *)(yypvt[-1].binstr->ptr())); PASM->EmitInstrR(yypvt[-2].instr,&f); } delete yypvt[-1].binstr; } break; case 512: #line 1382 "asmparse.y" { PASM->EmitInstrBrOffset(yypvt[-1].instr, yypvt[-0].int32); } break; case 513: #line 1383 "asmparse.y" { PASM->EmitInstrBrTarget(yypvt[-1].instr, yypvt[-0].string); } break; case 514: #line 1385 "asmparse.y" { PASM->SetMemberRefFixup(yypvt[-0].token,PASM->OpcodeLen(yypvt[-1].instr)); PASM->EmitInstrI(yypvt[-1].instr,yypvt[-0].token); PASM->m_tkCurrentCVOwner = yypvt[-0].token; PASM->m_pCustomDescrList = NULL; iCallConv = 0; } break; case 515: #line 1392 "asmparse.y" { yypvt[-3].binstr->insertInt8(IMAGE_CEE_CS_CALLCONV_FIELD); mdToken mr = PASM->MakeMemberRef(yypvt[-2].token, yypvt[-0].string, yypvt[-3].binstr); PASM->SetMemberRefFixup(mr, PASM->OpcodeLen(yypvt[-4].instr)); PASM->EmitInstrI(yypvt[-4].instr,mr); PASM->m_tkCurrentCVOwner = mr; PASM->m_pCustomDescrList = NULL; } break; case 516: #line 1400 "asmparse.y" { yypvt[-1].binstr->insertInt8(IMAGE_CEE_CS_CALLCONV_FIELD); mdToken mr = PASM->MakeMemberRef(mdTokenNil, yypvt[-0].string, yypvt[-1].binstr); PASM->SetMemberRefFixup(mr, PASM->OpcodeLen(yypvt[-2].instr)); PASM->EmitInstrI(yypvt[-2].instr,mr); PASM->m_tkCurrentCVOwner = mr; PASM->m_pCustomDescrList = NULL; } break; case 517: #line 1407 "asmparse.y" { mdToken mr = yypvt[-0].token; PASM->SetMemberRefFixup(mr, PASM->OpcodeLen(yypvt[-1].instr)); PASM->EmitInstrI(yypvt[-1].instr,mr); PASM->m_tkCurrentCVOwner = mr; PASM->m_pCustomDescrList = NULL; } break; case 518: #line 1413 "asmparse.y" { mdToken mr = yypvt[-0].tdd->m_tkTypeSpec; PASM->SetMemberRefFixup(mr, PASM->OpcodeLen(yypvt[-1].instr)); PASM->EmitInstrI(yypvt[-1].instr,mr); PASM->m_tkCurrentCVOwner = mr; PASM->m_pCustomDescrList = NULL; } break; case 519: #line 1419 "asmparse.y" { mdToken mr = yypvt[-0].tdd->m_tkTypeSpec; PASM->SetMemberRefFixup(mr, PASM->OpcodeLen(yypvt[-1].instr)); PASM->EmitInstrI(yypvt[-1].instr,mr); PASM->m_tkCurrentCVOwner = mr; PASM->m_pCustomDescrList = NULL; } break; case 520: #line 1425 "asmparse.y" { PASM->EmitInstrI(yypvt[-1].instr, yypvt[-0].token); PASM->m_tkCurrentCVOwner = yypvt[-0].token; PASM->m_pCustomDescrList = NULL; } break; case 521: #line 1429 "asmparse.y" { PASM->EmitInstrStringLiteral(yypvt[-1].instr, yypvt[-0].binstr,TRUE); } break; case 522: #line 1431 "asmparse.y" { PASM->EmitInstrStringLiteral(yypvt[-4].instr, yypvt[-1].binstr,FALSE); } break; case 523: #line 1433 "asmparse.y" { PASM->EmitInstrStringLiteral(yypvt[-3].instr, yypvt[-1].binstr,FALSE,TRUE); } break; case 524: #line 1435 "asmparse.y" { PASM->EmitInstrSig(yypvt[-5].instr, parser->MakeSig(yypvt[-4].int32, yypvt[-3].binstr, yypvt[-1].binstr)); PASM->ResetArgNameList(); } break; case 525: #line 1439 "asmparse.y" { PASM->EmitInstrI(yypvt[-1].instr,yypvt[-0].token); PASM->m_tkCurrentCVOwner = yypvt[-0].token; PASM->m_pCustomDescrList = NULL; iOpcodeLen = 0; } break; case 526: #line 1444 "asmparse.y" { PASM->EmitInstrSwitch(yypvt[-3].instr, yypvt[-1].labels); } break; case 527: #line 1447 "asmparse.y" { yyval.labels = 0; } break; case 528: #line 1448 "asmparse.y" { yyval.labels = new Labels(yypvt[-2].string, yypvt[-0].labels, TRUE); } break; case 529: #line 1449 "asmparse.y" { yyval.labels = new Labels((char *)(UINT_PTR)yypvt[-2].int32, yypvt[-0].labels, FALSE); } break; case 530: #line 1450 "asmparse.y" { yyval.labels = new Labels(yypvt[-0].string, NULL, TRUE); } break; case 531: #line 1451 "asmparse.y" { yyval.labels = new Labels((char *)(UINT_PTR)yypvt[-0].int32, NULL, FALSE); } break; case 532: #line 1455 "asmparse.y" { yyval.binstr = NULL; } break; case 533: #line 1456 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; } break; case 534: #line 1459 "asmparse.y" { yyval.binstr = NULL; } break; case 535: #line 1460 "asmparse.y" { yyval.binstr = yypvt[-0].binstr; } break; case 536: #line 1463 "asmparse.y" { yyval.binstr = yypvt[-0].binstr; } break; case 537: #line 1464 "asmparse.y" { yyval.binstr = yypvt[-2].binstr; yyval.binstr->append(yypvt[-0].binstr); delete yypvt[-0].binstr; } break; case 538: #line 1468 "asmparse.y" { yyval.binstr = new BinStr(); } break; case 539: #line 1469 "asmparse.y" { yyval.binstr = yypvt[-0].binstr;} break; case 540: #line 1472 "asmparse.y" { yyval.binstr = yypvt[-0].binstr; } break; case 541: #line 1473 "asmparse.y" { yyval.binstr = yypvt[-2].binstr; yyval.binstr->append(yypvt[-0].binstr); delete yypvt[-0].binstr; } break; case 542: #line 1476 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_SENTINEL); } break; case 543: #line 1477 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->append(yypvt[-1].binstr); PASM->addArgName(NULL, yypvt[-1].binstr, yypvt[-0].binstr, yypvt[-2].int32); } break; case 544: #line 1478 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->append(yypvt[-2].binstr); PASM->addArgName(yypvt[-0].string, yypvt[-2].binstr, yypvt[-1].binstr, yypvt[-3].int32);} break; case 545: #line 1482 "asmparse.y" { yyval.token = PASM->ResolveClassRef(PASM->GetAsmRef(yypvt[-2].string), yypvt[-0].string, NULL); delete[] yypvt[-2].string;} break; case 546: #line 1483 "asmparse.y" { yyval.token = PASM->ResolveClassRef(yypvt[-2].token, yypvt[-0].string, NULL); } break; case 547: #line 1484 "asmparse.y" { yyval.token = PASM->ResolveClassRef(mdTokenNil, yypvt[-0].string, NULL); } break; case 548: #line 1485 "asmparse.y" { yyval.token = PASM->ResolveClassRef(PASM->GetModRef(yypvt[-2].string),yypvt[-0].string, NULL); delete[] yypvt[-2].string;} break; case 549: #line 1486 "asmparse.y" { yyval.token = PASM->ResolveClassRef(1,yypvt[-0].string,NULL); } break; case 550: #line 1487 "asmparse.y" { yyval.token = yypvt[-0].token; } break; case 551: #line 1488 "asmparse.y" { yyval.token = yypvt[-0].tdd->m_tkTypeSpec; } break; case 552: #line 1489 "asmparse.y" { if(PASM->m_pCurClass != NULL) yyval.token = PASM->m_pCurClass->m_cl; else { yyval.token = 0; PASM->report->error(".this outside class scope\n"); } } break; case 553: #line 1492 "asmparse.y" { if(PASM->m_pCurClass != NULL) { yyval.token = PASM->m_pCurClass->m_crExtends; if(RidFromToken(yyval.token) == 0) PASM->report->error(".base undefined\n"); } else { yyval.token = 0; PASM->report->error(".base outside class scope\n"); } } break; case 554: #line 1498 "asmparse.y" { if(PASM->m_pCurClass != NULL) { if(PASM->m_pCurClass->m_pEncloser != NULL) yyval.token = PASM->m_pCurClass->m_pEncloser->m_cl; else { yyval.token = 0; PASM->report->error(".nester undefined\n"); } } else { yyval.token = 0; PASM->report->error(".nester outside class scope\n"); } } break; case 555: #line 1505 "asmparse.y" { yyval.string = yypvt[-0].string; } break; case 556: #line 1506 "asmparse.y" { yyval.string = newStringWDel(yypvt[-2].string, NESTING_SEP, yypvt[-0].string); } break; case 557: #line 1509 "asmparse.y" { yyval.token = yypvt[-0].token;} break; case 558: #line 1510 "asmparse.y" { yyval.token = PASM->GetAsmRef(yypvt[-1].string); delete[] yypvt[-1].string;} break; case 559: #line 1511 "asmparse.y" { yyval.token = PASM->GetModRef(yypvt[-1].string); delete[] yypvt[-1].string;} break; case 560: #line 1512 "asmparse.y" { yyval.token = PASM->ResolveTypeSpec(yypvt[-0].binstr); } break; case 561: #line 1516 "asmparse.y" { yyval.binstr = new BinStr(); } break; case 562: #line 1518 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_CUSTOMMARSHALER); corEmitInt(yyval.binstr,yypvt[-7].binstr->length()); yyval.binstr->append(yypvt[-7].binstr); corEmitInt(yyval.binstr,yypvt[-5].binstr->length()); yyval.binstr->append(yypvt[-5].binstr); corEmitInt(yyval.binstr,yypvt[-3].binstr->length()); yyval.binstr->append(yypvt[-3].binstr); corEmitInt(yyval.binstr,yypvt[-1].binstr->length()); yyval.binstr->append(yypvt[-1].binstr); PASM->report->warn("Deprecated 4-string form of custom marshaler, first two strings ignored\n");} break; case 563: #line 1525 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_CUSTOMMARSHALER); corEmitInt(yyval.binstr,0); corEmitInt(yyval.binstr,0); corEmitInt(yyval.binstr,yypvt[-3].binstr->length()); yyval.binstr->append(yypvt[-3].binstr); corEmitInt(yyval.binstr,yypvt[-1].binstr->length()); yyval.binstr->append(yypvt[-1].binstr); } break; case 564: #line 1530 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_FIXEDSYSSTRING); corEmitInt(yyval.binstr,yypvt[-1].int32); } break; case 565: #line 1533 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_FIXEDARRAY); corEmitInt(yyval.binstr,yypvt[-2].int32); yyval.binstr->append(yypvt[-0].binstr); } break; case 566: #line 1535 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_VARIANT); PASM->report->warn("Deprecated native type 'variant'\n"); } break; case 567: #line 1537 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_CURRENCY); } break; case 568: #line 1538 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_SYSCHAR); PASM->report->warn("Deprecated native type 'syschar'\n"); } break; case 569: #line 1540 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_VOID); PASM->report->warn("Deprecated native type 'void'\n"); } break; case 570: #line 1542 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_BOOLEAN); } break; case 571: #line 1543 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_I1); } break; case 572: #line 1544 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_I2); } break; case 573: #line 1545 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_I4); } break; case 574: #line 1546 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_I8); } break; case 575: #line 1547 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_R4); } break; case 576: #line 1548 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_R8); } break; case 577: #line 1549 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_ERROR); } break; case 578: #line 1550 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_U1); } break; case 579: #line 1551 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_U2); } break; case 580: #line 1552 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_U4); } break; case 581: #line 1553 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_U8); } break; case 582: #line 1554 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_U1); } break; case 583: #line 1555 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_U2); } break; case 584: #line 1556 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_U4); } break; case 585: #line 1557 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_U8); } break; case 586: #line 1558 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->insertInt8(NATIVE_TYPE_PTR); PASM->report->warn("Deprecated native type '*'\n"); } break; case 587: #line 1560 "asmparse.y" { yyval.binstr = yypvt[-2].binstr; if(yyval.binstr->length()==0) yyval.binstr->appendInt8(NATIVE_TYPE_MAX); yyval.binstr->insertInt8(NATIVE_TYPE_ARRAY); } break; case 588: #line 1562 "asmparse.y" { yyval.binstr = yypvt[-3].binstr; if(yyval.binstr->length()==0) yyval.binstr->appendInt8(NATIVE_TYPE_MAX); yyval.binstr->insertInt8(NATIVE_TYPE_ARRAY); corEmitInt(yyval.binstr,0); corEmitInt(yyval.binstr,yypvt[-1].int32); corEmitInt(yyval.binstr,0); } break; case 589: #line 1567 "asmparse.y" { yyval.binstr = yypvt[-5].binstr; if(yyval.binstr->length()==0) yyval.binstr->appendInt8(NATIVE_TYPE_MAX); yyval.binstr->insertInt8(NATIVE_TYPE_ARRAY); corEmitInt(yyval.binstr,yypvt[-1].int32); corEmitInt(yyval.binstr,yypvt[-3].int32); corEmitInt(yyval.binstr,ntaSizeParamIndexSpecified); } break; case 590: #line 1572 "asmparse.y" { yyval.binstr = yypvt[-4].binstr; if(yyval.binstr->length()==0) yyval.binstr->appendInt8(NATIVE_TYPE_MAX); yyval.binstr->insertInt8(NATIVE_TYPE_ARRAY); corEmitInt(yyval.binstr,yypvt[-1].int32); } break; case 591: #line 1575 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_DECIMAL); PASM->report->warn("Deprecated native type 'decimal'\n"); } break; case 592: #line 1577 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_DATE); PASM->report->warn("Deprecated native type 'date'\n"); } break; case 593: #line 1579 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_BSTR); } break; case 594: #line 1580 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_LPSTR); } break; case 595: #line 1581 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_LPWSTR); } break; case 596: #line 1582 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_LPTSTR); } break; case 597: #line 1583 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_OBJECTREF); PASM->report->warn("Deprecated native type 'objectref'\n"); } break; case 598: #line 1585 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_IUNKNOWN); if(yypvt[-0].int32 != -1) corEmitInt(yyval.binstr,yypvt[-0].int32); } break; case 599: #line 1587 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_IDISPATCH); if(yypvt[-0].int32 != -1) corEmitInt(yyval.binstr,yypvt[-0].int32); } break; case 600: #line 1589 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_STRUCT); } break; case 601: #line 1590 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_INTF); if(yypvt[-0].int32 != -1) corEmitInt(yyval.binstr,yypvt[-0].int32); } break; case 602: #line 1592 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_SAFEARRAY); corEmitInt(yyval.binstr,yypvt[-0].int32); corEmitInt(yyval.binstr,0);} break; case 603: #line 1595 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_SAFEARRAY); corEmitInt(yyval.binstr,yypvt[-2].int32); corEmitInt(yyval.binstr,yypvt[-0].binstr->length()); yyval.binstr->append(yypvt[-0].binstr); } break; case 604: #line 1599 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_INT); } break; case 605: #line 1600 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_UINT); } break; case 606: #line 1601 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_UINT); } break; case 607: #line 1602 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_NESTEDSTRUCT); PASM->report->warn("Deprecated native type 'nested struct'\n"); } break; case 608: #line 1604 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_BYVALSTR); } break; case 609: #line 1605 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_ANSIBSTR); } break; case 610: #line 1606 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_TBSTR); } break; case 611: #line 1607 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_VARIANTBOOL); } break; case 612: #line 1608 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_FUNC); } break; case 613: #line 1609 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_ASANY); } break; case 614: #line 1610 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(NATIVE_TYPE_LPSTRUCT); } break; case 615: #line 1611 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->append(yypvt[-0].tdd->m_pbsTypeSpec); } break; case 616: #line 1614 "asmparse.y" { yyval.int32 = -1; } break; case 617: #line 1615 "asmparse.y" { yyval.int32 = yypvt[-1].int32; } break; case 618: #line 1618 "asmparse.y" { yyval.int32 = VT_EMPTY; } break; case 619: #line 1619 "asmparse.y" { yyval.int32 = VT_NULL; } break; case 620: #line 1620 "asmparse.y" { yyval.int32 = VT_VARIANT; } break; case 621: #line 1621 "asmparse.y" { yyval.int32 = VT_CY; } break; case 622: #line 1622 "asmparse.y" { yyval.int32 = VT_VOID; } break; case 623: #line 1623 "asmparse.y" { yyval.int32 = VT_BOOL; } break; case 624: #line 1624 "asmparse.y" { yyval.int32 = VT_I1; } break; case 625: #line 1625 "asmparse.y" { yyval.int32 = VT_I2; } break; case 626: #line 1626 "asmparse.y" { yyval.int32 = VT_I4; } break; case 627: #line 1627 "asmparse.y" { yyval.int32 = VT_I8; } break; case 628: #line 1628 "asmparse.y" { yyval.int32 = VT_R4; } break; case 629: #line 1629 "asmparse.y" { yyval.int32 = VT_R8; } break; case 630: #line 1630 "asmparse.y" { yyval.int32 = VT_UI1; } break; case 631: #line 1631 "asmparse.y" { yyval.int32 = VT_UI2; } break; case 632: #line 1632 "asmparse.y" { yyval.int32 = VT_UI4; } break; case 633: #line 1633 "asmparse.y" { yyval.int32 = VT_UI8; } break; case 634: #line 1634 "asmparse.y" { yyval.int32 = VT_UI1; } break; case 635: #line 1635 "asmparse.y" { yyval.int32 = VT_UI2; } break; case 636: #line 1636 "asmparse.y" { yyval.int32 = VT_UI4; } break; case 637: #line 1637 "asmparse.y" { yyval.int32 = VT_UI8; } break; case 638: #line 1638 "asmparse.y" { yyval.int32 = VT_PTR; } break; case 639: #line 1639 "asmparse.y" { yyval.int32 = yypvt[-2].int32 | VT_ARRAY; } break; case 640: #line 1640 "asmparse.y" { yyval.int32 = yypvt[-1].int32 | VT_VECTOR; } break; case 641: #line 1641 "asmparse.y" { yyval.int32 = yypvt[-1].int32 | VT_BYREF; } break; case 642: #line 1642 "asmparse.y" { yyval.int32 = VT_DECIMAL; } break; case 643: #line 1643 "asmparse.y" { yyval.int32 = VT_DATE; } break; case 644: #line 1644 "asmparse.y" { yyval.int32 = VT_BSTR; } break; case 645: #line 1645 "asmparse.y" { yyval.int32 = VT_LPSTR; } break; case 646: #line 1646 "asmparse.y" { yyval.int32 = VT_LPWSTR; } break; case 647: #line 1647 "asmparse.y" { yyval.int32 = VT_UNKNOWN; } break; case 648: #line 1648 "asmparse.y" { yyval.int32 = VT_DISPATCH; } break; case 649: #line 1649 "asmparse.y" { yyval.int32 = VT_SAFEARRAY; } break; case 650: #line 1650 "asmparse.y" { yyval.int32 = VT_INT; } break; case 651: #line 1651 "asmparse.y" { yyval.int32 = VT_UINT; } break; case 652: #line 1652 "asmparse.y" { yyval.int32 = VT_UINT; } break; case 653: #line 1653 "asmparse.y" { yyval.int32 = VT_ERROR; } break; case 654: #line 1654 "asmparse.y" { yyval.int32 = VT_HRESULT; } break; case 655: #line 1655 "asmparse.y" { yyval.int32 = VT_CARRAY; } break; case 656: #line 1656 "asmparse.y" { yyval.int32 = VT_USERDEFINED; } break; case 657: #line 1657 "asmparse.y" { yyval.int32 = VT_RECORD; } break; case 658: #line 1658 "asmparse.y" { yyval.int32 = VT_FILETIME; } break; case 659: #line 1659 "asmparse.y" { yyval.int32 = VT_BLOB; } break; case 660: #line 1660 "asmparse.y" { yyval.int32 = VT_STREAM; } break; case 661: #line 1661 "asmparse.y" { yyval.int32 = VT_STORAGE; } break; case 662: #line 1662 "asmparse.y" { yyval.int32 = VT_STREAMED_OBJECT; } break; case 663: #line 1663 "asmparse.y" { yyval.int32 = VT_STORED_OBJECT; } break; case 664: #line 1664 "asmparse.y" { yyval.int32 = VT_BLOB_OBJECT; } break; case 665: #line 1665 "asmparse.y" { yyval.int32 = VT_CF; } break; case 666: #line 1666 "asmparse.y" { yyval.int32 = VT_CLSID; } break; case 667: #line 1670 "asmparse.y" { if(yypvt[-0].token == PASM->m_tkSysString) { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_STRING); } else if(yypvt[-0].token == PASM->m_tkSysObject) { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_OBJECT); } else yyval.binstr = parser->MakeTypeClass(ELEMENT_TYPE_CLASS, yypvt[-0].token); } break; case 668: #line 1676 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_OBJECT); } break; case 669: #line 1677 "asmparse.y" { yyval.binstr = parser->MakeTypeClass(ELEMENT_TYPE_VALUETYPE, yypvt[-0].token); } break; case 670: #line 1678 "asmparse.y" { yyval.binstr = parser->MakeTypeClass(ELEMENT_TYPE_VALUETYPE, yypvt[-0].token); } break; case 671: #line 1679 "asmparse.y" { yyval.binstr = yypvt[-2].binstr; yyval.binstr->insertInt8(ELEMENT_TYPE_SZARRAY); } break; case 672: #line 1680 "asmparse.y" { yyval.binstr = parser->MakeTypeArray(ELEMENT_TYPE_ARRAY, yypvt[-3].binstr, yypvt[-1].binstr); } break; case 673: #line 1681 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->insertInt8(ELEMENT_TYPE_BYREF); } break; case 674: #line 1682 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->insertInt8(ELEMENT_TYPE_PTR); } break; case 675: #line 1683 "asmparse.y" { yyval.binstr = yypvt[-1].binstr; yyval.binstr->insertInt8(ELEMENT_TYPE_PINNED); } break; case 676: #line 1684 "asmparse.y" { yyval.binstr = parser->MakeTypeClass(ELEMENT_TYPE_CMOD_REQD, yypvt[-1].token); yyval.binstr->append(yypvt[-4].binstr); } break; case 677: #line 1686 "asmparse.y" { yyval.binstr = parser->MakeTypeClass(ELEMENT_TYPE_CMOD_OPT, yypvt[-1].token); yyval.binstr->append(yypvt[-4].binstr); } break; case 678: #line 1689 "asmparse.y" { yyval.binstr = parser->MakeSig(yypvt[-5].int32, yypvt[-4].binstr, yypvt[-1].binstr); yyval.binstr->insertInt8(ELEMENT_TYPE_FNPTR); PASM->delArgNameList(PASM->m_firstArgName); PASM->m_firstArgName = parser->m_ANSFirst.POP(); PASM->m_lastArgName = parser->m_ANSLast.POP(); } break; case 679: #line 1695 "asmparse.y" { if(yypvt[-1].binstr == NULL) yyval.binstr = yypvt[-3].binstr; else { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_GENERICINST); yyval.binstr->append(yypvt[-3].binstr); corEmitInt(yyval.binstr, corCountArgs(yypvt[-1].binstr)); yyval.binstr->append(yypvt[-1].binstr); delete yypvt[-3].binstr; delete yypvt[-1].binstr; }} break; case 680: #line 1702 "asmparse.y" { //if(PASM->m_pCurMethod) { // if(($3 < 0)||((DWORD)$3 >= PASM->m_pCurMethod->m_NumTyPars)) // PASM->report->error("Invalid method type parameter '%d'\n",$3); yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_MVAR); corEmitInt(yyval.binstr, yypvt[-0].int32); //} else PASM->report->error("Method type parameter '%d' outside method scope\n",$3); } break; case 681: #line 1708 "asmparse.y" { //if(PASM->m_pCurClass) { // if(($2 < 0)||((DWORD)$2 >= PASM->m_pCurClass->m_NumTyPars)) // PASM->report->error("Invalid type parameter '%d'\n",$2); yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_VAR); corEmitInt(yyval.binstr, yypvt[-0].int32); //} else PASM->report->error("Type parameter '%d' outside class scope\n",$2); } break; case 682: #line 1714 "asmparse.y" { int eltype = ELEMENT_TYPE_MVAR; int n=-1; if(PASM->m_pCurMethod) n = PASM->m_pCurMethod->FindTyPar(yypvt[-0].string); else { if(PASM->m_TyParList) n = PASM->m_TyParList->IndexOf(yypvt[-0].string); if(n == -1) { n = TyParFixupList.COUNT(); TyParFixupList.PUSH(yypvt[-0].string); eltype = ELEMENT_TYPE_MVARFIXUP; } } if(n == -1) { PASM->report->error("Invalid method type parameter '%s'\n",yypvt[-0].string); n = 0x1FFFFFFF; } yyval.binstr = new BinStr(); yyval.binstr->appendInt8(eltype); corEmitInt(yyval.binstr,n); } break; case 683: #line 1729 "asmparse.y" { int eltype = ELEMENT_TYPE_VAR; int n=-1; if(PASM->m_pCurClass && !newclass) n = PASM->m_pCurClass->FindTyPar(yypvt[-0].string); else { if(PASM->m_TyParList) n = PASM->m_TyParList->IndexOf(yypvt[-0].string); if(n == -1) { n = TyParFixupList.COUNT(); TyParFixupList.PUSH(yypvt[-0].string); eltype = ELEMENT_TYPE_VARFIXUP; } } if(n == -1) { PASM->report->error("Invalid type parameter '%s'\n",yypvt[-0].string); n = 0x1FFFFFFF; } yyval.binstr = new BinStr(); yyval.binstr->appendInt8(eltype); corEmitInt(yyval.binstr,n); } break; case 684: #line 1744 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_TYPEDBYREF); } break; case 685: #line 1745 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_VOID); } break; case 686: #line 1746 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_I); } break; case 687: #line 1747 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_U); } break; case 688: #line 1748 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_U); } break; case 689: #line 1749 "asmparse.y" { yyval.binstr = yypvt[-0].binstr; } break; case 690: #line 1750 "asmparse.y" { yyval.binstr = yypvt[-0].binstr; yyval.binstr->insertInt8(ELEMENT_TYPE_SENTINEL); } break; case 691: #line 1753 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_CHAR); } break; case 692: #line 1754 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_STRING); } break; case 693: #line 1755 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_BOOLEAN); } break; case 694: #line 1756 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_I1); } break; case 695: #line 1757 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_I2); } break; case 696: #line 1758 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_I4); } break; case 697: #line 1759 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_I8); } break; case 698: #line 1760 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_R4); } break; case 699: #line 1761 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_R8); } break; case 700: #line 1762 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_U1); } break; case 701: #line 1763 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_U2); } break; case 702: #line 1764 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_U4); } break; case 703: #line 1765 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_U8); } break; case 704: #line 1766 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_U1); } break; case 705: #line 1767 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_U2); } break; case 706: #line 1768 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_U4); } break; case 707: #line 1769 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(ELEMENT_TYPE_U8); } break; case 708: #line 1770 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->append(yypvt[-0].tdd->m_pbsTypeSpec); } break; case 709: #line 1773 "asmparse.y" { yyval.binstr = yypvt[-0].binstr; } break; case 710: #line 1774 "asmparse.y" { yyval.binstr = yypvt[-2].binstr; yypvt[-2].binstr->append(yypvt[-0].binstr); delete yypvt[-0].binstr; } break; case 711: #line 1777 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt32(0x7FFFFFFF); yyval.binstr->appendInt32(0x7FFFFFFF); } break; case 712: #line 1778 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt32(0x7FFFFFFF); yyval.binstr->appendInt32(0x7FFFFFFF); } break; case 713: #line 1779 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt32(0); yyval.binstr->appendInt32(yypvt[-0].int32); } break; case 714: #line 1780 "asmparse.y" { FAIL_UNLESS(yypvt[-2].int32 <= yypvt[-0].int32, ("lower bound %d must be <= upper bound %d\n", yypvt[-2].int32, yypvt[-0].int32)); if (yypvt[-2].int32 > yypvt[-0].int32) { YYERROR; }; yyval.binstr = new BinStr(); yyval.binstr->appendInt32(yypvt[-2].int32); yyval.binstr->appendInt32(yypvt[-0].int32-yypvt[-2].int32+1); } break; case 715: #line 1783 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt32(yypvt[-1].int32); yyval.binstr->appendInt32(0x7FFFFFFF); } break; case 716: #line 1788 "asmparse.y" { PASM->AddPermissionDecl(yypvt[-4].secAct, yypvt[-3].token, yypvt[-1].pair); } break; case 717: #line 1790 "asmparse.y" { PASM->AddPermissionDecl(yypvt[-5].secAct, yypvt[-4].token, yypvt[-1].binstr); } break; case 718: #line 1791 "asmparse.y" { PASM->AddPermissionDecl(yypvt[-1].secAct, yypvt[-0].token, (NVPair *)NULL); } break; case 719: #line 1792 "asmparse.y" { PASM->AddPermissionSetDecl(yypvt[-2].secAct, yypvt[-1].binstr); } break; case 720: #line 1794 "asmparse.y" { PASM->AddPermissionSetDecl(yypvt[-1].secAct,BinStrToUnicode(yypvt[-0].binstr,true));} break; case 721: #line 1796 "asmparse.y" { BinStr* ret = new BinStr(); ret->insertInt8('.'); corEmitInt(ret, nSecAttrBlobs); ret->append(yypvt[-1].binstr); PASM->AddPermissionSetDecl(yypvt[-4].secAct,ret); nSecAttrBlobs = 0; } break; case 722: #line 1804 "asmparse.y" { yyval.binstr = new BinStr(); nSecAttrBlobs = 0;} break; case 723: #line 1805 "asmparse.y" { yyval.binstr = yypvt[-0].binstr; nSecAttrBlobs = 1; } break; case 724: #line 1806 "asmparse.y" { yyval.binstr = yypvt[-2].binstr; yyval.binstr->append(yypvt[-0].binstr); nSecAttrBlobs++; } break; case 725: #line 1810 "asmparse.y" { yyval.binstr = PASM->EncodeSecAttr(PASM->ReflectionNotation(yypvt[-4].token),yypvt[-1].binstr,nCustomBlobNVPairs); nCustomBlobNVPairs = 0; } break; case 726: #line 1813 "asmparse.y" { yyval.binstr = PASM->EncodeSecAttr(yypvt[-4].string,yypvt[-1].binstr,nCustomBlobNVPairs); nCustomBlobNVPairs = 0; } break; case 727: #line 1817 "asmparse.y" { yyval.secAct = yypvt[-2].secAct; bParsingByteArray = TRUE; } break; case 728: #line 1819 "asmparse.y" { yyval.secAct = yypvt[-2].secAct; bParsingByteArray = TRUE; } break; case 729: #line 1822 "asmparse.y" { yyval.pair = yypvt[-0].pair; } break; case 730: #line 1823 "asmparse.y" { yyval.pair = yypvt[-2].pair->Concat(yypvt[-0].pair); } break; case 731: #line 1826 "asmparse.y" { yypvt[-2].binstr->appendInt8(0); yyval.pair = new NVPair(yypvt[-2].binstr, yypvt[-0].binstr); } break; case 732: #line 1829 "asmparse.y" { yyval.int32 = 1; } break; case 733: #line 1830 "asmparse.y" { yyval.int32 = 0; } break; case 734: #line 1833 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(SERIALIZATION_TYPE_BOOLEAN); yyval.binstr->appendInt8(yypvt[-0].int32); } break; case 735: #line 1836 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(SERIALIZATION_TYPE_I4); yyval.binstr->appendInt32(yypvt[-0].int32); } break; case 736: #line 1839 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(SERIALIZATION_TYPE_I4); yyval.binstr->appendInt32(yypvt[-1].int32); } break; case 737: #line 1842 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(SERIALIZATION_TYPE_STRING); yyval.binstr->append(yypvt[-0].binstr); delete yypvt[-0].binstr; yyval.binstr->appendInt8(0); } break; case 738: #line 1846 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(SERIALIZATION_TYPE_ENUM); char* sz = PASM->ReflectionNotation(yypvt[-5].token); strcpy_s((char *)yyval.binstr->getBuff((unsigned)strlen(sz) + 1), strlen(sz) + 1,sz); yyval.binstr->appendInt8(1); yyval.binstr->appendInt32(yypvt[-1].int32); } break; case 739: #line 1852 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(SERIALIZATION_TYPE_ENUM); char* sz = PASM->ReflectionNotation(yypvt[-5].token); strcpy_s((char *)yyval.binstr->getBuff((unsigned)strlen(sz) + 1), strlen(sz) + 1,sz); yyval.binstr->appendInt8(2); yyval.binstr->appendInt32(yypvt[-1].int32); } break; case 740: #line 1858 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(SERIALIZATION_TYPE_ENUM); char* sz = PASM->ReflectionNotation(yypvt[-5].token); strcpy_s((char *)yyval.binstr->getBuff((unsigned)strlen(sz) + 1), strlen(sz) + 1,sz); yyval.binstr->appendInt8(4); yyval.binstr->appendInt32(yypvt[-1].int32); } break; case 741: #line 1864 "asmparse.y" { yyval.binstr = new BinStr(); yyval.binstr->appendInt8(SERIALIZATION_TYPE_ENUM); char* sz = PASM->ReflectionNotation(yypvt[-3].token); strcpy_s((char *)yyval.binstr->getBuff((unsigned)strlen(sz) + 1), strlen(sz) + 1,sz); yyval.binstr->appendInt8(4); yyval.binstr->appendInt32(yypvt[-1].int32); } break; case 742: #line 1872 "asmparse.y" { yyval.secAct = dclRequest; } break; case 743: #line 1873 "asmparse.y" { yyval.secAct = dclDemand; } break; case 744: #line 1874 "asmparse.y" { yyval.secAct = dclAssert; } break; case 745: #line 1875 "asmparse.y" { yyval.secAct = dclDeny; } break; case 746: #line 1876 "asmparse.y" { yyval.secAct = dclPermitOnly; } break; case 747: #line 1877 "asmparse.y" { yyval.secAct = dclLinktimeCheck; } break; case 748: #line 1878 "asmparse.y" { yyval.secAct = dclInheritanceCheck; } break; case 749: #line 1879 "asmparse.y" { yyval.secAct = dclRequestMinimum; } break; case 750: #line 1880 "asmparse.y" { yyval.secAct = dclRequestOptional; } break; case 751: #line 1881 "asmparse.y" { yyval.secAct = dclRequestRefuse; } break; case 752: #line 1882 "asmparse.y" { yyval.secAct = dclPrejitGrant; } break; case 753: #line 1883 "asmparse.y" { yyval.secAct = dclPrejitDenied; } break; case 754: #line 1884 "asmparse.y" { yyval.secAct = dclNonCasDemand; } break; case 755: #line 1885 "asmparse.y" { yyval.secAct = dclNonCasLinkDemand; } break; case 756: #line 1886 "asmparse.y" { yyval.secAct = dclNonCasInheritance; } break; case 757: #line 1890 "asmparse.y" { PASM->ResetLineNumbers(); nCurrPC = PASM->m_CurPC; PENV->bExternSource = TRUE; PENV->bExternSourceAutoincrement = FALSE; } break; case 758: #line 1891 "asmparse.y" { PASM->ResetLineNumbers(); nCurrPC = PASM->m_CurPC; PENV->bExternSource = TRUE; PENV->bExternSourceAutoincrement = TRUE; } break; case 759: #line 1894 "asmparse.y" { PENV->nExtLine = PENV->nExtLineEnd = yypvt[-1].int32; PENV->nExtCol = 0; PENV->nExtColEnd = static_cast<unsigned>(-1); PASM->SetSourceFileName(yypvt[-0].string);} break; case 760: #line 1897 "asmparse.y" { PENV->nExtLine = PENV->nExtLineEnd = yypvt[-0].int32; PENV->nExtCol = 0; PENV->nExtColEnd = static_cast<unsigned>(-1); } break; case 761: #line 1899 "asmparse.y" { PENV->nExtLine = PENV->nExtLineEnd = yypvt[-3].int32; PENV->nExtCol=yypvt[-1].int32; PENV->nExtColEnd = static_cast<unsigned>(-1); PASM->SetSourceFileName(yypvt[-0].string);} break; case 762: #line 1902 "asmparse.y" { PENV->nExtLine = PENV->nExtLineEnd = yypvt[-2].int32; PENV->nExtCol=yypvt[-0].int32; PENV->nExtColEnd = static_cast<unsigned>(-1);} break; case 763: #line 1905 "asmparse.y" { PENV->nExtLine = PENV->nExtLineEnd = yypvt[-5].int32; PENV->nExtCol=yypvt[-3].int32; PENV->nExtColEnd = yypvt[-1].int32; PASM->SetSourceFileName(yypvt[-0].string);} break; case 764: #line 1909 "asmparse.y" { PENV->nExtLine = PENV->nExtLineEnd = yypvt[-4].int32; PENV->nExtCol=yypvt[-2].int32; PENV->nExtColEnd = yypvt[-0].int32; } break; case 765: #line 1912 "asmparse.y" { PENV->nExtLine = yypvt[-5].int32; PENV->nExtLineEnd = yypvt[-3].int32; PENV->nExtCol=yypvt[-1].int32; PENV->nExtColEnd = static_cast<unsigned>(-1); PASM->SetSourceFileName(yypvt[-0].string);} break; case 766: #line 1916 "asmparse.y" { PENV->nExtLine = yypvt[-4].int32; PENV->nExtLineEnd = yypvt[-2].int32; PENV->nExtCol=yypvt[-0].int32; PENV->nExtColEnd = static_cast<unsigned>(-1); } break; case 767: #line 1919 "asmparse.y" { PENV->nExtLine = yypvt[-7].int32; PENV->nExtLineEnd = yypvt[-5].int32; PENV->nExtCol=yypvt[-3].int32; PENV->nExtColEnd = yypvt[-1].int32; PASM->SetSourceFileName(yypvt[-0].string);} break; case 768: #line 1923 "asmparse.y" { PENV->nExtLine = yypvt[-6].int32; PENV->nExtLineEnd = yypvt[-4].int32; PENV->nExtCol=yypvt[-2].int32; PENV->nExtColEnd = yypvt[-0].int32; } break; case 769: #line 1925 "asmparse.y" { PENV->nExtLine = PENV->nExtLineEnd = yypvt[-1].int32 - 1; PENV->nExtCol = 0; PENV->nExtColEnd = static_cast<unsigned>(-1); PASM->SetSourceFileName(yypvt[-0].binstr);} break; case 770: #line 1932 "asmparse.y" { PASMM->AddFile(yypvt[-5].string, yypvt[-6].fileAttr|yypvt[-4].fileAttr|yypvt[-0].fileAttr, yypvt[-2].binstr); } break; case 771: #line 1933 "asmparse.y" { PASMM->AddFile(yypvt[-1].string, yypvt[-2].fileAttr|yypvt[-0].fileAttr, NULL); } break; case 772: #line 1936 "asmparse.y" { yyval.fileAttr = (CorFileFlags) 0; } break; case 773: #line 1937 "asmparse.y" { yyval.fileAttr = (CorFileFlags) (yypvt[-1].fileAttr | ffContainsNoMetaData); } break; case 774: #line 1940 "asmparse.y" { yyval.fileAttr = (CorFileFlags) 0; } break; case 775: #line 1941 "asmparse.y" { yyval.fileAttr = (CorFileFlags) 0x80000000; } break; case 776: #line 1944 "asmparse.y" { bParsingByteArray = TRUE; } break; case 777: #line 1947 "asmparse.y" { PASMM->StartAssembly(yypvt[-0].string, NULL, (DWORD)yypvt[-1].asmAttr, FALSE); } break; case 778: #line 1950 "asmparse.y" { yyval.asmAttr = (CorAssemblyFlags) 0; } break; case 779: #line 1951 "asmparse.y" { yyval.asmAttr = (CorAssemblyFlags) (yypvt[-1].asmAttr | afRetargetable); } break; case 780: #line 1952 "asmparse.y" { yyval.asmAttr = (CorAssemblyFlags) (yypvt[-1].asmAttr | afContentType_WindowsRuntime); } break; case 781: #line 1953 "asmparse.y" { yyval.asmAttr = (CorAssemblyFlags) (yypvt[-1].asmAttr | afPA_NoPlatform); } break; case 782: #line 1954 "asmparse.y" { yyval.asmAttr = yypvt[-2].asmAttr; } break; case 783: #line 1955 "asmparse.y" { SET_PA(yyval.asmAttr,yypvt[-1].asmAttr,afPA_MSIL); } break; case 784: #line 1956 "asmparse.y" { SET_PA(yyval.asmAttr,yypvt[-1].asmAttr,afPA_x86); } break; case 785: #line 1957 "asmparse.y" { SET_PA(yyval.asmAttr,yypvt[-1].asmAttr,afPA_AMD64); } break; case 786: #line 1958 "asmparse.y" { SET_PA(yyval.asmAttr,yypvt[-1].asmAttr,afPA_ARM); } break; case 787: #line 1959 "asmparse.y" { SET_PA(yyval.asmAttr,yypvt[-1].asmAttr,afPA_ARM64); } break; case 790: #line 1966 "asmparse.y" { PASMM->SetAssemblyHashAlg(yypvt[-0].int32); } break; case 793: #line 1971 "asmparse.y" { yyval.int32 = yypvt[-0].int32; } break; case 794: #line 1972 "asmparse.y" { yyval.int32 = 0xFFFF; } break; case 795: #line 1975 "asmparse.y" { PASMM->SetAssemblyPublicKey(yypvt[-1].binstr); } break; case 796: #line 1977 "asmparse.y" { PASMM->SetAssemblyVer((USHORT)yypvt[-6].int32, (USHORT)yypvt[-4].int32, (USHORT)yypvt[-2].int32, (USHORT)yypvt[-0].int32); } break; case 797: #line 1978 "asmparse.y" { yypvt[-0].binstr->appendInt8(0); PASMM->SetAssemblyLocale(yypvt[-0].binstr,TRUE); } break; case 798: #line 1979 "asmparse.y" { PASMM->SetAssemblyLocale(yypvt[-1].binstr,FALSE); } break; case 801: #line 1984 "asmparse.y" { bParsingByteArray = TRUE; } break; case 802: #line 1987 "asmparse.y" { bParsingByteArray = TRUE; } break; case 803: #line 1990 "asmparse.y" { bParsingByteArray = TRUE; } break; case 804: #line 1994 "asmparse.y" { PASMM->StartAssembly(yypvt[-0].string, NULL, yypvt[-1].asmAttr, TRUE); } break; case 805: #line 1996 "asmparse.y" { PASMM->StartAssembly(yypvt[-2].string, yypvt[-0].string, yypvt[-3].asmAttr, TRUE); } break; case 808: #line 2003 "asmparse.y" { PASMM->SetAssemblyHashBlob(yypvt[-1].binstr); } break; case 810: #line 2005 "asmparse.y" { PASMM->SetAssemblyPublicKeyToken(yypvt[-1].binstr); } break; case 811: #line 2006 "asmparse.y" { PASMM->SetAssemblyAutodetect(); } break; case 812: #line 2009 "asmparse.y" { PASMM->StartComType(yypvt[-0].string, yypvt[-1].exptAttr);} break; case 813: #line 2012 "asmparse.y" { PASMM->StartComType(yypvt[-0].string, yypvt[-1].exptAttr); } break; case 814: #line 2015 "asmparse.y" { yyval.exptAttr = (CorTypeAttr) 0; } break; case 815: #line 2016 "asmparse.y" { yyval.exptAttr = (CorTypeAttr) (yypvt[-1].exptAttr | tdNotPublic); } break; case 816: #line 2017 "asmparse.y" { yyval.exptAttr = (CorTypeAttr) (yypvt[-1].exptAttr | tdPublic); } break; case 817: #line 2018 "asmparse.y" { yyval.exptAttr = (CorTypeAttr) (yypvt[-1].exptAttr | tdForwarder); } break; case 818: #line 2019 "asmparse.y" { yyval.exptAttr = (CorTypeAttr) (yypvt[-2].exptAttr | tdNestedPublic); } break; case 819: #line 2020 "asmparse.y" { yyval.exptAttr = (CorTypeAttr) (yypvt[-2].exptAttr | tdNestedPrivate); } break; case 820: #line 2021 "asmparse.y" { yyval.exptAttr = (CorTypeAttr) (yypvt[-2].exptAttr | tdNestedFamily); } break; case 821: #line 2022 "asmparse.y" { yyval.exptAttr = (CorTypeAttr) (yypvt[-2].exptAttr | tdNestedAssembly); } break; case 822: #line 2023 "asmparse.y" { yyval.exptAttr = (CorTypeAttr) (yypvt[-2].exptAttr | tdNestedFamANDAssem); } break; case 823: #line 2024 "asmparse.y" { yyval.exptAttr = (CorTypeAttr) (yypvt[-2].exptAttr | tdNestedFamORAssem); } break; case 826: #line 2031 "asmparse.y" { PASMM->SetComTypeFile(yypvt[-0].string); } break; case 827: #line 2032 "asmparse.y" { PASMM->SetComTypeComType(yypvt[-0].string); } break; case 828: #line 2033 "asmparse.y" { PASMM->SetComTypeAsmRef(yypvt[-0].string); } break; case 829: #line 2034 "asmparse.y" { if(!PASMM->SetComTypeImplementationTok(yypvt[-1].int32)) PASM->report->error("Invalid implementation of exported type\n"); } break; case 830: #line 2036 "asmparse.y" { if(!PASMM->SetComTypeClassTok(yypvt[-0].int32)) PASM->report->error("Invalid TypeDefID of exported type\n"); } break; case 833: #line 2042 "asmparse.y" { PASMM->StartManifestRes(yypvt[-0].string, yypvt[-0].string, yypvt[-1].manresAttr); } break; case 834: #line 2044 "asmparse.y" { PASMM->StartManifestRes(yypvt[-2].string, yypvt[-0].string, yypvt[-3].manresAttr); } break; case 835: #line 2047 "asmparse.y" { yyval.manresAttr = (CorManifestResourceFlags) 0; } break; case 836: #line 2048 "asmparse.y" { yyval.manresAttr = (CorManifestResourceFlags) (yypvt[-1].manresAttr | mrPublic); } break; case 837: #line 2049 "asmparse.y" { yyval.manresAttr = (CorManifestResourceFlags) (yypvt[-1].manresAttr | mrPrivate); } break; case 840: #line 2056 "asmparse.y" { PASMM->SetManifestResFile(yypvt[-2].string, (ULONG)yypvt[-0].int32); } break; case 841: #line 2057 "asmparse.y" { PASMM->SetManifestResAsmRef(yypvt[-0].string); } break;/* End of actions */ #line 329 "F:\\NetFXDev1\\src\\tools\\devdiv\\amd64\\yypars.c" } } goto yystack; /* stack new state and value */ } #pragma warning(default:102) #ifdef YYDUMP YYLOCAL void YYNEAR YYPASCAL yydumpinfo(void) { short stackindex; short valindex; //dump yys printf("short yys[%d] {\n", YYMAXDEPTH); for (stackindex = 0; stackindex < YYMAXDEPTH; stackindex++){ if (stackindex) printf(", %s", stackindex % 10 ? "\0" : "\n"); printf("%6d", yys[stackindex]); } printf("\n};\n"); //dump yyv printf("YYSTYPE yyv[%d] {\n", YYMAXDEPTH); for (valindex = 0; valindex < YYMAXDEPTH; valindex++){ if (valindex) printf(", %s", valindex % 5 ? "\0" : "\n"); printf("%#*x", 3+sizeof(YYSTYPE), yyv[valindex]); } printf("\n};\n"); } #endif
-1
dotnet/runtime
66,474
Update repo CMake configuration to target /W4 by default
Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
AaronRobinsonMSFT
2022-03-10T20:20:31Z
2022-03-11T04:59:21Z
ba5207b0f4054fe8963fc3e87c2bd32907516961
5ce2b9f860f7a84c3059650bb67817d59d8f4953
Update repo CMake configuration to target /W4 by default. Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
./src/mono/dlls/mscordbi/cordb-frame.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // File: CORDB-FRAME.CPP // #include <cordb-code.h> #include <cordb-frame.h> #include <cordb-function.h> #include <cordb-process.h> #include <cordb-register.h> #include <cordb-thread.h> #include <cordb-value.h> using namespace std; CordbFrameEnum::CordbFrameEnum(Connection* conn, CordbThread* thread) : CordbBaseMono(conn) { this->m_pThread = thread; m_nFrames = 0; m_ppFrames = NULL; } CordbFrameEnum::~CordbFrameEnum() { Reset(); } HRESULT STDMETHODCALLTYPE CordbFrameEnum::Next(ULONG celt, ICorDebugFrame* frames[], ULONG* pceltFetched) { GetCount(); for (int i = 0; i < m_nFrames; i++) { this->m_ppFrames[i]->QueryInterface(IID_ICorDebugFrame, (void**)&frames[i]); } LOG((LF_CORDB, LL_INFO1000000, "CordbFrameEnum - Next - IMPLEMENTED\n")); return S_OK; } HRESULT STDMETHODCALLTYPE CordbFrameEnum::Skip(ULONG celt) { LOG((LF_CORDB, LL_INFO100000, "CordbFrameEnum - Skip - NOT IMPLEMENTED\n")); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CordbFrameEnum::Reset(void) { for (int i = 0; i < m_nFrames; i++) { this->m_ppFrames[i]->InternalRelease(); } m_nFrames = 0; if (m_ppFrames) free(m_ppFrames); m_ppFrames = NULL; return S_OK; } HRESULT STDMETHODCALLTYPE CordbFrameEnum::Clone(ICorDebugEnum** ppEnum) { LOG((LF_CORDB, LL_INFO100000, "CordbFrameEnum - Clone - NOT IMPLEMENTED\n")); return E_NOTIMPL; } HRESULT CordbFrameEnum::GetCount() { HRESULT hr = S_OK; if (m_nFrames != 0) return hr; EX_TRY { Reset(); MdbgProtBuffer localbuf; m_dbgprot_buffer_init(&localbuf, 128); m_dbgprot_buffer_add_id(&localbuf, m_pThread->GetThreadId()); m_dbgprot_buffer_add_int(&localbuf, 0); m_dbgprot_buffer_add_int(&localbuf, -1); int cmdId = conn->SendEvent(MDBGPROT_CMD_SET_THREAD, MDBGPROT_CMD_THREAD_GET_FRAME_INFO, &localbuf); m_dbgprot_buffer_free(&localbuf); ReceivedReplyPacket* received_reply_packet = conn->GetReplyWithError(cmdId); CHECK_ERROR_RETURN_FALSE(received_reply_packet); MdbgProtBuffer* pReply = received_reply_packet->Buffer(); m_nFrames = m_dbgprot_decode_int(pReply->p, &pReply->p, pReply->end); m_ppFrames = (CordbNativeFrame**)malloc(sizeof(CordbNativeFrame*) * m_nFrames); for (int i = 0; i < m_nFrames; i++) { int frameid = m_dbgprot_decode_int(pReply->p, &pReply->p, pReply->end); int methodId = m_dbgprot_decode_id(pReply->p, &pReply->p, pReply->end); int il_offset = m_dbgprot_decode_int(pReply->p, &pReply->p, pReply->end); int flags = m_dbgprot_decode_byte(pReply->p, &pReply->p, pReply->end); CordbNativeFrame* frame = new CordbNativeFrame(conn, frameid, methodId, il_offset, flags, m_pThread, i); frame->InternalAddRef(); m_ppFrames[i] = frame; } } EX_CATCH_HRESULT(hr); return hr; } HRESULT STDMETHODCALLTYPE CordbFrameEnum::GetCount(ULONG* pcelt) { LOG((LF_CORDB, LL_INFO1000000, "CordbFrameEnum - GetCount - IMPLEMENTED\n")); HRESULT hr = S_OK; hr = GetCount(); *pcelt = m_nFrames; return hr; } HRESULT STDMETHODCALLTYPE CordbFrameEnum::QueryInterface(REFIID riid, void** ppvObject) { LOG((LF_CORDB, LL_INFO100000, "CordbFrameEnum - QueryInterface - NOT IMPLEMENTED\n")); return E_NOTIMPL; } CordbJITILFrame::CordbJITILFrame( Connection* conn, int frameid, int methodId, int il_offset, int flags, CordbThread* thread) : CordbBaseMono(conn) { this->m_debuggerFrameId = frameid; this->m_debuggerMethodId = methodId; this->m_ilOffset = il_offset; this->m_flags = flags; this->m_pThread = thread; } HRESULT STDMETHODCALLTYPE CordbJITILFrame::GetChain(ICorDebugChain** ppChain) { LOG((LF_CORDB, LL_INFO100000, "CordbFrame - GetChain - NOT IMPLEMENTED\n")); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CordbJITILFrame::GetCode(ICorDebugCode** ppCode) { LOG((LF_CORDB, LL_INFO100000, "CordbFrame - GetCode - NOT IMPLEMENTED\n")); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CordbJITILFrame::GetFunction(ICorDebugFunction** ppFunction) { CordbFunction* func = conn->GetProcess()->FindFunction(m_debuggerMethodId); if (!func) { func = new CordbFunction(conn, 0, m_debuggerMethodId, NULL); } func->QueryInterface(IID_ICorDebugFunction, (void**)ppFunction); LOG((LF_CORDB, LL_INFO1000000, "CordbFrame - GetFunction - IMPLEMENTED\n")); return S_OK; } HRESULT STDMETHODCALLTYPE CordbJITILFrame::GetFunctionToken(mdMethodDef* pToken) { LOG((LF_CORDB, LL_INFO100000, "CordbFrame - GetFunctionToken - IMPLEMENTED\n")); HRESULT hr = S_OK; EX_TRY { MdbgProtBuffer localbuf; m_dbgprot_buffer_init(&localbuf, 128); m_dbgprot_buffer_add_id(&localbuf, m_debuggerMethodId); int cmdId = conn->SendEvent(MDBGPROT_CMD_SET_METHOD, MDBGPROT_CMD_METHOD_GET_INFO, &localbuf); m_dbgprot_buffer_free(&localbuf); ReceivedReplyPacket* received_reply_packet = conn->GetReplyWithError(cmdId); CHECK_ERROR_RETURN_FALSE(received_reply_packet); MdbgProtBuffer* pReply = received_reply_packet->Buffer(); int flags = m_dbgprot_decode_int(pReply->p, &pReply->p, pReply->end); int iflags = m_dbgprot_decode_int(pReply->p, &pReply->p, pReply->end); *pToken = m_dbgprot_decode_int(pReply->p, &pReply->p, pReply->end); } EX_CATCH_HRESULT(hr); return hr; } HRESULT STDMETHODCALLTYPE CordbJITILFrame::GetStackRange(CORDB_ADDRESS* pStart, CORDB_ADDRESS* pEnd) { *pStart = 0; //forced value, only to make vs work, I'm not sure which value should returned from mono runtime *pEnd = 1; //forced value, only to make vs work, I'm not sure which value should returned from mono runtime LOG((LF_CORDB, LL_INFO100000, "CordbFrame - GetStackRange - NOT IMPLEMENTED\n")); return S_OK; } HRESULT STDMETHODCALLTYPE CordbJITILFrame::GetCaller(ICorDebugFrame** ppFrame) { LOG((LF_CORDB, LL_INFO100000, "CordbFrame - GetCaller - NOT IMPLEMENTED\n")); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CordbJITILFrame::GetCallee(ICorDebugFrame** ppFrame) { LOG((LF_CORDB, LL_INFO100000, "CordbFrame - GetCallee - NOT IMPLEMENTED\n")); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CordbJITILFrame::CreateStepper(ICorDebugStepper** ppStepper) { LOG((LF_CORDB, LL_INFO100000, "CordbJITILFrame - CreateStepper - IMPLEMENTED\n")); return m_pThread->CreateStepper(ppStepper); } HRESULT STDMETHODCALLTYPE CordbJITILFrame::QueryInterface(REFIID id, _COM_Outptr_ void __RPC_FAR* __RPC_FAR* pInterface) { if (id == IID_ICorDebugILFrame) { *pInterface = static_cast<ICorDebugILFrame*>(this); } else if (id == IID_ICorDebugILFrame2) { *pInterface = static_cast<ICorDebugILFrame2*>(this); } else if (id == IID_ICorDebugILFrame3) { *pInterface = static_cast<ICorDebugILFrame3*>(this); } else if (id == IID_ICorDebugILFrame4) { *pInterface = static_cast<ICorDebugILFrame4*>(this); } else { *pInterface = NULL; return E_NOINTERFACE; } AddRef(); return S_OK; } HRESULT STDMETHODCALLTYPE CordbJITILFrame::RemapFunction(ULONG32 newILOffset) { LOG((LF_CORDB, LL_INFO100000, "CordbFrame - RemapFunction - NOT IMPLEMENTED\n")); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CordbJITILFrame::EnumerateTypeParameters(ICorDebugTypeEnum** ppTyParEnum) { LOG((LF_CORDB, LL_INFO100000, "CordbFrame - EnumerateTypeParameters - NOT IMPLEMENTED\n")); return S_OK; } HRESULT STDMETHODCALLTYPE CordbJITILFrame::GetReturnValueForILOffset(ULONG32 ILoffset, ICorDebugValue** ppReturnValue) { LOG((LF_CORDB, LL_INFO100000, "CordbFrame - GetReturnValueForILOffset - NOT IMPLEMENTED\n")); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CordbJITILFrame::EnumerateLocalVariablesEx(ILCodeKind flags, ICorDebugValueEnum** ppValueEnum) { LOG((LF_CORDB, LL_INFO100000, "CordbFrame - EnumerateLocalVariablesEx - IMPLEMENTED\n")); CordbValueEnum* pCordbValueEnum = new CordbValueEnum(conn, m_pThread->GetThreadId(), m_debuggerFrameId, false, flags); return pCordbValueEnum->QueryInterface(IID_ICorDebugValueEnum, (void**)ppValueEnum); } HRESULT STDMETHODCALLTYPE CordbJITILFrame::GetLocalVariableEx(ILCodeKind flags, DWORD dwIndex, ICorDebugValue** ppValue) { LOG((LF_CORDB, LL_INFO100000, "CordbFrame - GetLocalVariableEx - NOT IMPLEMENTED\n")); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CordbJITILFrame::GetCodeEx(ILCodeKind flags, ICorDebugCode** ppCode) { if (flags == ILCODE_REJIT_IL) *ppCode = NULL; else { ICorDebugFunction* ppFunction; GetFunction(&ppFunction); ppFunction->GetILCode(ppCode); ppFunction->Release(); } LOG((LF_CORDB, LL_INFO1000000, "CordbJITILFrame - GetCodeEx - IMPLEMENTED\n")); return S_OK; } HRESULT STDMETHODCALLTYPE CordbJITILFrame::GetIP(ULONG32* pnOffset, CorDebugMappingResult* pMappingResult) { *pnOffset = m_ilOffset; *pMappingResult = MAPPING_EXACT; LOG((LF_CORDB, LL_INFO1000000, "CordbFrame - GetIP - IMPLEMENTED\n")); return S_OK; } HRESULT STDMETHODCALLTYPE CordbJITILFrame::SetIP(ULONG32 nOffset) { LOG((LF_CORDB, LL_INFO100000, "CordbFrame - SetIP - NOT IMPLEMENTED\n")); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CordbJITILFrame::EnumerateLocalVariables(ICorDebugValueEnum** ppValueEnum) { LOG((LF_CORDB, LL_INFO100000, "CordbFrame - EnumerateLocalVariables - IMPLEMENTED\n")); CordbValueEnum *pCordbValueEnum = new CordbValueEnum(conn, m_pThread->GetThreadId(), false, m_debuggerFrameId); return pCordbValueEnum->QueryInterface(IID_ICorDebugValueEnum, (void**)ppValueEnum); } HRESULT STDMETHODCALLTYPE CordbJITILFrame::GetLocalVariable(DWORD dwIndex, ICorDebugValue** ppValue) { HRESULT hr = S_OK; EX_TRY { MdbgProtBuffer localbuf; m_dbgprot_buffer_init(&localbuf, 128); m_dbgprot_buffer_add_id(&localbuf, m_pThread->GetThreadId()); m_dbgprot_buffer_add_id(&localbuf, m_debuggerFrameId); m_dbgprot_buffer_add_int(&localbuf, 1); m_dbgprot_buffer_add_int(&localbuf, dwIndex); int cmdId = conn->SendEvent(MDBGPROT_CMD_SET_STACK_FRAME, MDBGPROT_CMD_STACK_FRAME_GET_VALUES, &localbuf); m_dbgprot_buffer_free(&localbuf); ReceivedReplyPacket* received_reply_packet = conn->GetReplyWithError(cmdId); CHECK_ERROR_RETURN_FALSE(received_reply_packet); MdbgProtBuffer* pReply = received_reply_packet->Buffer(); hr = CordbObjectValue::CreateCordbValue(conn, pReply, ppValue); } EX_CATCH_HRESULT(hr); return hr; } HRESULT STDMETHODCALLTYPE CordbJITILFrame::EnumerateArguments(ICorDebugValueEnum** ppValueEnum) { LOG((LF_CORDB, LL_INFO100000, "CordbFrame - EnumerateArguments - IMPLEMENTED\n")); CordbValueEnum* pCordbValueEnum = new CordbValueEnum(conn, m_pThread->GetThreadId(), m_debuggerFrameId, true); return pCordbValueEnum->QueryInterface(IID_ICorDebugValueEnum, (void**)ppValueEnum); } HRESULT STDMETHODCALLTYPE CordbJITILFrame::GetArgument(DWORD dwIndex, ICorDebugValue** ppValue) { LOG((LF_CORDB, LL_INFO1000000, "CordbFrame - GetArgument - IMPLEMENTED\n")); HRESULT hr = S_OK; EX_TRY { MdbgProtBuffer localbuf; m_dbgprot_buffer_init(&localbuf, 128); m_dbgprot_buffer_add_id(&localbuf, m_pThread->GetThreadId()); m_dbgprot_buffer_add_id(&localbuf, m_debuggerFrameId); m_dbgprot_buffer_add_int(&localbuf, dwIndex); int cmdId = conn->SendEvent(MDBGPROT_CMD_SET_STACK_FRAME, MDBGPROT_CMD_STACK_FRAME_GET_ARGUMENT, &localbuf); m_dbgprot_buffer_free(&localbuf); ReceivedReplyPacket* received_reply_packet = conn->GetReplyWithError(cmdId); CHECK_ERROR_RETURN_FALSE(received_reply_packet); MdbgProtBuffer* pReply = received_reply_packet->Buffer(); hr = CordbObjectValue::CreateCordbValue(conn, pReply, ppValue); } EX_CATCH_HRESULT(hr); return hr; } HRESULT STDMETHODCALLTYPE CordbJITILFrame::GetStackDepth(ULONG32* pDepth) { LOG((LF_CORDB, LL_INFO100000, "CordbFrame - GetStackDepth - NOT IMPLEMENTED\n")); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CordbJITILFrame::GetStackValue(DWORD dwIndex, ICorDebugValue** ppValue) { LOG((LF_CORDB, LL_INFO100000, "CordbFrame - GetStackValue - NOT IMPLEMENTED\n")); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CordbJITILFrame::CanSetIP(ULONG32 nOffset) { LOG((LF_CORDB, LL_INFO100000, "CordbFrame - CanSetIP - NOT IMPLEMENTED\n")); return E_NOTIMPL; } CordbNativeFrame::~CordbNativeFrame() { m_JITILFrame->InternalRelease(); } CordbNativeFrame::CordbNativeFrame( Connection* conn, int frameid, int methodId, int il_offset, int flags, CordbThread* thread, int posFrame) : CordbBaseMono(conn) { m_JITILFrame = new CordbJITILFrame(conn, frameid, methodId, il_offset, flags, thread); m_JITILFrame->InternalAddRef(); this->m_pThread = thread; this->m_nPosFrame = posFrame; } HRESULT STDMETHODCALLTYPE CordbNativeFrame::GetIP(ULONG32* pnOffset) { LOG((LF_CORDB, LL_INFO100000, "CordbNativeFrame - GetIP - NOT IMPLEMENTED\n")); return S_OK; } HRESULT STDMETHODCALLTYPE CordbNativeFrame::SetIP(ULONG32 nOffset) { LOG((LF_CORDB, LL_INFO100000, "CordbNativeFrame - SetIP - NOT IMPLEMENTED\n")); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CordbNativeFrame::GetRegisterSet(ICorDebugRegisterSet** ppRegisters) { return m_pThread->GetRegisterSet(ppRegisters); } HRESULT STDMETHODCALLTYPE CordbNativeFrame::GetLocalRegisterValue(CorDebugRegister reg, ULONG cbSigBlob, PCCOR_SIGNATURE pvSigBlob, ICorDebugValue** ppValue) { LOG((LF_CORDB, LL_INFO100000, "CordbNativeFrame - GetLocalRegisterValue - NOT IMPLEMENTED\n")); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CordbNativeFrame::GetLocalDoubleRegisterValue(CorDebugRegister highWordReg, CorDebugRegister lowWordReg, ULONG cbSigBlob, PCCOR_SIGNATURE pvSigBlob, ICorDebugValue** ppValue) { LOG((LF_CORDB, LL_INFO100000, "CordbNativeFrame - GetLocalDoubleRegisterValue - NOT IMPLEMENTED\n")); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CordbNativeFrame::GetLocalMemoryValue(CORDB_ADDRESS address, ULONG cbSigBlob, PCCOR_SIGNATURE pvSigBlob, ICorDebugValue** ppValue) { LOG((LF_CORDB, LL_INFO100000, "CordbNativeFrame - GetLocalMemoryValue - NOT IMPLEMENTED\n")); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CordbNativeFrame::GetLocalRegisterMemoryValue(CorDebugRegister highWordReg, CORDB_ADDRESS lowWordAddress, ULONG cbSigBlob, PCCOR_SIGNATURE pvSigBlob, ICorDebugValue** ppValue) { LOG((LF_CORDB, LL_INFO100000, "CordbNativeFrame - GetLocalRegisterMemoryValue - NOT IMPLEMENTED\n")); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CordbNativeFrame::GetLocalMemoryRegisterValue(CORDB_ADDRESS highWordAddress, CorDebugRegister lowWordRegister, ULONG cbSigBlob, PCCOR_SIGNATURE pvSigBlob, ICorDebugValue** ppValue) { LOG((LF_CORDB, LL_INFO100000, "CordbNativeFrame - GetLocalMemoryRegisterValue - NOT IMPLEMENTED\n")); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CordbNativeFrame::CanSetIP(ULONG32 nOffset) { LOG((LF_CORDB, LL_INFO100000, "CordbNativeFrame - CanSetIP - NOT IMPLEMENTED\n")); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CordbNativeFrame::GetChain(ICorDebugChain** ppChain) { LOG((LF_CORDB, LL_INFO100000, "CordbNativeFrame - GetChain - NOT IMPLEMENTED\n")); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CordbNativeFrame::GetCode(ICorDebugCode** ppCode) { ICorDebugFunction* ppFunction; m_JITILFrame->GetFunction(&ppFunction); ppFunction->GetILCode(ppCode); ppFunction->Release(); LOG((LF_CORDB, LL_INFO100000, "CordbJITILFrame - GetCodeEx - IMPLEMENTED\n")); return S_OK; } HRESULT STDMETHODCALLTYPE CordbNativeFrame::GetFunction(ICorDebugFunction** ppFunction) { return m_JITILFrame->GetFunction(ppFunction); } HRESULT STDMETHODCALLTYPE CordbNativeFrame::GetFunctionToken(mdMethodDef* pToken) { LOG((LF_CORDB, LL_INFO100000, "CordbNativeFrame - GetFunctionToken - IMPLEMENTED\n")); return m_JITILFrame->GetFunctionToken(pToken); } HRESULT STDMETHODCALLTYPE CordbNativeFrame::GetStackRange(CORDB_ADDRESS* pStart, CORDB_ADDRESS* pEnd) { return m_JITILFrame->GetStackRange(pStart, pEnd); } HRESULT STDMETHODCALLTYPE CordbNativeFrame::GetCaller(ICorDebugFrame** ppFrame) { LOG((LF_CORDB, LL_INFO100000, "CordbNativeFrame - GetCaller - NOT IMPLEMENTED\n")); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CordbNativeFrame::GetCallee(ICorDebugFrame** ppFrame) { LOG((LF_CORDB, LL_INFO100000, "CordbNativeFrame - GetCallee - NOT IMPLEMENTED\n")); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CordbNativeFrame::CreateStepper(ICorDebugStepper** ppStepper) { LOG((LF_CORDB, LL_INFO100000, "CordbNativeFrame - CreateStepper - IMPLEMENTED\n")); return m_pThread->CreateStepper(ppStepper); } HRESULT STDMETHODCALLTYPE CordbNativeFrame::QueryInterface(REFIID id, void** pInterface) { if (id == IID_ICorDebugFrame) { *pInterface = static_cast<ICorDebugFrame*>(static_cast<ICorDebugNativeFrame*>(this)); } else if (id == IID_ICorDebugNativeFrame) { *pInterface = static_cast<ICorDebugNativeFrame*>(this); } else if (id == IID_ICorDebugNativeFrame2) { *pInterface = static_cast<ICorDebugNativeFrame2*>(this); } else if (id == IID_IUnknown) { *pInterface = static_cast<IUnknown*>(static_cast<ICorDebugNativeFrame*>(this)); } else { // might be searching for an IL Frame. delegate that search to the // JITILFrame if (m_JITILFrame != NULL) { return m_JITILFrame->QueryInterface(id, pInterface); } else { *pInterface = NULL; return E_NOINTERFACE; } } AddRef(); return S_OK; } HRESULT STDMETHODCALLTYPE CordbNativeFrame::IsChild(BOOL* pIsChild) { LOG((LF_CORDB, LL_INFO100000, "CordbNativeFrame - IsChild - NOT IMPLEMENTED\n")); return S_OK; } HRESULT STDMETHODCALLTYPE CordbNativeFrame::IsMatchingParentFrame(ICorDebugNativeFrame2* pPotentialParentFrame, BOOL* pIsParent) { LOG((LF_CORDB, LL_INFO100000, "CordbNativeFrame - IsMatchingParentFrame - NOT IMPLEMENTED\n")); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CordbNativeFrame::GetStackParameterSize(ULONG32* pSize) { LOG((LF_CORDB, LL_INFO100000, "CordbNativeFrame - GetStackParameterSize - NOT IMPLEMENTED\n")); return E_NOTIMPL; }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // File: CORDB-FRAME.CPP // #include <cordb-code.h> #include <cordb-frame.h> #include <cordb-function.h> #include <cordb-process.h> #include <cordb-register.h> #include <cordb-thread.h> #include <cordb-value.h> using namespace std; CordbFrameEnum::CordbFrameEnum(Connection* conn, CordbThread* thread) : CordbBaseMono(conn) { this->m_pThread = thread; m_nFrames = 0; m_ppFrames = NULL; } CordbFrameEnum::~CordbFrameEnum() { Reset(); } HRESULT STDMETHODCALLTYPE CordbFrameEnum::Next(ULONG celt, ICorDebugFrame* frames[], ULONG* pceltFetched) { GetCount(); for (int i = 0; i < m_nFrames; i++) { this->m_ppFrames[i]->QueryInterface(IID_ICorDebugFrame, (void**)&frames[i]); } LOG((LF_CORDB, LL_INFO1000000, "CordbFrameEnum - Next - IMPLEMENTED\n")); return S_OK; } HRESULT STDMETHODCALLTYPE CordbFrameEnum::Skip(ULONG celt) { LOG((LF_CORDB, LL_INFO100000, "CordbFrameEnum - Skip - NOT IMPLEMENTED\n")); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CordbFrameEnum::Reset(void) { for (int i = 0; i < m_nFrames; i++) { this->m_ppFrames[i]->InternalRelease(); } m_nFrames = 0; if (m_ppFrames) free(m_ppFrames); m_ppFrames = NULL; return S_OK; } HRESULT STDMETHODCALLTYPE CordbFrameEnum::Clone(ICorDebugEnum** ppEnum) { LOG((LF_CORDB, LL_INFO100000, "CordbFrameEnum - Clone - NOT IMPLEMENTED\n")); return E_NOTIMPL; } HRESULT CordbFrameEnum::GetCount() { HRESULT hr = S_OK; if (m_nFrames != 0) return hr; EX_TRY { Reset(); MdbgProtBuffer localbuf; m_dbgprot_buffer_init(&localbuf, 128); m_dbgprot_buffer_add_id(&localbuf, m_pThread->GetThreadId()); m_dbgprot_buffer_add_int(&localbuf, 0); m_dbgprot_buffer_add_int(&localbuf, -1); int cmdId = conn->SendEvent(MDBGPROT_CMD_SET_THREAD, MDBGPROT_CMD_THREAD_GET_FRAME_INFO, &localbuf); m_dbgprot_buffer_free(&localbuf); ReceivedReplyPacket* received_reply_packet = conn->GetReplyWithError(cmdId); CHECK_ERROR_RETURN_FALSE(received_reply_packet); MdbgProtBuffer* pReply = received_reply_packet->Buffer(); m_nFrames = m_dbgprot_decode_int(pReply->p, &pReply->p, pReply->end); m_ppFrames = (CordbNativeFrame**)malloc(sizeof(CordbNativeFrame*) * m_nFrames); for (int i = 0; i < m_nFrames; i++) { int frameid = m_dbgprot_decode_int(pReply->p, &pReply->p, pReply->end); int methodId = m_dbgprot_decode_id(pReply->p, &pReply->p, pReply->end); int il_offset = m_dbgprot_decode_int(pReply->p, &pReply->p, pReply->end); int flags = m_dbgprot_decode_byte(pReply->p, &pReply->p, pReply->end); CordbNativeFrame* frame = new CordbNativeFrame(conn, frameid, methodId, il_offset, flags, m_pThread, i); frame->InternalAddRef(); m_ppFrames[i] = frame; } } EX_CATCH_HRESULT(hr); return hr; } HRESULT STDMETHODCALLTYPE CordbFrameEnum::GetCount(ULONG* pcelt) { LOG((LF_CORDB, LL_INFO1000000, "CordbFrameEnum - GetCount - IMPLEMENTED\n")); HRESULT hr = S_OK; hr = GetCount(); *pcelt = m_nFrames; return hr; } HRESULT STDMETHODCALLTYPE CordbFrameEnum::QueryInterface(REFIID riid, void** ppvObject) { LOG((LF_CORDB, LL_INFO100000, "CordbFrameEnum - QueryInterface - NOT IMPLEMENTED\n")); return E_NOTIMPL; } CordbJITILFrame::CordbJITILFrame( Connection* conn, int frameid, int methodId, int il_offset, int flags, CordbThread* thread) : CordbBaseMono(conn) { this->m_debuggerFrameId = frameid; this->m_debuggerMethodId = methodId; this->m_ilOffset = il_offset; this->m_flags = flags; this->m_pThread = thread; } HRESULT STDMETHODCALLTYPE CordbJITILFrame::GetChain(ICorDebugChain** ppChain) { LOG((LF_CORDB, LL_INFO100000, "CordbFrame - GetChain - NOT IMPLEMENTED\n")); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CordbJITILFrame::GetCode(ICorDebugCode** ppCode) { LOG((LF_CORDB, LL_INFO100000, "CordbFrame - GetCode - NOT IMPLEMENTED\n")); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CordbJITILFrame::GetFunction(ICorDebugFunction** ppFunction) { CordbFunction* func = conn->GetProcess()->FindFunction(m_debuggerMethodId); if (!func) { func = new CordbFunction(conn, 0, m_debuggerMethodId, NULL); } func->QueryInterface(IID_ICorDebugFunction, (void**)ppFunction); LOG((LF_CORDB, LL_INFO1000000, "CordbFrame - GetFunction - IMPLEMENTED\n")); return S_OK; } HRESULT STDMETHODCALLTYPE CordbJITILFrame::GetFunctionToken(mdMethodDef* pToken) { LOG((LF_CORDB, LL_INFO100000, "CordbFrame - GetFunctionToken - IMPLEMENTED\n")); HRESULT hr = S_OK; EX_TRY { MdbgProtBuffer localbuf; m_dbgprot_buffer_init(&localbuf, 128); m_dbgprot_buffer_add_id(&localbuf, m_debuggerMethodId); int cmdId = conn->SendEvent(MDBGPROT_CMD_SET_METHOD, MDBGPROT_CMD_METHOD_GET_INFO, &localbuf); m_dbgprot_buffer_free(&localbuf); ReceivedReplyPacket* received_reply_packet = conn->GetReplyWithError(cmdId); CHECK_ERROR_RETURN_FALSE(received_reply_packet); MdbgProtBuffer* pReply = received_reply_packet->Buffer(); int flags = m_dbgprot_decode_int(pReply->p, &pReply->p, pReply->end); int iflags = m_dbgprot_decode_int(pReply->p, &pReply->p, pReply->end); *pToken = m_dbgprot_decode_int(pReply->p, &pReply->p, pReply->end); } EX_CATCH_HRESULT(hr); return hr; } HRESULT STDMETHODCALLTYPE CordbJITILFrame::GetStackRange(CORDB_ADDRESS* pStart, CORDB_ADDRESS* pEnd) { *pStart = 0; //forced value, only to make vs work, I'm not sure which value should returned from mono runtime *pEnd = 1; //forced value, only to make vs work, I'm not sure which value should returned from mono runtime LOG((LF_CORDB, LL_INFO100000, "CordbFrame - GetStackRange - NOT IMPLEMENTED\n")); return S_OK; } HRESULT STDMETHODCALLTYPE CordbJITILFrame::GetCaller(ICorDebugFrame** ppFrame) { LOG((LF_CORDB, LL_INFO100000, "CordbFrame - GetCaller - NOT IMPLEMENTED\n")); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CordbJITILFrame::GetCallee(ICorDebugFrame** ppFrame) { LOG((LF_CORDB, LL_INFO100000, "CordbFrame - GetCallee - NOT IMPLEMENTED\n")); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CordbJITILFrame::CreateStepper(ICorDebugStepper** ppStepper) { LOG((LF_CORDB, LL_INFO100000, "CordbJITILFrame - CreateStepper - IMPLEMENTED\n")); return m_pThread->CreateStepper(ppStepper); } HRESULT STDMETHODCALLTYPE CordbJITILFrame::QueryInterface(REFIID id, _COM_Outptr_ void __RPC_FAR* __RPC_FAR* pInterface) { if (id == IID_ICorDebugILFrame) { *pInterface = static_cast<ICorDebugILFrame*>(this); } else if (id == IID_ICorDebugILFrame2) { *pInterface = static_cast<ICorDebugILFrame2*>(this); } else if (id == IID_ICorDebugILFrame3) { *pInterface = static_cast<ICorDebugILFrame3*>(this); } else if (id == IID_ICorDebugILFrame4) { *pInterface = static_cast<ICorDebugILFrame4*>(this); } else { *pInterface = NULL; return E_NOINTERFACE; } AddRef(); return S_OK; } HRESULT STDMETHODCALLTYPE CordbJITILFrame::RemapFunction(ULONG32 newILOffset) { LOG((LF_CORDB, LL_INFO100000, "CordbFrame - RemapFunction - NOT IMPLEMENTED\n")); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CordbJITILFrame::EnumerateTypeParameters(ICorDebugTypeEnum** ppTyParEnum) { LOG((LF_CORDB, LL_INFO100000, "CordbFrame - EnumerateTypeParameters - NOT IMPLEMENTED\n")); return S_OK; } HRESULT STDMETHODCALLTYPE CordbJITILFrame::GetReturnValueForILOffset(ULONG32 ILoffset, ICorDebugValue** ppReturnValue) { LOG((LF_CORDB, LL_INFO100000, "CordbFrame - GetReturnValueForILOffset - NOT IMPLEMENTED\n")); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CordbJITILFrame::EnumerateLocalVariablesEx(ILCodeKind flags, ICorDebugValueEnum** ppValueEnum) { LOG((LF_CORDB, LL_INFO100000, "CordbFrame - EnumerateLocalVariablesEx - IMPLEMENTED\n")); CordbValueEnum* pCordbValueEnum = new CordbValueEnum(conn, m_pThread->GetThreadId(), m_debuggerFrameId, false, flags); return pCordbValueEnum->QueryInterface(IID_ICorDebugValueEnum, (void**)ppValueEnum); } HRESULT STDMETHODCALLTYPE CordbJITILFrame::GetLocalVariableEx(ILCodeKind flags, DWORD dwIndex, ICorDebugValue** ppValue) { LOG((LF_CORDB, LL_INFO100000, "CordbFrame - GetLocalVariableEx - NOT IMPLEMENTED\n")); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CordbJITILFrame::GetCodeEx(ILCodeKind flags, ICorDebugCode** ppCode) { if (flags == ILCODE_REJIT_IL) *ppCode = NULL; else { ICorDebugFunction* ppFunction; GetFunction(&ppFunction); ppFunction->GetILCode(ppCode); ppFunction->Release(); } LOG((LF_CORDB, LL_INFO1000000, "CordbJITILFrame - GetCodeEx - IMPLEMENTED\n")); return S_OK; } HRESULT STDMETHODCALLTYPE CordbJITILFrame::GetIP(ULONG32* pnOffset, CorDebugMappingResult* pMappingResult) { *pnOffset = m_ilOffset; *pMappingResult = MAPPING_EXACT; LOG((LF_CORDB, LL_INFO1000000, "CordbFrame - GetIP - IMPLEMENTED\n")); return S_OK; } HRESULT STDMETHODCALLTYPE CordbJITILFrame::SetIP(ULONG32 nOffset) { LOG((LF_CORDB, LL_INFO100000, "CordbFrame - SetIP - NOT IMPLEMENTED\n")); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CordbJITILFrame::EnumerateLocalVariables(ICorDebugValueEnum** ppValueEnum) { LOG((LF_CORDB, LL_INFO100000, "CordbFrame - EnumerateLocalVariables - IMPLEMENTED\n")); CordbValueEnum *pCordbValueEnum = new CordbValueEnum(conn, m_pThread->GetThreadId(), false, m_debuggerFrameId); return pCordbValueEnum->QueryInterface(IID_ICorDebugValueEnum, (void**)ppValueEnum); } HRESULT STDMETHODCALLTYPE CordbJITILFrame::GetLocalVariable(DWORD dwIndex, ICorDebugValue** ppValue) { HRESULT hr = S_OK; EX_TRY { MdbgProtBuffer localbuf; m_dbgprot_buffer_init(&localbuf, 128); m_dbgprot_buffer_add_id(&localbuf, m_pThread->GetThreadId()); m_dbgprot_buffer_add_id(&localbuf, m_debuggerFrameId); m_dbgprot_buffer_add_int(&localbuf, 1); m_dbgprot_buffer_add_int(&localbuf, dwIndex); int cmdId = conn->SendEvent(MDBGPROT_CMD_SET_STACK_FRAME, MDBGPROT_CMD_STACK_FRAME_GET_VALUES, &localbuf); m_dbgprot_buffer_free(&localbuf); ReceivedReplyPacket* received_reply_packet = conn->GetReplyWithError(cmdId); CHECK_ERROR_RETURN_FALSE(received_reply_packet); MdbgProtBuffer* pReply = received_reply_packet->Buffer(); hr = CordbObjectValue::CreateCordbValue(conn, pReply, ppValue); } EX_CATCH_HRESULT(hr); return hr; } HRESULT STDMETHODCALLTYPE CordbJITILFrame::EnumerateArguments(ICorDebugValueEnum** ppValueEnum) { LOG((LF_CORDB, LL_INFO100000, "CordbFrame - EnumerateArguments - IMPLEMENTED\n")); CordbValueEnum* pCordbValueEnum = new CordbValueEnum(conn, m_pThread->GetThreadId(), m_debuggerFrameId, true); return pCordbValueEnum->QueryInterface(IID_ICorDebugValueEnum, (void**)ppValueEnum); } HRESULT STDMETHODCALLTYPE CordbJITILFrame::GetArgument(DWORD dwIndex, ICorDebugValue** ppValue) { LOG((LF_CORDB, LL_INFO1000000, "CordbFrame - GetArgument - IMPLEMENTED\n")); HRESULT hr = S_OK; EX_TRY { MdbgProtBuffer localbuf; m_dbgprot_buffer_init(&localbuf, 128); m_dbgprot_buffer_add_id(&localbuf, m_pThread->GetThreadId()); m_dbgprot_buffer_add_id(&localbuf, m_debuggerFrameId); m_dbgprot_buffer_add_int(&localbuf, dwIndex); int cmdId = conn->SendEvent(MDBGPROT_CMD_SET_STACK_FRAME, MDBGPROT_CMD_STACK_FRAME_GET_ARGUMENT, &localbuf); m_dbgprot_buffer_free(&localbuf); ReceivedReplyPacket* received_reply_packet = conn->GetReplyWithError(cmdId); CHECK_ERROR_RETURN_FALSE(received_reply_packet); MdbgProtBuffer* pReply = received_reply_packet->Buffer(); hr = CordbObjectValue::CreateCordbValue(conn, pReply, ppValue); } EX_CATCH_HRESULT(hr); return hr; } HRESULT STDMETHODCALLTYPE CordbJITILFrame::GetStackDepth(ULONG32* pDepth) { LOG((LF_CORDB, LL_INFO100000, "CordbFrame - GetStackDepth - NOT IMPLEMENTED\n")); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CordbJITILFrame::GetStackValue(DWORD dwIndex, ICorDebugValue** ppValue) { LOG((LF_CORDB, LL_INFO100000, "CordbFrame - GetStackValue - NOT IMPLEMENTED\n")); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CordbJITILFrame::CanSetIP(ULONG32 nOffset) { LOG((LF_CORDB, LL_INFO100000, "CordbFrame - CanSetIP - NOT IMPLEMENTED\n")); return E_NOTIMPL; } CordbNativeFrame::~CordbNativeFrame() { m_JITILFrame->InternalRelease(); } CordbNativeFrame::CordbNativeFrame( Connection* conn, int frameid, int methodId, int il_offset, int flags, CordbThread* thread, int posFrame) : CordbBaseMono(conn) { m_JITILFrame = new CordbJITILFrame(conn, frameid, methodId, il_offset, flags, thread); m_JITILFrame->InternalAddRef(); this->m_pThread = thread; this->m_nPosFrame = posFrame; } HRESULT STDMETHODCALLTYPE CordbNativeFrame::GetIP(ULONG32* pnOffset) { LOG((LF_CORDB, LL_INFO100000, "CordbNativeFrame - GetIP - NOT IMPLEMENTED\n")); return S_OK; } HRESULT STDMETHODCALLTYPE CordbNativeFrame::SetIP(ULONG32 nOffset) { LOG((LF_CORDB, LL_INFO100000, "CordbNativeFrame - SetIP - NOT IMPLEMENTED\n")); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CordbNativeFrame::GetRegisterSet(ICorDebugRegisterSet** ppRegisters) { return m_pThread->GetRegisterSet(ppRegisters); } HRESULT STDMETHODCALLTYPE CordbNativeFrame::GetLocalRegisterValue(CorDebugRegister reg, ULONG cbSigBlob, PCCOR_SIGNATURE pvSigBlob, ICorDebugValue** ppValue) { LOG((LF_CORDB, LL_INFO100000, "CordbNativeFrame - GetLocalRegisterValue - NOT IMPLEMENTED\n")); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CordbNativeFrame::GetLocalDoubleRegisterValue(CorDebugRegister highWordReg, CorDebugRegister lowWordReg, ULONG cbSigBlob, PCCOR_SIGNATURE pvSigBlob, ICorDebugValue** ppValue) { LOG((LF_CORDB, LL_INFO100000, "CordbNativeFrame - GetLocalDoubleRegisterValue - NOT IMPLEMENTED\n")); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CordbNativeFrame::GetLocalMemoryValue(CORDB_ADDRESS address, ULONG cbSigBlob, PCCOR_SIGNATURE pvSigBlob, ICorDebugValue** ppValue) { LOG((LF_CORDB, LL_INFO100000, "CordbNativeFrame - GetLocalMemoryValue - NOT IMPLEMENTED\n")); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CordbNativeFrame::GetLocalRegisterMemoryValue(CorDebugRegister highWordReg, CORDB_ADDRESS lowWordAddress, ULONG cbSigBlob, PCCOR_SIGNATURE pvSigBlob, ICorDebugValue** ppValue) { LOG((LF_CORDB, LL_INFO100000, "CordbNativeFrame - GetLocalRegisterMemoryValue - NOT IMPLEMENTED\n")); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CordbNativeFrame::GetLocalMemoryRegisterValue(CORDB_ADDRESS highWordAddress, CorDebugRegister lowWordRegister, ULONG cbSigBlob, PCCOR_SIGNATURE pvSigBlob, ICorDebugValue** ppValue) { LOG((LF_CORDB, LL_INFO100000, "CordbNativeFrame - GetLocalMemoryRegisterValue - NOT IMPLEMENTED\n")); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CordbNativeFrame::CanSetIP(ULONG32 nOffset) { LOG((LF_CORDB, LL_INFO100000, "CordbNativeFrame - CanSetIP - NOT IMPLEMENTED\n")); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CordbNativeFrame::GetChain(ICorDebugChain** ppChain) { LOG((LF_CORDB, LL_INFO100000, "CordbNativeFrame - GetChain - NOT IMPLEMENTED\n")); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CordbNativeFrame::GetCode(ICorDebugCode** ppCode) { ICorDebugFunction* ppFunction; m_JITILFrame->GetFunction(&ppFunction); ppFunction->GetILCode(ppCode); ppFunction->Release(); LOG((LF_CORDB, LL_INFO100000, "CordbJITILFrame - GetCodeEx - IMPLEMENTED\n")); return S_OK; } HRESULT STDMETHODCALLTYPE CordbNativeFrame::GetFunction(ICorDebugFunction** ppFunction) { return m_JITILFrame->GetFunction(ppFunction); } HRESULT STDMETHODCALLTYPE CordbNativeFrame::GetFunctionToken(mdMethodDef* pToken) { LOG((LF_CORDB, LL_INFO100000, "CordbNativeFrame - GetFunctionToken - IMPLEMENTED\n")); return m_JITILFrame->GetFunctionToken(pToken); } HRESULT STDMETHODCALLTYPE CordbNativeFrame::GetStackRange(CORDB_ADDRESS* pStart, CORDB_ADDRESS* pEnd) { return m_JITILFrame->GetStackRange(pStart, pEnd); } HRESULT STDMETHODCALLTYPE CordbNativeFrame::GetCaller(ICorDebugFrame** ppFrame) { LOG((LF_CORDB, LL_INFO100000, "CordbNativeFrame - GetCaller - NOT IMPLEMENTED\n")); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CordbNativeFrame::GetCallee(ICorDebugFrame** ppFrame) { LOG((LF_CORDB, LL_INFO100000, "CordbNativeFrame - GetCallee - NOT IMPLEMENTED\n")); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CordbNativeFrame::CreateStepper(ICorDebugStepper** ppStepper) { LOG((LF_CORDB, LL_INFO100000, "CordbNativeFrame - CreateStepper - IMPLEMENTED\n")); return m_pThread->CreateStepper(ppStepper); } HRESULT STDMETHODCALLTYPE CordbNativeFrame::QueryInterface(REFIID id, void** pInterface) { if (id == IID_ICorDebugFrame) { *pInterface = static_cast<ICorDebugFrame*>(static_cast<ICorDebugNativeFrame*>(this)); } else if (id == IID_ICorDebugNativeFrame) { *pInterface = static_cast<ICorDebugNativeFrame*>(this); } else if (id == IID_ICorDebugNativeFrame2) { *pInterface = static_cast<ICorDebugNativeFrame2*>(this); } else if (id == IID_IUnknown) { *pInterface = static_cast<IUnknown*>(static_cast<ICorDebugNativeFrame*>(this)); } else { // might be searching for an IL Frame. delegate that search to the // JITILFrame if (m_JITILFrame != NULL) { return m_JITILFrame->QueryInterface(id, pInterface); } else { *pInterface = NULL; return E_NOINTERFACE; } } AddRef(); return S_OK; } HRESULT STDMETHODCALLTYPE CordbNativeFrame::IsChild(BOOL* pIsChild) { LOG((LF_CORDB, LL_INFO100000, "CordbNativeFrame - IsChild - NOT IMPLEMENTED\n")); return S_OK; } HRESULT STDMETHODCALLTYPE CordbNativeFrame::IsMatchingParentFrame(ICorDebugNativeFrame2* pPotentialParentFrame, BOOL* pIsParent) { LOG((LF_CORDB, LL_INFO100000, "CordbNativeFrame - IsMatchingParentFrame - NOT IMPLEMENTED\n")); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CordbNativeFrame::GetStackParameterSize(ULONG32* pSize) { LOG((LF_CORDB, LL_INFO100000, "CordbNativeFrame - GetStackParameterSize - NOT IMPLEMENTED\n")); return E_NOTIMPL; }
-1
dotnet/runtime
66,474
Update repo CMake configuration to target /W4 by default
Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
AaronRobinsonMSFT
2022-03-10T20:20:31Z
2022-03-11T04:59:21Z
ba5207b0f4054fe8963fc3e87c2bd32907516961
5ce2b9f860f7a84c3059650bb67817d59d8f4953
Update repo CMake configuration to target /W4 by default. Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
./src/tests/Loader/classloader/TypeInitialization/CoreCLR/CircularCctorThreeThreads03.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <OutputType>Exe</OutputType> </PropertyGroup> <ItemGroup> <Compile Include="CircularCctorThreeThreads03.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <OutputType>Exe</OutputType> </PropertyGroup> <ItemGroup> <Compile Include="CircularCctorThreeThreads03.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,474
Update repo CMake configuration to target /W4 by default
Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
AaronRobinsonMSFT
2022-03-10T20:20:31Z
2022-03-11T04:59:21Z
ba5207b0f4054fe8963fc3e87c2bd32907516961
5ce2b9f860f7a84c3059650bb67817d59d8f4953
Update repo CMake configuration to target /W4 by default. Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
./src/libraries/System.Reflection/tests/AssemblyVersion/System.Reflection.Tests.Assembly_1_1_1_3.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <AssemblyVersion>1.1.1.3</AssemblyVersion> <TargetFramework>netstandard2.0</TargetFramework> </PropertyGroup> <ItemGroup> <Compile Include="Program_1_1_1_3.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <AssemblyVersion>1.1.1.3</AssemblyVersion> <TargetFramework>netstandard2.0</TargetFramework> </PropertyGroup> <ItemGroup> <Compile Include="Program_1_1_1_3.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,474
Update repo CMake configuration to target /W4 by default
Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
AaronRobinsonMSFT
2022-03-10T20:20:31Z
2022-03-11T04:59:21Z
ba5207b0f4054fe8963fc3e87c2bd32907516961
5ce2b9f860f7a84c3059650bb67817d59d8f4953
Update repo CMake configuration to target /W4 by default. Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
./src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/CustomConverterTests/CustomConverterTests.DictionaryInt32StringKeyValueConverter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; using Xunit; namespace System.Text.Json.Serialization.Tests { public static partial class CustomConverterTests { /// <summary> /// Demonstrates a <see cref="Dictionary{int, string}"> converter using a JSON array containing KeyValuePair objects. /// Sample JSON: [{"Key":1,"Value":"One"},{"Key":2,"Value":"Two"}] /// </summary> internal class DictionaryInt32StringKeyValueConverter : JsonConverter<Dictionary<int, string>> { private JsonConverter<KeyValuePair<int, string>> _intToStringConverter; public DictionaryInt32StringKeyValueConverter(JsonSerializerOptions options!!) { if (options == null) { throw new ArgumentNullException(nameof(options)); } _intToStringConverter = (JsonConverter<KeyValuePair<int, string>>)options.GetConverter(typeof(KeyValuePair<int, string>)); // KeyValuePair<> converter is built-in. Debug.Assert(_intToStringConverter != null); } public override Dictionary<int, string> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType != JsonTokenType.StartArray) { throw new JsonException(); } var value = new Dictionary<int, string>(); while (reader.Read()) { if (reader.TokenType == JsonTokenType.EndArray) { return value; } KeyValuePair<int, string> kvpair = _intToStringConverter.Read(ref reader, typeof(KeyValuePair<int, string>), options); value.Add(kvpair.Key, kvpair.Value); } throw new JsonException(); } public override void Write(Utf8JsonWriter writer, Dictionary<int, string> value, JsonSerializerOptions options) { writer.WriteStartArray(); foreach (KeyValuePair<int, string> item in value) { _intToStringConverter.Write(writer, item, options); } writer.WriteEndArray(); } } [Fact] public static void VerifyDictionaryInt32StringKeyValueConverter() { const string json = @"[{""Key"":1,""Value"":""ValueOne""},{""Key"":2,""Value"":""ValueTwo""}]"; var options = new JsonSerializerOptions(); options.Converters.Add(new DictionaryInt32StringKeyValueConverter(options)); Dictionary<int, string> dictionary = JsonSerializer.Deserialize<Dictionary<int, string>>(json, options); Assert.Equal("ValueOne", dictionary[1]); Assert.Equal("ValueTwo", dictionary[2]); string jsonSerialized = JsonSerializer.Serialize(dictionary, options); Assert.Equal(json, jsonSerialized); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; using Xunit; namespace System.Text.Json.Serialization.Tests { public static partial class CustomConverterTests { /// <summary> /// Demonstrates a <see cref="Dictionary{int, string}"> converter using a JSON array containing KeyValuePair objects. /// Sample JSON: [{"Key":1,"Value":"One"},{"Key":2,"Value":"Two"}] /// </summary> internal class DictionaryInt32StringKeyValueConverter : JsonConverter<Dictionary<int, string>> { private JsonConverter<KeyValuePair<int, string>> _intToStringConverter; public DictionaryInt32StringKeyValueConverter(JsonSerializerOptions options!!) { if (options == null) { throw new ArgumentNullException(nameof(options)); } _intToStringConverter = (JsonConverter<KeyValuePair<int, string>>)options.GetConverter(typeof(KeyValuePair<int, string>)); // KeyValuePair<> converter is built-in. Debug.Assert(_intToStringConverter != null); } public override Dictionary<int, string> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType != JsonTokenType.StartArray) { throw new JsonException(); } var value = new Dictionary<int, string>(); while (reader.Read()) { if (reader.TokenType == JsonTokenType.EndArray) { return value; } KeyValuePair<int, string> kvpair = _intToStringConverter.Read(ref reader, typeof(KeyValuePair<int, string>), options); value.Add(kvpair.Key, kvpair.Value); } throw new JsonException(); } public override void Write(Utf8JsonWriter writer, Dictionary<int, string> value, JsonSerializerOptions options) { writer.WriteStartArray(); foreach (KeyValuePair<int, string> item in value) { _intToStringConverter.Write(writer, item, options); } writer.WriteEndArray(); } } [Fact] public static void VerifyDictionaryInt32StringKeyValueConverter() { const string json = @"[{""Key"":1,""Value"":""ValueOne""},{""Key"":2,""Value"":""ValueTwo""}]"; var options = new JsonSerializerOptions(); options.Converters.Add(new DictionaryInt32StringKeyValueConverter(options)); Dictionary<int, string> dictionary = JsonSerializer.Deserialize<Dictionary<int, string>>(json, options); Assert.Equal("ValueOne", dictionary[1]); Assert.Equal("ValueTwo", dictionary[2]); string jsonSerialized = JsonSerializer.Serialize(dictionary, options); Assert.Equal(json, jsonSerialized); } } }
-1
dotnet/runtime
66,474
Update repo CMake configuration to target /W4 by default
Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
AaronRobinsonMSFT
2022-03-10T20:20:31Z
2022-03-11T04:59:21Z
ba5207b0f4054fe8963fc3e87c2bd32907516961
5ce2b9f860f7a84c3059650bb67817d59d8f4953
Update repo CMake configuration to target /W4 by default. Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
./src/libraries/System.DirectoryServices.AccountManagement/ref/System.DirectoryServices.AccountManagement.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // ------------------------------------------------------------------------------ // Changes to this file must follow the https://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.DirectoryServices.AccountManagement { public partial class AdvancedFilters { protected internal AdvancedFilters(System.DirectoryServices.AccountManagement.Principal p) { } public void AccountExpirationDate(System.DateTime expirationTime, System.DirectoryServices.AccountManagement.MatchType match) { } public void AccountLockoutTime(System.DateTime lockoutTime, System.DirectoryServices.AccountManagement.MatchType match) { } protected void AdvancedFilterSet(string attribute, object value, System.Type objectType, System.DirectoryServices.AccountManagement.MatchType mt) { } public void BadLogonCount(int badLogonCount, System.DirectoryServices.AccountManagement.MatchType match) { } public void LastBadPasswordAttempt(System.DateTime lastAttempt, System.DirectoryServices.AccountManagement.MatchType match) { } public void LastLogonTime(System.DateTime logonTime, System.DirectoryServices.AccountManagement.MatchType match) { } public void LastPasswordSetTime(System.DateTime passwordSetTime, System.DirectoryServices.AccountManagement.MatchType match) { } } [System.DirectoryServices.AccountManagement.DirectoryRdnPrefixAttribute("CN")] public partial class AuthenticablePrincipal : System.DirectoryServices.AccountManagement.Principal { protected internal AuthenticablePrincipal(System.DirectoryServices.AccountManagement.PrincipalContext context) { } protected internal AuthenticablePrincipal(System.DirectoryServices.AccountManagement.PrincipalContext context, string samAccountName, string password, bool enabled) { } public System.DateTime? AccountExpirationDate { get { throw null; } set { } } public System.DateTime? AccountLockoutTime { get { throw null; } } public virtual System.DirectoryServices.AccountManagement.AdvancedFilters AdvancedSearchFilter { get { throw null; } } public bool AllowReversiblePasswordEncryption { get { throw null; } set { } } public int BadLogonCount { get { throw null; } } public System.Security.Cryptography.X509Certificates.X509Certificate2Collection Certificates { get { throw null; } } public bool DelegationPermitted { get { throw null; } set { } } public bool? Enabled { get { throw null; } set { } } public string HomeDirectory { get { throw null; } set { } } public string HomeDrive { get { throw null; } set { } } public System.DateTime? LastBadPasswordAttempt { get { throw null; } } public System.DateTime? LastLogon { get { throw null; } } public System.DateTime? LastPasswordSet { get { throw null; } } public bool PasswordNeverExpires { get { throw null; } set { } } public bool PasswordNotRequired { get { throw null; } set { } } public byte[] PermittedLogonTimes { get { throw null; } set { } } public System.DirectoryServices.AccountManagement.PrincipalValueCollection<string> PermittedWorkstations { get { throw null; } } public string ScriptPath { get { throw null; } set { } } public bool SmartcardLogonRequired { get { throw null; } set { } } public bool UserCannotChangePassword { get { throw null; } set { } } public void ChangePassword(string oldPassword, string newPassword) { } public void ExpirePasswordNow() { } public static System.DirectoryServices.AccountManagement.PrincipalSearchResult<System.DirectoryServices.AccountManagement.AuthenticablePrincipal> FindByBadPasswordAttempt(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DateTime time, System.DirectoryServices.AccountManagement.MatchType type) { throw null; } protected static System.DirectoryServices.AccountManagement.PrincipalSearchResult<T> FindByBadPasswordAttempt<T>(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DateTime time, System.DirectoryServices.AccountManagement.MatchType type) { throw null; } public static System.DirectoryServices.AccountManagement.PrincipalSearchResult<System.DirectoryServices.AccountManagement.AuthenticablePrincipal> FindByExpirationTime(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DateTime time, System.DirectoryServices.AccountManagement.MatchType type) { throw null; } protected static System.DirectoryServices.AccountManagement.PrincipalSearchResult<T> FindByExpirationTime<T>(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DateTime time, System.DirectoryServices.AccountManagement.MatchType type) { throw null; } public static System.DirectoryServices.AccountManagement.PrincipalSearchResult<System.DirectoryServices.AccountManagement.AuthenticablePrincipal> FindByLockoutTime(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DateTime time, System.DirectoryServices.AccountManagement.MatchType type) { throw null; } protected static System.DirectoryServices.AccountManagement.PrincipalSearchResult<T> FindByLockoutTime<T>(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DateTime time, System.DirectoryServices.AccountManagement.MatchType type) { throw null; } public static System.DirectoryServices.AccountManagement.PrincipalSearchResult<System.DirectoryServices.AccountManagement.AuthenticablePrincipal> FindByLogonTime(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DateTime time, System.DirectoryServices.AccountManagement.MatchType type) { throw null; } protected static System.DirectoryServices.AccountManagement.PrincipalSearchResult<T> FindByLogonTime<T>(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DateTime time, System.DirectoryServices.AccountManagement.MatchType type) { throw null; } public static System.DirectoryServices.AccountManagement.PrincipalSearchResult<System.DirectoryServices.AccountManagement.AuthenticablePrincipal> FindByPasswordSetTime(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DateTime time, System.DirectoryServices.AccountManagement.MatchType type) { throw null; } protected static System.DirectoryServices.AccountManagement.PrincipalSearchResult<T> FindByPasswordSetTime<T>(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DateTime time, System.DirectoryServices.AccountManagement.MatchType type) { throw null; } public bool IsAccountLockedOut() { throw null; } public void RefreshExpiredPassword() { } public void SetPassword(string newPassword) { } public void UnlockAccount() { } } [System.DirectoryServices.AccountManagement.DirectoryRdnPrefixAttribute("CN")] public partial class ComputerPrincipal : System.DirectoryServices.AccountManagement.AuthenticablePrincipal { public ComputerPrincipal(System.DirectoryServices.AccountManagement.PrincipalContext context) : base (default(System.DirectoryServices.AccountManagement.PrincipalContext)) { } public ComputerPrincipal(System.DirectoryServices.AccountManagement.PrincipalContext context, string samAccountName, string password, bool enabled) : base (default(System.DirectoryServices.AccountManagement.PrincipalContext)) { } public System.DirectoryServices.AccountManagement.PrincipalValueCollection<string> ServicePrincipalNames { get { throw null; } } public static new System.DirectoryServices.AccountManagement.PrincipalSearchResult<System.DirectoryServices.AccountManagement.ComputerPrincipal> FindByBadPasswordAttempt(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DateTime time, System.DirectoryServices.AccountManagement.MatchType type) { throw null; } public static new System.DirectoryServices.AccountManagement.PrincipalSearchResult<System.DirectoryServices.AccountManagement.ComputerPrincipal> FindByExpirationTime(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DateTime time, System.DirectoryServices.AccountManagement.MatchType type) { throw null; } public static new System.DirectoryServices.AccountManagement.ComputerPrincipal FindByIdentity(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DirectoryServices.AccountManagement.IdentityType identityType, string identityValue) { throw null; } public static new System.DirectoryServices.AccountManagement.ComputerPrincipal FindByIdentity(System.DirectoryServices.AccountManagement.PrincipalContext context, string identityValue) { throw null; } public static new System.DirectoryServices.AccountManagement.PrincipalSearchResult<System.DirectoryServices.AccountManagement.ComputerPrincipal> FindByLockoutTime(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DateTime time, System.DirectoryServices.AccountManagement.MatchType type) { throw null; } public static new System.DirectoryServices.AccountManagement.PrincipalSearchResult<System.DirectoryServices.AccountManagement.ComputerPrincipal> FindByLogonTime(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DateTime time, System.DirectoryServices.AccountManagement.MatchType type) { throw null; } public static new System.DirectoryServices.AccountManagement.PrincipalSearchResult<System.DirectoryServices.AccountManagement.ComputerPrincipal> FindByPasswordSetTime(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DateTime time, System.DirectoryServices.AccountManagement.MatchType type) { throw null; } } [System.FlagsAttribute] public enum ContextOptions { Negotiate = 1, SimpleBind = 2, SecureSocketLayer = 4, Signing = 8, Sealing = 16, ServerBind = 32, } public enum ContextType { Machine = 0, Domain = 1, ApplicationDirectory = 2, } [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=true)] public sealed partial class DirectoryObjectClassAttribute : System.Attribute { public DirectoryObjectClassAttribute(string objectClass) { } public System.DirectoryServices.AccountManagement.ContextType? Context { get { throw null; } } public string ObjectClass { get { throw null; } } } [System.AttributeUsageAttribute(System.AttributeTargets.Property, AllowMultiple=true)] public sealed partial class DirectoryPropertyAttribute : System.Attribute { public DirectoryPropertyAttribute(string schemaAttributeName) { } public System.DirectoryServices.AccountManagement.ContextType? Context { get { throw null; } set { } } public string SchemaAttributeName { get { throw null; } } } [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=true)] public sealed partial class DirectoryRdnPrefixAttribute : System.Attribute { public DirectoryRdnPrefixAttribute(string rdnPrefix) { } public System.DirectoryServices.AccountManagement.ContextType? Context { get { throw null; } } public string RdnPrefix { get { throw null; } } } [System.DirectoryServices.AccountManagement.DirectoryRdnPrefixAttribute("CN")] public partial class GroupPrincipal : System.DirectoryServices.AccountManagement.Principal { public GroupPrincipal(System.DirectoryServices.AccountManagement.PrincipalContext context) { } public GroupPrincipal(System.DirectoryServices.AccountManagement.PrincipalContext context, string samAccountName) { } public System.DirectoryServices.AccountManagement.GroupScope? GroupScope { get { throw null; } set { } } public bool? IsSecurityGroup { get { throw null; } set { } } public System.DirectoryServices.AccountManagement.PrincipalCollection Members { get { throw null; } } public override void Dispose() { } public static new System.DirectoryServices.AccountManagement.GroupPrincipal FindByIdentity(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DirectoryServices.AccountManagement.IdentityType identityType, string identityValue) { throw null; } public static new System.DirectoryServices.AccountManagement.GroupPrincipal FindByIdentity(System.DirectoryServices.AccountManagement.PrincipalContext context, string identityValue) { throw null; } public System.DirectoryServices.AccountManagement.PrincipalSearchResult<System.DirectoryServices.AccountManagement.Principal> GetMembers() { throw null; } public System.DirectoryServices.AccountManagement.PrincipalSearchResult<System.DirectoryServices.AccountManagement.Principal> GetMembers(bool recursive) { throw null; } } public enum GroupScope { Local = 0, Global = 1, Universal = 2, } public enum IdentityType { SamAccountName = 0, Name = 1, UserPrincipalName = 2, DistinguishedName = 3, Sid = 4, Guid = 5, } public enum MatchType { Equals = 0, NotEquals = 1, GreaterThan = 2, GreaterThanOrEquals = 3, LessThan = 4, LessThanOrEquals = 5, } public partial class MultipleMatchesException : System.DirectoryServices.AccountManagement.PrincipalException { public MultipleMatchesException() : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } protected MultipleMatchesException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } public MultipleMatchesException(string message) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } public MultipleMatchesException(string message, System.Exception innerException) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } } public partial class NoMatchingPrincipalException : System.DirectoryServices.AccountManagement.PrincipalException { public NoMatchingPrincipalException() : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } protected NoMatchingPrincipalException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } public NoMatchingPrincipalException(string message) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } public NoMatchingPrincipalException(string message, System.Exception innerException) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } } public partial class PasswordException : System.DirectoryServices.AccountManagement.PrincipalException { public PasswordException() : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } protected PasswordException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } public PasswordException(string message) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } public PasswordException(string message, System.Exception innerException) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } } public abstract partial class Principal : System.IDisposable { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] protected Principal() { } public System.DirectoryServices.AccountManagement.PrincipalContext Context { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] protected internal System.DirectoryServices.AccountManagement.PrincipalContext ContextRaw { get { throw null; } set { } } public System.DirectoryServices.AccountManagement.ContextType ContextType { get { throw null; } } public string Description { get { throw null; } set { } } public string DisplayName { get { throw null; } set { } } public string DistinguishedName { get { throw null; } } public System.Guid? Guid { get { throw null; } } public string Name { get { throw null; } set { } } public string SamAccountName { get { throw null; } set { } } public System.Security.Principal.SecurityIdentifier Sid { get { throw null; } } public string StructuralObjectClass { get { throw null; } } public string UserPrincipalName { get { throw null; } set { } } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] protected void CheckDisposedOrDeleted() { } public void Delete() { } public virtual void Dispose() { } public override bool Equals(object o) { throw null; } protected object[] ExtensionGet(string attribute) { throw null; } protected void ExtensionSet(string attribute, object value) { } public static System.DirectoryServices.AccountManagement.Principal FindByIdentity(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DirectoryServices.AccountManagement.IdentityType identityType, string identityValue) { throw null; } public static System.DirectoryServices.AccountManagement.Principal FindByIdentity(System.DirectoryServices.AccountManagement.PrincipalContext context, string identityValue) { throw null; } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] protected static System.DirectoryServices.AccountManagement.Principal FindByIdentityWithType(System.DirectoryServices.AccountManagement.PrincipalContext context, System.Type principalType, System.DirectoryServices.AccountManagement.IdentityType identityType, string identityValue) { throw null; } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] protected static System.DirectoryServices.AccountManagement.Principal FindByIdentityWithType(System.DirectoryServices.AccountManagement.PrincipalContext context, System.Type principalType, string identityValue) { throw null; } public System.DirectoryServices.AccountManagement.PrincipalSearchResult<System.DirectoryServices.AccountManagement.Principal> GetGroups() { throw null; } public System.DirectoryServices.AccountManagement.PrincipalSearchResult<System.DirectoryServices.AccountManagement.Principal> GetGroups(System.DirectoryServices.AccountManagement.PrincipalContext contextToQuery) { throw null; } public override int GetHashCode() { throw null; } public object GetUnderlyingObject() { throw null; } public System.Type GetUnderlyingObjectType() { throw null; } public bool IsMemberOf(System.DirectoryServices.AccountManagement.GroupPrincipal group) { throw null; } public bool IsMemberOf(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DirectoryServices.AccountManagement.IdentityType identityType, string identityValue) { throw null; } public void Save() { } public void Save(System.DirectoryServices.AccountManagement.PrincipalContext context) { } public override string ToString() { throw null; } } public partial class PrincipalCollection : System.Collections.Generic.ICollection<System.DirectoryServices.AccountManagement.Principal>, System.Collections.Generic.IEnumerable<System.DirectoryServices.AccountManagement.Principal>, System.Collections.ICollection, System.Collections.IEnumerable { internal PrincipalCollection() { } public int Count { get { throw null; } } public bool IsReadOnly { get { throw null; } } public bool IsSynchronized { get { throw null; } } public object SyncRoot { get { throw null; } } int System.Collections.ICollection.Count { get { throw null; } } bool System.Collections.ICollection.IsSynchronized { get { throw null; } } object System.Collections.ICollection.SyncRoot { get { throw null; } } public void Add(System.DirectoryServices.AccountManagement.ComputerPrincipal computer) { } public void Add(System.DirectoryServices.AccountManagement.GroupPrincipal group) { } public void Add(System.DirectoryServices.AccountManagement.Principal principal) { } public void Add(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DirectoryServices.AccountManagement.IdentityType identityType, string identityValue) { } public void Add(System.DirectoryServices.AccountManagement.UserPrincipal user) { } public void Clear() { } public bool Contains(System.DirectoryServices.AccountManagement.ComputerPrincipal computer) { throw null; } public bool Contains(System.DirectoryServices.AccountManagement.GroupPrincipal group) { throw null; } public bool Contains(System.DirectoryServices.AccountManagement.Principal principal) { throw null; } public bool Contains(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DirectoryServices.AccountManagement.IdentityType identityType, string identityValue) { throw null; } public bool Contains(System.DirectoryServices.AccountManagement.UserPrincipal user) { throw null; } public void CopyTo(System.DirectoryServices.AccountManagement.Principal[] array, int index) { } public System.Collections.Generic.IEnumerator<System.DirectoryServices.AccountManagement.Principal> GetEnumerator() { throw null; } public bool Remove(System.DirectoryServices.AccountManagement.ComputerPrincipal computer) { throw null; } public bool Remove(System.DirectoryServices.AccountManagement.GroupPrincipal group) { throw null; } public bool Remove(System.DirectoryServices.AccountManagement.Principal principal) { throw null; } public bool Remove(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DirectoryServices.AccountManagement.IdentityType identityType, string identityValue) { throw null; } public bool Remove(System.DirectoryServices.AccountManagement.UserPrincipal user) { throw null; } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } public partial class PrincipalContext : System.IDisposable { public PrincipalContext(System.DirectoryServices.AccountManagement.ContextType contextType) { } public PrincipalContext(System.DirectoryServices.AccountManagement.ContextType contextType, string name) { } public PrincipalContext(System.DirectoryServices.AccountManagement.ContextType contextType, string name, string container) { } public PrincipalContext(System.DirectoryServices.AccountManagement.ContextType contextType, string name, string container, System.DirectoryServices.AccountManagement.ContextOptions options) { } public PrincipalContext(System.DirectoryServices.AccountManagement.ContextType contextType, string name, string container, System.DirectoryServices.AccountManagement.ContextOptions options, string userName, string password) { } public PrincipalContext(System.DirectoryServices.AccountManagement.ContextType contextType, string name, string userName, string password) { } public PrincipalContext(System.DirectoryServices.AccountManagement.ContextType contextType, string name, string container, string userName, string password) { } public string ConnectedServer { get { throw null; } } public string Container { get { throw null; } } public System.DirectoryServices.AccountManagement.ContextType ContextType { get { throw null; } } public string Name { get { throw null; } } public System.DirectoryServices.AccountManagement.ContextOptions Options { get { throw null; } } public string UserName { get { throw null; } } public void Dispose() { } public bool ValidateCredentials(string userName, string password) { throw null; } public bool ValidateCredentials(string userName, string password, System.DirectoryServices.AccountManagement.ContextOptions options) { throw null; } } public abstract partial class PrincipalException : System.SystemException { protected PrincipalException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } } public partial class PrincipalExistsException : System.DirectoryServices.AccountManagement.PrincipalException { public PrincipalExistsException() : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } protected PrincipalExistsException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } public PrincipalExistsException(string message) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } public PrincipalExistsException(string message, System.Exception innerException) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } } public partial class PrincipalOperationException : System.DirectoryServices.AccountManagement.PrincipalException { public PrincipalOperationException() : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } protected PrincipalOperationException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } public PrincipalOperationException(string message) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } public PrincipalOperationException(string message, System.Exception innerException) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } public PrincipalOperationException(string message, System.Exception innerException, int errorCode) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } public PrincipalOperationException(string message, int errorCode) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } public int ErrorCode { get { throw null; } } public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } } public partial class PrincipalSearcher : System.IDisposable { public PrincipalSearcher() { } public PrincipalSearcher(System.DirectoryServices.AccountManagement.Principal queryFilter) { } public System.DirectoryServices.AccountManagement.PrincipalContext Context { get { throw null; } } public System.DirectoryServices.AccountManagement.Principal QueryFilter { get { throw null; } set { } } public virtual void Dispose() { } public System.DirectoryServices.AccountManagement.PrincipalSearchResult<System.DirectoryServices.AccountManagement.Principal> FindAll() { throw null; } public System.DirectoryServices.AccountManagement.Principal FindOne() { throw null; } public object GetUnderlyingSearcher() { throw null; } public System.Type GetUnderlyingSearcherType() { throw null; } } public partial class PrincipalSearchResult<T> : System.Collections.Generic.IEnumerable<T>, System.Collections.IEnumerable, System.IDisposable { internal PrincipalSearchResult() { } public void Dispose() { } public System.Collections.Generic.IEnumerator<T> GetEnumerator() { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } public partial class PrincipalServerDownException : System.DirectoryServices.AccountManagement.PrincipalException { public PrincipalServerDownException() : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } protected PrincipalServerDownException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } public PrincipalServerDownException(string message) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } public PrincipalServerDownException(string message, System.Exception innerException) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } public PrincipalServerDownException(string message, System.Exception innerException, int errorCode) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } public PrincipalServerDownException(string message, System.Exception innerException, int errorCode, string serverName) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } public PrincipalServerDownException(string message, int errorCode) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } } public partial class PrincipalValueCollection<T> : System.Collections.Generic.ICollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IList<T>, System.Collections.ICollection, System.Collections.IEnumerable, System.Collections.IList { internal PrincipalValueCollection() { } public int Count { get { throw null; } } public bool IsFixedSize { get { throw null; } } public bool IsReadOnly { get { throw null; } } public bool IsSynchronized { get { throw null; } } public T this[int index] { get { throw null; } set { } } public object SyncRoot { get { throw null; } } int System.Collections.ICollection.Count { get { throw null; } } bool System.Collections.ICollection.IsSynchronized { get { throw null; } } object System.Collections.ICollection.SyncRoot { get { throw null; } } bool System.Collections.IList.IsFixedSize { get { throw null; } } bool System.Collections.IList.IsReadOnly { get { throw null; } } object System.Collections.IList.this[int index] { get { throw null; } set { } } public void Add(T value) { } public void Clear() { } public bool Contains(T value) { throw null; } public void CopyTo(T[] array, int index) { } public System.Collections.Generic.IEnumerator<T> GetEnumerator() { throw null; } public int IndexOf(T value) { throw null; } public void Insert(int index, T value) { } public bool Remove(T value) { throw null; } public void RemoveAt(int index) { } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } int System.Collections.IList.Add(object value) { throw null; } void System.Collections.IList.Clear() { } bool System.Collections.IList.Contains(object value) { throw null; } int System.Collections.IList.IndexOf(object value) { throw null; } void System.Collections.IList.Insert(int index, object value) { } void System.Collections.IList.Remove(object value) { } void System.Collections.IList.RemoveAt(int index) { } } [System.DirectoryServices.AccountManagement.DirectoryRdnPrefixAttribute("CN")] public partial class UserPrincipal : System.DirectoryServices.AccountManagement.AuthenticablePrincipal { public UserPrincipal(System.DirectoryServices.AccountManagement.PrincipalContext context) : base (default(System.DirectoryServices.AccountManagement.PrincipalContext)) { } public UserPrincipal(System.DirectoryServices.AccountManagement.PrincipalContext context, string samAccountName, string password, bool enabled) : base (default(System.DirectoryServices.AccountManagement.PrincipalContext)) { } public override System.DirectoryServices.AccountManagement.AdvancedFilters AdvancedSearchFilter { get { throw null; } } public static System.DirectoryServices.AccountManagement.UserPrincipal Current { get { throw null; } } public string EmailAddress { get { throw null; } set { } } public string EmployeeId { get { throw null; } set { } } public string GivenName { get { throw null; } set { } } public string MiddleName { get { throw null; } set { } } public string Surname { get { throw null; } set { } } public string VoiceTelephoneNumber { get { throw null; } set { } } public static new System.DirectoryServices.AccountManagement.PrincipalSearchResult<System.DirectoryServices.AccountManagement.UserPrincipal> FindByBadPasswordAttempt(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DateTime time, System.DirectoryServices.AccountManagement.MatchType type) { throw null; } public static new System.DirectoryServices.AccountManagement.PrincipalSearchResult<System.DirectoryServices.AccountManagement.UserPrincipal> FindByExpirationTime(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DateTime time, System.DirectoryServices.AccountManagement.MatchType type) { throw null; } public static new System.DirectoryServices.AccountManagement.UserPrincipal FindByIdentity(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DirectoryServices.AccountManagement.IdentityType identityType, string identityValue) { throw null; } public static new System.DirectoryServices.AccountManagement.UserPrincipal FindByIdentity(System.DirectoryServices.AccountManagement.PrincipalContext context, string identityValue) { throw null; } public static new System.DirectoryServices.AccountManagement.PrincipalSearchResult<System.DirectoryServices.AccountManagement.UserPrincipal> FindByLockoutTime(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DateTime time, System.DirectoryServices.AccountManagement.MatchType type) { throw null; } public static new System.DirectoryServices.AccountManagement.PrincipalSearchResult<System.DirectoryServices.AccountManagement.UserPrincipal> FindByLogonTime(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DateTime time, System.DirectoryServices.AccountManagement.MatchType type) { throw null; } public static new System.DirectoryServices.AccountManagement.PrincipalSearchResult<System.DirectoryServices.AccountManagement.UserPrincipal> FindByPasswordSetTime(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DateTime time, System.DirectoryServices.AccountManagement.MatchType type) { throw null; } public System.DirectoryServices.AccountManagement.PrincipalSearchResult<System.DirectoryServices.AccountManagement.Principal> GetAuthorizationGroups() { throw null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // ------------------------------------------------------------------------------ // Changes to this file must follow the https://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.DirectoryServices.AccountManagement { public partial class AdvancedFilters { protected internal AdvancedFilters(System.DirectoryServices.AccountManagement.Principal p) { } public void AccountExpirationDate(System.DateTime expirationTime, System.DirectoryServices.AccountManagement.MatchType match) { } public void AccountLockoutTime(System.DateTime lockoutTime, System.DirectoryServices.AccountManagement.MatchType match) { } protected void AdvancedFilterSet(string attribute, object value, System.Type objectType, System.DirectoryServices.AccountManagement.MatchType mt) { } public void BadLogonCount(int badLogonCount, System.DirectoryServices.AccountManagement.MatchType match) { } public void LastBadPasswordAttempt(System.DateTime lastAttempt, System.DirectoryServices.AccountManagement.MatchType match) { } public void LastLogonTime(System.DateTime logonTime, System.DirectoryServices.AccountManagement.MatchType match) { } public void LastPasswordSetTime(System.DateTime passwordSetTime, System.DirectoryServices.AccountManagement.MatchType match) { } } [System.DirectoryServices.AccountManagement.DirectoryRdnPrefixAttribute("CN")] public partial class AuthenticablePrincipal : System.DirectoryServices.AccountManagement.Principal { protected internal AuthenticablePrincipal(System.DirectoryServices.AccountManagement.PrincipalContext context) { } protected internal AuthenticablePrincipal(System.DirectoryServices.AccountManagement.PrincipalContext context, string samAccountName, string password, bool enabled) { } public System.DateTime? AccountExpirationDate { get { throw null; } set { } } public System.DateTime? AccountLockoutTime { get { throw null; } } public virtual System.DirectoryServices.AccountManagement.AdvancedFilters AdvancedSearchFilter { get { throw null; } } public bool AllowReversiblePasswordEncryption { get { throw null; } set { } } public int BadLogonCount { get { throw null; } } public System.Security.Cryptography.X509Certificates.X509Certificate2Collection Certificates { get { throw null; } } public bool DelegationPermitted { get { throw null; } set { } } public bool? Enabled { get { throw null; } set { } } public string HomeDirectory { get { throw null; } set { } } public string HomeDrive { get { throw null; } set { } } public System.DateTime? LastBadPasswordAttempt { get { throw null; } } public System.DateTime? LastLogon { get { throw null; } } public System.DateTime? LastPasswordSet { get { throw null; } } public bool PasswordNeverExpires { get { throw null; } set { } } public bool PasswordNotRequired { get { throw null; } set { } } public byte[] PermittedLogonTimes { get { throw null; } set { } } public System.DirectoryServices.AccountManagement.PrincipalValueCollection<string> PermittedWorkstations { get { throw null; } } public string ScriptPath { get { throw null; } set { } } public bool SmartcardLogonRequired { get { throw null; } set { } } public bool UserCannotChangePassword { get { throw null; } set { } } public void ChangePassword(string oldPassword, string newPassword) { } public void ExpirePasswordNow() { } public static System.DirectoryServices.AccountManagement.PrincipalSearchResult<System.DirectoryServices.AccountManagement.AuthenticablePrincipal> FindByBadPasswordAttempt(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DateTime time, System.DirectoryServices.AccountManagement.MatchType type) { throw null; } protected static System.DirectoryServices.AccountManagement.PrincipalSearchResult<T> FindByBadPasswordAttempt<T>(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DateTime time, System.DirectoryServices.AccountManagement.MatchType type) { throw null; } public static System.DirectoryServices.AccountManagement.PrincipalSearchResult<System.DirectoryServices.AccountManagement.AuthenticablePrincipal> FindByExpirationTime(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DateTime time, System.DirectoryServices.AccountManagement.MatchType type) { throw null; } protected static System.DirectoryServices.AccountManagement.PrincipalSearchResult<T> FindByExpirationTime<T>(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DateTime time, System.DirectoryServices.AccountManagement.MatchType type) { throw null; } public static System.DirectoryServices.AccountManagement.PrincipalSearchResult<System.DirectoryServices.AccountManagement.AuthenticablePrincipal> FindByLockoutTime(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DateTime time, System.DirectoryServices.AccountManagement.MatchType type) { throw null; } protected static System.DirectoryServices.AccountManagement.PrincipalSearchResult<T> FindByLockoutTime<T>(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DateTime time, System.DirectoryServices.AccountManagement.MatchType type) { throw null; } public static System.DirectoryServices.AccountManagement.PrincipalSearchResult<System.DirectoryServices.AccountManagement.AuthenticablePrincipal> FindByLogonTime(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DateTime time, System.DirectoryServices.AccountManagement.MatchType type) { throw null; } protected static System.DirectoryServices.AccountManagement.PrincipalSearchResult<T> FindByLogonTime<T>(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DateTime time, System.DirectoryServices.AccountManagement.MatchType type) { throw null; } public static System.DirectoryServices.AccountManagement.PrincipalSearchResult<System.DirectoryServices.AccountManagement.AuthenticablePrincipal> FindByPasswordSetTime(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DateTime time, System.DirectoryServices.AccountManagement.MatchType type) { throw null; } protected static System.DirectoryServices.AccountManagement.PrincipalSearchResult<T> FindByPasswordSetTime<T>(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DateTime time, System.DirectoryServices.AccountManagement.MatchType type) { throw null; } public bool IsAccountLockedOut() { throw null; } public void RefreshExpiredPassword() { } public void SetPassword(string newPassword) { } public void UnlockAccount() { } } [System.DirectoryServices.AccountManagement.DirectoryRdnPrefixAttribute("CN")] public partial class ComputerPrincipal : System.DirectoryServices.AccountManagement.AuthenticablePrincipal { public ComputerPrincipal(System.DirectoryServices.AccountManagement.PrincipalContext context) : base (default(System.DirectoryServices.AccountManagement.PrincipalContext)) { } public ComputerPrincipal(System.DirectoryServices.AccountManagement.PrincipalContext context, string samAccountName, string password, bool enabled) : base (default(System.DirectoryServices.AccountManagement.PrincipalContext)) { } public System.DirectoryServices.AccountManagement.PrincipalValueCollection<string> ServicePrincipalNames { get { throw null; } } public static new System.DirectoryServices.AccountManagement.PrincipalSearchResult<System.DirectoryServices.AccountManagement.ComputerPrincipal> FindByBadPasswordAttempt(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DateTime time, System.DirectoryServices.AccountManagement.MatchType type) { throw null; } public static new System.DirectoryServices.AccountManagement.PrincipalSearchResult<System.DirectoryServices.AccountManagement.ComputerPrincipal> FindByExpirationTime(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DateTime time, System.DirectoryServices.AccountManagement.MatchType type) { throw null; } public static new System.DirectoryServices.AccountManagement.ComputerPrincipal FindByIdentity(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DirectoryServices.AccountManagement.IdentityType identityType, string identityValue) { throw null; } public static new System.DirectoryServices.AccountManagement.ComputerPrincipal FindByIdentity(System.DirectoryServices.AccountManagement.PrincipalContext context, string identityValue) { throw null; } public static new System.DirectoryServices.AccountManagement.PrincipalSearchResult<System.DirectoryServices.AccountManagement.ComputerPrincipal> FindByLockoutTime(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DateTime time, System.DirectoryServices.AccountManagement.MatchType type) { throw null; } public static new System.DirectoryServices.AccountManagement.PrincipalSearchResult<System.DirectoryServices.AccountManagement.ComputerPrincipal> FindByLogonTime(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DateTime time, System.DirectoryServices.AccountManagement.MatchType type) { throw null; } public static new System.DirectoryServices.AccountManagement.PrincipalSearchResult<System.DirectoryServices.AccountManagement.ComputerPrincipal> FindByPasswordSetTime(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DateTime time, System.DirectoryServices.AccountManagement.MatchType type) { throw null; } } [System.FlagsAttribute] public enum ContextOptions { Negotiate = 1, SimpleBind = 2, SecureSocketLayer = 4, Signing = 8, Sealing = 16, ServerBind = 32, } public enum ContextType { Machine = 0, Domain = 1, ApplicationDirectory = 2, } [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=true)] public sealed partial class DirectoryObjectClassAttribute : System.Attribute { public DirectoryObjectClassAttribute(string objectClass) { } public System.DirectoryServices.AccountManagement.ContextType? Context { get { throw null; } } public string ObjectClass { get { throw null; } } } [System.AttributeUsageAttribute(System.AttributeTargets.Property, AllowMultiple=true)] public sealed partial class DirectoryPropertyAttribute : System.Attribute { public DirectoryPropertyAttribute(string schemaAttributeName) { } public System.DirectoryServices.AccountManagement.ContextType? Context { get { throw null; } set { } } public string SchemaAttributeName { get { throw null; } } } [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=true)] public sealed partial class DirectoryRdnPrefixAttribute : System.Attribute { public DirectoryRdnPrefixAttribute(string rdnPrefix) { } public System.DirectoryServices.AccountManagement.ContextType? Context { get { throw null; } } public string RdnPrefix { get { throw null; } } } [System.DirectoryServices.AccountManagement.DirectoryRdnPrefixAttribute("CN")] public partial class GroupPrincipal : System.DirectoryServices.AccountManagement.Principal { public GroupPrincipal(System.DirectoryServices.AccountManagement.PrincipalContext context) { } public GroupPrincipal(System.DirectoryServices.AccountManagement.PrincipalContext context, string samAccountName) { } public System.DirectoryServices.AccountManagement.GroupScope? GroupScope { get { throw null; } set { } } public bool? IsSecurityGroup { get { throw null; } set { } } public System.DirectoryServices.AccountManagement.PrincipalCollection Members { get { throw null; } } public override void Dispose() { } public static new System.DirectoryServices.AccountManagement.GroupPrincipal FindByIdentity(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DirectoryServices.AccountManagement.IdentityType identityType, string identityValue) { throw null; } public static new System.DirectoryServices.AccountManagement.GroupPrincipal FindByIdentity(System.DirectoryServices.AccountManagement.PrincipalContext context, string identityValue) { throw null; } public System.DirectoryServices.AccountManagement.PrincipalSearchResult<System.DirectoryServices.AccountManagement.Principal> GetMembers() { throw null; } public System.DirectoryServices.AccountManagement.PrincipalSearchResult<System.DirectoryServices.AccountManagement.Principal> GetMembers(bool recursive) { throw null; } } public enum GroupScope { Local = 0, Global = 1, Universal = 2, } public enum IdentityType { SamAccountName = 0, Name = 1, UserPrincipalName = 2, DistinguishedName = 3, Sid = 4, Guid = 5, } public enum MatchType { Equals = 0, NotEquals = 1, GreaterThan = 2, GreaterThanOrEquals = 3, LessThan = 4, LessThanOrEquals = 5, } public partial class MultipleMatchesException : System.DirectoryServices.AccountManagement.PrincipalException { public MultipleMatchesException() : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } protected MultipleMatchesException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } public MultipleMatchesException(string message) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } public MultipleMatchesException(string message, System.Exception innerException) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } } public partial class NoMatchingPrincipalException : System.DirectoryServices.AccountManagement.PrincipalException { public NoMatchingPrincipalException() : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } protected NoMatchingPrincipalException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } public NoMatchingPrincipalException(string message) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } public NoMatchingPrincipalException(string message, System.Exception innerException) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } } public partial class PasswordException : System.DirectoryServices.AccountManagement.PrincipalException { public PasswordException() : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } protected PasswordException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } public PasswordException(string message) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } public PasswordException(string message, System.Exception innerException) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } } public abstract partial class Principal : System.IDisposable { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] protected Principal() { } public System.DirectoryServices.AccountManagement.PrincipalContext Context { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] protected internal System.DirectoryServices.AccountManagement.PrincipalContext ContextRaw { get { throw null; } set { } } public System.DirectoryServices.AccountManagement.ContextType ContextType { get { throw null; } } public string Description { get { throw null; } set { } } public string DisplayName { get { throw null; } set { } } public string DistinguishedName { get { throw null; } } public System.Guid? Guid { get { throw null; } } public string Name { get { throw null; } set { } } public string SamAccountName { get { throw null; } set { } } public System.Security.Principal.SecurityIdentifier Sid { get { throw null; } } public string StructuralObjectClass { get { throw null; } } public string UserPrincipalName { get { throw null; } set { } } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] protected void CheckDisposedOrDeleted() { } public void Delete() { } public virtual void Dispose() { } public override bool Equals(object o) { throw null; } protected object[] ExtensionGet(string attribute) { throw null; } protected void ExtensionSet(string attribute, object value) { } public static System.DirectoryServices.AccountManagement.Principal FindByIdentity(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DirectoryServices.AccountManagement.IdentityType identityType, string identityValue) { throw null; } public static System.DirectoryServices.AccountManagement.Principal FindByIdentity(System.DirectoryServices.AccountManagement.PrincipalContext context, string identityValue) { throw null; } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] protected static System.DirectoryServices.AccountManagement.Principal FindByIdentityWithType(System.DirectoryServices.AccountManagement.PrincipalContext context, System.Type principalType, System.DirectoryServices.AccountManagement.IdentityType identityType, string identityValue) { throw null; } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] protected static System.DirectoryServices.AccountManagement.Principal FindByIdentityWithType(System.DirectoryServices.AccountManagement.PrincipalContext context, System.Type principalType, string identityValue) { throw null; } public System.DirectoryServices.AccountManagement.PrincipalSearchResult<System.DirectoryServices.AccountManagement.Principal> GetGroups() { throw null; } public System.DirectoryServices.AccountManagement.PrincipalSearchResult<System.DirectoryServices.AccountManagement.Principal> GetGroups(System.DirectoryServices.AccountManagement.PrincipalContext contextToQuery) { throw null; } public override int GetHashCode() { throw null; } public object GetUnderlyingObject() { throw null; } public System.Type GetUnderlyingObjectType() { throw null; } public bool IsMemberOf(System.DirectoryServices.AccountManagement.GroupPrincipal group) { throw null; } public bool IsMemberOf(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DirectoryServices.AccountManagement.IdentityType identityType, string identityValue) { throw null; } public void Save() { } public void Save(System.DirectoryServices.AccountManagement.PrincipalContext context) { } public override string ToString() { throw null; } } public partial class PrincipalCollection : System.Collections.Generic.ICollection<System.DirectoryServices.AccountManagement.Principal>, System.Collections.Generic.IEnumerable<System.DirectoryServices.AccountManagement.Principal>, System.Collections.ICollection, System.Collections.IEnumerable { internal PrincipalCollection() { } public int Count { get { throw null; } } public bool IsReadOnly { get { throw null; } } public bool IsSynchronized { get { throw null; } } public object SyncRoot { get { throw null; } } int System.Collections.ICollection.Count { get { throw null; } } bool System.Collections.ICollection.IsSynchronized { get { throw null; } } object System.Collections.ICollection.SyncRoot { get { throw null; } } public void Add(System.DirectoryServices.AccountManagement.ComputerPrincipal computer) { } public void Add(System.DirectoryServices.AccountManagement.GroupPrincipal group) { } public void Add(System.DirectoryServices.AccountManagement.Principal principal) { } public void Add(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DirectoryServices.AccountManagement.IdentityType identityType, string identityValue) { } public void Add(System.DirectoryServices.AccountManagement.UserPrincipal user) { } public void Clear() { } public bool Contains(System.DirectoryServices.AccountManagement.ComputerPrincipal computer) { throw null; } public bool Contains(System.DirectoryServices.AccountManagement.GroupPrincipal group) { throw null; } public bool Contains(System.DirectoryServices.AccountManagement.Principal principal) { throw null; } public bool Contains(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DirectoryServices.AccountManagement.IdentityType identityType, string identityValue) { throw null; } public bool Contains(System.DirectoryServices.AccountManagement.UserPrincipal user) { throw null; } public void CopyTo(System.DirectoryServices.AccountManagement.Principal[] array, int index) { } public System.Collections.Generic.IEnumerator<System.DirectoryServices.AccountManagement.Principal> GetEnumerator() { throw null; } public bool Remove(System.DirectoryServices.AccountManagement.ComputerPrincipal computer) { throw null; } public bool Remove(System.DirectoryServices.AccountManagement.GroupPrincipal group) { throw null; } public bool Remove(System.DirectoryServices.AccountManagement.Principal principal) { throw null; } public bool Remove(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DirectoryServices.AccountManagement.IdentityType identityType, string identityValue) { throw null; } public bool Remove(System.DirectoryServices.AccountManagement.UserPrincipal user) { throw null; } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } public partial class PrincipalContext : System.IDisposable { public PrincipalContext(System.DirectoryServices.AccountManagement.ContextType contextType) { } public PrincipalContext(System.DirectoryServices.AccountManagement.ContextType contextType, string name) { } public PrincipalContext(System.DirectoryServices.AccountManagement.ContextType contextType, string name, string container) { } public PrincipalContext(System.DirectoryServices.AccountManagement.ContextType contextType, string name, string container, System.DirectoryServices.AccountManagement.ContextOptions options) { } public PrincipalContext(System.DirectoryServices.AccountManagement.ContextType contextType, string name, string container, System.DirectoryServices.AccountManagement.ContextOptions options, string userName, string password) { } public PrincipalContext(System.DirectoryServices.AccountManagement.ContextType contextType, string name, string userName, string password) { } public PrincipalContext(System.DirectoryServices.AccountManagement.ContextType contextType, string name, string container, string userName, string password) { } public string ConnectedServer { get { throw null; } } public string Container { get { throw null; } } public System.DirectoryServices.AccountManagement.ContextType ContextType { get { throw null; } } public string Name { get { throw null; } } public System.DirectoryServices.AccountManagement.ContextOptions Options { get { throw null; } } public string UserName { get { throw null; } } public void Dispose() { } public bool ValidateCredentials(string userName, string password) { throw null; } public bool ValidateCredentials(string userName, string password, System.DirectoryServices.AccountManagement.ContextOptions options) { throw null; } } public abstract partial class PrincipalException : System.SystemException { protected PrincipalException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } } public partial class PrincipalExistsException : System.DirectoryServices.AccountManagement.PrincipalException { public PrincipalExistsException() : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } protected PrincipalExistsException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } public PrincipalExistsException(string message) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } public PrincipalExistsException(string message, System.Exception innerException) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } } public partial class PrincipalOperationException : System.DirectoryServices.AccountManagement.PrincipalException { public PrincipalOperationException() : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } protected PrincipalOperationException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } public PrincipalOperationException(string message) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } public PrincipalOperationException(string message, System.Exception innerException) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } public PrincipalOperationException(string message, System.Exception innerException, int errorCode) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } public PrincipalOperationException(string message, int errorCode) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } public int ErrorCode { get { throw null; } } public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } } public partial class PrincipalSearcher : System.IDisposable { public PrincipalSearcher() { } public PrincipalSearcher(System.DirectoryServices.AccountManagement.Principal queryFilter) { } public System.DirectoryServices.AccountManagement.PrincipalContext Context { get { throw null; } } public System.DirectoryServices.AccountManagement.Principal QueryFilter { get { throw null; } set { } } public virtual void Dispose() { } public System.DirectoryServices.AccountManagement.PrincipalSearchResult<System.DirectoryServices.AccountManagement.Principal> FindAll() { throw null; } public System.DirectoryServices.AccountManagement.Principal FindOne() { throw null; } public object GetUnderlyingSearcher() { throw null; } public System.Type GetUnderlyingSearcherType() { throw null; } } public partial class PrincipalSearchResult<T> : System.Collections.Generic.IEnumerable<T>, System.Collections.IEnumerable, System.IDisposable { internal PrincipalSearchResult() { } public void Dispose() { } public System.Collections.Generic.IEnumerator<T> GetEnumerator() { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } public partial class PrincipalServerDownException : System.DirectoryServices.AccountManagement.PrincipalException { public PrincipalServerDownException() : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } protected PrincipalServerDownException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } public PrincipalServerDownException(string message) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } public PrincipalServerDownException(string message, System.Exception innerException) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } public PrincipalServerDownException(string message, System.Exception innerException, int errorCode) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } public PrincipalServerDownException(string message, System.Exception innerException, int errorCode, string serverName) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } public PrincipalServerDownException(string message, int errorCode) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } } public partial class PrincipalValueCollection<T> : System.Collections.Generic.ICollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IList<T>, System.Collections.ICollection, System.Collections.IEnumerable, System.Collections.IList { internal PrincipalValueCollection() { } public int Count { get { throw null; } } public bool IsFixedSize { get { throw null; } } public bool IsReadOnly { get { throw null; } } public bool IsSynchronized { get { throw null; } } public T this[int index] { get { throw null; } set { } } public object SyncRoot { get { throw null; } } int System.Collections.ICollection.Count { get { throw null; } } bool System.Collections.ICollection.IsSynchronized { get { throw null; } } object System.Collections.ICollection.SyncRoot { get { throw null; } } bool System.Collections.IList.IsFixedSize { get { throw null; } } bool System.Collections.IList.IsReadOnly { get { throw null; } } object System.Collections.IList.this[int index] { get { throw null; } set { } } public void Add(T value) { } public void Clear() { } public bool Contains(T value) { throw null; } public void CopyTo(T[] array, int index) { } public System.Collections.Generic.IEnumerator<T> GetEnumerator() { throw null; } public int IndexOf(T value) { throw null; } public void Insert(int index, T value) { } public bool Remove(T value) { throw null; } public void RemoveAt(int index) { } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } int System.Collections.IList.Add(object value) { throw null; } void System.Collections.IList.Clear() { } bool System.Collections.IList.Contains(object value) { throw null; } int System.Collections.IList.IndexOf(object value) { throw null; } void System.Collections.IList.Insert(int index, object value) { } void System.Collections.IList.Remove(object value) { } void System.Collections.IList.RemoveAt(int index) { } } [System.DirectoryServices.AccountManagement.DirectoryRdnPrefixAttribute("CN")] public partial class UserPrincipal : System.DirectoryServices.AccountManagement.AuthenticablePrincipal { public UserPrincipal(System.DirectoryServices.AccountManagement.PrincipalContext context) : base (default(System.DirectoryServices.AccountManagement.PrincipalContext)) { } public UserPrincipal(System.DirectoryServices.AccountManagement.PrincipalContext context, string samAccountName, string password, bool enabled) : base (default(System.DirectoryServices.AccountManagement.PrincipalContext)) { } public override System.DirectoryServices.AccountManagement.AdvancedFilters AdvancedSearchFilter { get { throw null; } } public static System.DirectoryServices.AccountManagement.UserPrincipal Current { get { throw null; } } public string EmailAddress { get { throw null; } set { } } public string EmployeeId { get { throw null; } set { } } public string GivenName { get { throw null; } set { } } public string MiddleName { get { throw null; } set { } } public string Surname { get { throw null; } set { } } public string VoiceTelephoneNumber { get { throw null; } set { } } public static new System.DirectoryServices.AccountManagement.PrincipalSearchResult<System.DirectoryServices.AccountManagement.UserPrincipal> FindByBadPasswordAttempt(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DateTime time, System.DirectoryServices.AccountManagement.MatchType type) { throw null; } public static new System.DirectoryServices.AccountManagement.PrincipalSearchResult<System.DirectoryServices.AccountManagement.UserPrincipal> FindByExpirationTime(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DateTime time, System.DirectoryServices.AccountManagement.MatchType type) { throw null; } public static new System.DirectoryServices.AccountManagement.UserPrincipal FindByIdentity(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DirectoryServices.AccountManagement.IdentityType identityType, string identityValue) { throw null; } public static new System.DirectoryServices.AccountManagement.UserPrincipal FindByIdentity(System.DirectoryServices.AccountManagement.PrincipalContext context, string identityValue) { throw null; } public static new System.DirectoryServices.AccountManagement.PrincipalSearchResult<System.DirectoryServices.AccountManagement.UserPrincipal> FindByLockoutTime(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DateTime time, System.DirectoryServices.AccountManagement.MatchType type) { throw null; } public static new System.DirectoryServices.AccountManagement.PrincipalSearchResult<System.DirectoryServices.AccountManagement.UserPrincipal> FindByLogonTime(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DateTime time, System.DirectoryServices.AccountManagement.MatchType type) { throw null; } public static new System.DirectoryServices.AccountManagement.PrincipalSearchResult<System.DirectoryServices.AccountManagement.UserPrincipal> FindByPasswordSetTime(System.DirectoryServices.AccountManagement.PrincipalContext context, System.DateTime time, System.DirectoryServices.AccountManagement.MatchType type) { throw null; } public System.DirectoryServices.AccountManagement.PrincipalSearchResult<System.DirectoryServices.AccountManagement.Principal> GetAuthorizationGroups() { throw null; } } }
-1
dotnet/runtime
66,474
Update repo CMake configuration to target /W4 by default
Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
AaronRobinsonMSFT
2022-03-10T20:20:31Z
2022-03-11T04:59:21Z
ba5207b0f4054fe8963fc3e87c2bd32907516961
5ce2b9f860f7a84c3059650bb67817d59d8f4953
Update repo CMake configuration to target /W4 by default. Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
./src/coreclr/pal/tests/palsuite/file_io/GetFileSizeEx/test1/GetFileSizeEx.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*===================================================================== ** ** Source: GetFileSizeEx.c (test 1) ** ** Purpose: Tests the PAL implementation of the GetFileSizeEx function. ** ** **===================================================================*/ #include <palsuite.h> void CleanUp_GetFileSizeEx_test1(HANDLE hFile) { if (CloseHandle(hFile) != TRUE) { Fail("GetFileSizeEx: ERROR -> Unable to close file \"%s\".\n" " Error is %d\n", szTextFile, GetLastError()); } if (!DeleteFileA(szTextFile)) { Fail("GetFileSizeEx: ERROR -> Unable to delete file \"%s\".\n" " Error is %d\n", szTextFile, GetLastError()); } } void CheckFileSize_GetFileSizeEx_test1(HANDLE hFile, DWORD dwOffset, DWORD dwHighOrder) { DWORD dwRc = 0; DWORD dwError = 0; LARGE_INTEGER qwFileSize; dwRc = SetFilePointer(hFile, dwOffset, (PLONG)&dwHighOrder, FILE_BEGIN); if (dwRc == INVALID_SET_FILE_POINTER) { Trace("GetFileSizeEx: ERROR -> Call to SetFilePointer failed with %ld.\n", GetLastError()); CleanUp_GetFileSizeEx_test1(hFile); Fail(""); } else { if (!SetEndOfFile(hFile)) { dwError = GetLastError(); CleanUp_GetFileSizeEx_test1(hFile); if (dwError == 112) { Fail("GetFileSizeEx: ERROR -> SetEndOfFile failed due to lack of " "disk space\n"); } else { Fail("GetFileSizeEx: ERROR -> SetEndOfFile call failed " "with error %ld\n", dwError); } } else { GetFileSizeEx(hFile, &qwFileSize); if ((qwFileSize.u.LowPart != dwOffset) || (qwFileSize.u.HighPart != dwHighOrder)) { CleanUp_GetFileSizeEx_test1(hFile); Fail("GetFileSizeEx: ERROR -> File sizes do not match up.\n"); } } } } PALTEST(file_io_GetFileSizeEx_test1_paltest_getfilesizeex_test1, "file_io/GetFileSizeEx/test1/paltest_getfilesizeex_test1") { HANDLE hFile = NULL; BOOL bRc = FALSE; DWORD lpNumberOfBytesWritten; LARGE_INTEGER qwFileSize; LARGE_INTEGER qwFileSize2; char * data = "1234567890"; qwFileSize.QuadPart = 0; qwFileSize2.QuadPart = 0; if (0 != PAL_Initialize(argc,argv)) { return FAIL; } /* test on a null file */ bRc = GetFileSizeEx(NULL, &qwFileSize); if (bRc != FALSE) { Fail("GetFileSizeEx: ERROR -> Returned status as TRUE for " "a null handle.\n"); } /* test on an invalid file */ bRc = GetFileSizeEx(INVALID_HANDLE_VALUE, &qwFileSize); if (bRc != FALSE) { Fail("GetFileSizeEx: ERROR -> Returned status as TRUE for " "an invalid handle.\n"); } /* create a test file */ hFile = CreateFile(szTextFile, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if(hFile == INVALID_HANDLE_VALUE) { Fail("GetFileSizeEx: ERROR -> Unable to create file \"%s\".\n", szTextFile); } /* give the file a size */ CheckFileSize_GetFileSizeEx_test1(hFile, 256, 0); /* make the file large using the high order option */ CheckFileSize_GetFileSizeEx_test1(hFile, 256, 1); /* set the file size to zero */ CheckFileSize_GetFileSizeEx_test1(hFile, 0, 0); /* test if file size changes by writing to it. */ /* get file size */ GetFileSizeEx(hFile, &qwFileSize); /* test writing to the file */ if(WriteFile(hFile, data, strlen(data), &lpNumberOfBytesWritten, NULL)==0) { Trace("GetFileSizeEx: ERROR -> Call to WriteFile failed with %ld.\n", GetLastError()); CleanUp_GetFileSizeEx_test1(hFile); Fail(""); } /* make sure the buffer flushed.*/ if(FlushFileBuffers(hFile)==0) { Trace("GetFileSizeEx: ERROR -> Call to FlushFileBuffers failed with %ld.\n", GetLastError()); CleanUp_GetFileSizeEx_test1(hFile); Fail(""); } /* get file size after writing some chars */ GetFileSizeEx(hFile, &qwFileSize2); if((qwFileSize2.QuadPart-qwFileSize.QuadPart) !=strlen(data)) { CleanUp_GetFileSizeEx_test1(hFile); Fail("GetFileSizeEx: ERROR -> File size did not increase properly after.\n" "writing %d chars\n", strlen(data)); } CleanUp_GetFileSizeEx_test1(hFile); PAL_Terminate(); return PASS; }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*===================================================================== ** ** Source: GetFileSizeEx.c (test 1) ** ** Purpose: Tests the PAL implementation of the GetFileSizeEx function. ** ** **===================================================================*/ #include <palsuite.h> void CleanUp_GetFileSizeEx_test1(HANDLE hFile) { if (CloseHandle(hFile) != TRUE) { Fail("GetFileSizeEx: ERROR -> Unable to close file \"%s\".\n" " Error is %d\n", szTextFile, GetLastError()); } if (!DeleteFileA(szTextFile)) { Fail("GetFileSizeEx: ERROR -> Unable to delete file \"%s\".\n" " Error is %d\n", szTextFile, GetLastError()); } } void CheckFileSize_GetFileSizeEx_test1(HANDLE hFile, DWORD dwOffset, DWORD dwHighOrder) { DWORD dwRc = 0; DWORD dwError = 0; LARGE_INTEGER qwFileSize; dwRc = SetFilePointer(hFile, dwOffset, (PLONG)&dwHighOrder, FILE_BEGIN); if (dwRc == INVALID_SET_FILE_POINTER) { Trace("GetFileSizeEx: ERROR -> Call to SetFilePointer failed with %ld.\n", GetLastError()); CleanUp_GetFileSizeEx_test1(hFile); Fail(""); } else { if (!SetEndOfFile(hFile)) { dwError = GetLastError(); CleanUp_GetFileSizeEx_test1(hFile); if (dwError == 112) { Fail("GetFileSizeEx: ERROR -> SetEndOfFile failed due to lack of " "disk space\n"); } else { Fail("GetFileSizeEx: ERROR -> SetEndOfFile call failed " "with error %ld\n", dwError); } } else { GetFileSizeEx(hFile, &qwFileSize); if ((qwFileSize.u.LowPart != dwOffset) || (qwFileSize.u.HighPart != dwHighOrder)) { CleanUp_GetFileSizeEx_test1(hFile); Fail("GetFileSizeEx: ERROR -> File sizes do not match up.\n"); } } } } PALTEST(file_io_GetFileSizeEx_test1_paltest_getfilesizeex_test1, "file_io/GetFileSizeEx/test1/paltest_getfilesizeex_test1") { HANDLE hFile = NULL; BOOL bRc = FALSE; DWORD lpNumberOfBytesWritten; LARGE_INTEGER qwFileSize; LARGE_INTEGER qwFileSize2; char * data = "1234567890"; qwFileSize.QuadPart = 0; qwFileSize2.QuadPart = 0; if (0 != PAL_Initialize(argc,argv)) { return FAIL; } /* test on a null file */ bRc = GetFileSizeEx(NULL, &qwFileSize); if (bRc != FALSE) { Fail("GetFileSizeEx: ERROR -> Returned status as TRUE for " "a null handle.\n"); } /* test on an invalid file */ bRc = GetFileSizeEx(INVALID_HANDLE_VALUE, &qwFileSize); if (bRc != FALSE) { Fail("GetFileSizeEx: ERROR -> Returned status as TRUE for " "an invalid handle.\n"); } /* create a test file */ hFile = CreateFile(szTextFile, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if(hFile == INVALID_HANDLE_VALUE) { Fail("GetFileSizeEx: ERROR -> Unable to create file \"%s\".\n", szTextFile); } /* give the file a size */ CheckFileSize_GetFileSizeEx_test1(hFile, 256, 0); /* make the file large using the high order option */ CheckFileSize_GetFileSizeEx_test1(hFile, 256, 1); /* set the file size to zero */ CheckFileSize_GetFileSizeEx_test1(hFile, 0, 0); /* test if file size changes by writing to it. */ /* get file size */ GetFileSizeEx(hFile, &qwFileSize); /* test writing to the file */ if(WriteFile(hFile, data, strlen(data), &lpNumberOfBytesWritten, NULL)==0) { Trace("GetFileSizeEx: ERROR -> Call to WriteFile failed with %ld.\n", GetLastError()); CleanUp_GetFileSizeEx_test1(hFile); Fail(""); } /* make sure the buffer flushed.*/ if(FlushFileBuffers(hFile)==0) { Trace("GetFileSizeEx: ERROR -> Call to FlushFileBuffers failed with %ld.\n", GetLastError()); CleanUp_GetFileSizeEx_test1(hFile); Fail(""); } /* get file size after writing some chars */ GetFileSizeEx(hFile, &qwFileSize2); if((qwFileSize2.QuadPart-qwFileSize.QuadPart) !=strlen(data)) { CleanUp_GetFileSizeEx_test1(hFile); Fail("GetFileSizeEx: ERROR -> File size did not increase properly after.\n" "writing %d chars\n", strlen(data)); } CleanUp_GetFileSizeEx_test1(hFile); PAL_Terminate(); return PASS; }
-1
dotnet/runtime
66,474
Update repo CMake configuration to target /W4 by default
Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
AaronRobinsonMSFT
2022-03-10T20:20:31Z
2022-03-11T04:59:21Z
ba5207b0f4054fe8963fc3e87c2bd32907516961
5ce2b9f860f7a84c3059650bb67817d59d8f4953
Update repo CMake configuration to target /W4 by default. Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
./src/libraries/System.Private.Xml.Linq/tests/SDMSample/SDMMisc.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Xml; using System.Xml.Linq; using Xunit; namespace XDocumentTests.SDMSample { public class SDM_Misc { [Fact] public void NodeTypes() { XDocument document = new XDocument(); XElement element = new XElement("x"); XText text = new XText("text-value"); XComment comment = new XComment("comment"); XProcessingInstruction processingInstruction = new XProcessingInstruction("target", "data"); Assert.Equal(XmlNodeType.Document, document.NodeType); Assert.Equal(XmlNodeType.Element, element.NodeType); Assert.Equal(XmlNodeType.Text, text.NodeType); Assert.Equal(XmlNodeType.Comment, comment.NodeType); Assert.Equal(XmlNodeType.ProcessingInstruction, processingInstruction.NodeType); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Xml; using System.Xml.Linq; using Xunit; namespace XDocumentTests.SDMSample { public class SDM_Misc { [Fact] public void NodeTypes() { XDocument document = new XDocument(); XElement element = new XElement("x"); XText text = new XText("text-value"); XComment comment = new XComment("comment"); XProcessingInstruction processingInstruction = new XProcessingInstruction("target", "data"); Assert.Equal(XmlNodeType.Document, document.NodeType); Assert.Equal(XmlNodeType.Element, element.NodeType); Assert.Equal(XmlNodeType.Text, text.NodeType); Assert.Equal(XmlNodeType.Comment, comment.NodeType); Assert.Equal(XmlNodeType.ProcessingInstruction, processingInstruction.NodeType); } } }
-1
dotnet/runtime
66,474
Update repo CMake configuration to target /W4 by default
Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
AaronRobinsonMSFT
2022-03-10T20:20:31Z
2022-03-11T04:59:21Z
ba5207b0f4054fe8963fc3e87c2bd32907516961
5ce2b9f860f7a84c3059650bb67817d59d8f4953
Update repo CMake configuration to target /W4 by default. Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
./src/libraries/System.Runtime/tests/System/Reflection/NullabilityInfoContextTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO.Enumeration; using System.Runtime.Serialization; using System.Text.RegularExpressions; using Microsoft.DotNet.RemoteExecutor; using Xunit; namespace System.Reflection.Tests { public class NullabilityInfoContextTests { private static readonly NullabilityInfoContext nullabilityContext = new NullabilityInfoContext(); private static readonly Type testType = typeof(TypeWithNotNullContext); private static readonly Type genericType = typeof(GenericTest<TypeWithNotNullContext>); private static readonly Type stringType = typeof(string); private static readonly BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static; public static IEnumerable<object[]> FieldTestData() { yield return new object[] { "FieldNullable", NullabilityState.Nullable, NullabilityState.Nullable, typeof(string) }; yield return new object[] { "FieldUnknown", NullabilityState.Unknown, NullabilityState.Unknown, typeof(TypeWithNotNullContext) }; yield return new object[] { "FieldNonNullable", NullabilityState.NotNull, NullabilityState.NotNull, typeof(NullabilityInfoContextTests) }; yield return new object[] { "FieldValueTypeUnknown", NullabilityState.NotNull, NullabilityState.NotNull, typeof(int) }; yield return new object[] { "FieldValueTypeNotNull", NullabilityState.NotNull, NullabilityState.NotNull, typeof(double) }; yield return new object[] { "FieldValueTypeNullable", NullabilityState.Nullable, NullabilityState.Nullable, typeof(int?) }; yield return new object[] { "FieldDisallowNull", NullabilityState.Nullable, NullabilityState.NotNull, typeof(string) }; yield return new object[] { "FieldAllowNull", NullabilityState.NotNull, NullabilityState.Nullable, typeof(string) }; yield return new object[] { "FieldDisallowNull2", NullabilityState.Nullable, NullabilityState.NotNull, typeof(string) }; yield return new object[] { "FieldAllowNull2", NullabilityState.NotNull, NullabilityState.NotNull, typeof(string) }; yield return new object[] { "FieldNotNull", NullabilityState.NotNull, NullabilityState.Nullable, typeof(string) }; yield return new object[] { "FieldMaybeNull", NullabilityState.Nullable, NullabilityState.NotNull, typeof(string) }; yield return new object[] { "FieldMaybeNull2", NullabilityState.NotNull, NullabilityState.NotNull, typeof(string) }; yield return new object[] { "FieldNotNull2", NullabilityState.NotNull, NullabilityState.Nullable, typeof(string) }; } [Theory] [MemberData(nameof(FieldTestData))] public void FieldTest(string fieldName, NullabilityState readState, NullabilityState writeState, Type type) { FieldInfo field = testType.GetField(fieldName, flags); NullabilityInfo nullability = nullabilityContext.Create(field); Assert.Equal(readState, nullability.ReadState); Assert.Equal(writeState, nullability.WriteState); Assert.Equal(type, nullability.Type); Assert.Empty(nullability.GenericTypeArguments); Assert.Null(nullability.ElementType); } public static IEnumerable<object[]> EventTestData() { yield return new object[] { "EventNullable", NullabilityState.Nullable, NullabilityState.Nullable, typeof(EventHandler) }; yield return new object[] { "EventUnknown", NullabilityState.Unknown, NullabilityState.Unknown, typeof(EventHandler) }; yield return new object[] { "EventNotNull", NullabilityState.NotNull, NullabilityState.NotNull, typeof(EventHandler) }; } [Theory] [MemberData(nameof(EventTestData))] public void EventTest(string eventName, NullabilityState readState, NullabilityState writeState, Type type) { EventInfo @event = testType.GetEvent(eventName); NullabilityInfo nullability = nullabilityContext.Create(@event); Assert.Equal(readState, nullability.ReadState); Assert.Equal(writeState, nullability.WriteState); Assert.Equal(type, nullability.Type); Assert.Empty(nullability.GenericTypeArguments); Assert.Null(nullability.ElementType); } public static IEnumerable<object[]> PropertyTestData() { yield return new object[] { "PropertyNullable", NullabilityState.Nullable, NullabilityState.Nullable, typeof(TypeWithNotNullContext) }; yield return new object[] { "PropertyNullableReadOnly", NullabilityState.Nullable, NullabilityState.Unknown, typeof(TypeWithNotNullContext) }; yield return new object[] { "PropertyUnknown", NullabilityState.Unknown, NullabilityState.Unknown, typeof(string) }; yield return new object[] { "PropertyNonNullable", NullabilityState.NotNull, NullabilityState.NotNull, typeof(NullabilityInfoContextTests) }; yield return new object[] { "PropertyValueTypeUnknown", NullabilityState.NotNull, NullabilityState.NotNull, typeof(short) }; yield return new object[] { "PropertyValueType", NullabilityState.NotNull, NullabilityState.NotNull, typeof(float) }; yield return new object[] { "PropertyValueTypeNullable", NullabilityState.Nullable, NullabilityState.Nullable, typeof(long?) }; yield return new object[] { "PropertyValueTypeDisallowNull", NullabilityState.Nullable, NullabilityState.NotNull, typeof(int?) }; yield return new object[] { "PropertyValueTypeAllowNull", NullabilityState.NotNull, NullabilityState.NotNull, typeof(byte) }; yield return new object[] { "PropertyValueTypeNotNull", NullabilityState.NotNull, NullabilityState.Nullable, typeof(int?) }; yield return new object[] { "PropertyValueTypeMaybeNull", NullabilityState.NotNull, NullabilityState.NotNull, typeof(byte) }; yield return new object[] { "PropertyDisallowNull", NullabilityState.Nullable, NullabilityState.NotNull, typeof(string) }; yield return new object[] { "PropertyAllowNull", NullabilityState.NotNull, NullabilityState.Nullable, typeof(string) }; yield return new object[] { "PropertyDisallowNull2", NullabilityState.Nullable, NullabilityState.NotNull, typeof(string) }; yield return new object[] { "PropertyAllowNull2", NullabilityState.NotNull, NullabilityState.NotNull, typeof(string) }; yield return new object[] { "PropertyNotNull", NullabilityState.NotNull, NullabilityState.Nullable, typeof(string) }; yield return new object[] { "PropertyMaybeNull", NullabilityState.Nullable, NullabilityState.NotNull, typeof(string) }; yield return new object[] { "PropertyMaybeNull2", NullabilityState.NotNull, NullabilityState.NotNull, typeof(string) }; yield return new object[] { "PropertyNotNull2", NullabilityState.NotNull, NullabilityState.Nullable, typeof(string) }; yield return new object[] { "Item", NullabilityState.Nullable, NullabilityState.NotNull, typeof(string) }; } [Theory] [MemberData(nameof(PropertyTestData))] public void PropertyTest(string propertyName, NullabilityState readState, NullabilityState writeState, Type type) { PropertyInfo property = testType.GetProperty(propertyName, flags); NullabilityInfo nullability = nullabilityContext.Create(property); Assert.Equal(readState, nullability.ReadState); Assert.Equal(readState, nullabilityContext.Create(property.GetMethod.ReturnParameter).ReadState); Assert.Equal(writeState, nullability.WriteState); if (property.SetMethod != null) { Assert.Equal(writeState, nullabilityContext.Create(property.SetMethod.GetParameters()[0]).WriteState); } Assert.Equal(type, nullability.Type); Assert.Empty(nullability.GenericTypeArguments); Assert.Null(nullability.ElementType); } public static IEnumerable<object[]> ArrayPropertyTestData() { yield return new object[] { "PropertyArrayUnknown", NullabilityState.Unknown, NullabilityState.Unknown }; yield return new object[] { "PropertyArrayNullNull", NullabilityState.Nullable, NullabilityState.Nullable }; yield return new object[] { "PropertyArrayNullNon", NullabilityState.Nullable, NullabilityState.NotNull }; yield return new object[] { "PropertyArrayNonNull", NullabilityState.NotNull, NullabilityState.Nullable }; yield return new object[] { "PropertyArrayNonNon", NullabilityState.NotNull, NullabilityState.NotNull }; } [Theory] [SkipOnMono("Nullability attributes trimmed on Mono")] [MemberData(nameof(ArrayPropertyTestData))] public void ArrayPropertyTest(string propertyName, NullabilityState elementState, NullabilityState propertyState) { PropertyInfo property = testType.GetProperty(propertyName, flags); NullabilityInfo nullability = nullabilityContext.Create(property); Assert.Equal(propertyState, nullability.ReadState); Assert.NotNull(nullability.ElementType); Assert.Equal(elementState, nullability.ElementType.ReadState); Assert.Empty(nullability.GenericTypeArguments); } public static IEnumerable<object[]> GenericArrayPropertyTestData() { yield return new object[] { "PropertyArrayUnknown", NullabilityState.Unknown, NullabilityState.Unknown }; yield return new object[] { "PropertyArrayNullNull", NullabilityState.Nullable, NullabilityState.Nullable }; // T?[]? PropertyArrayNullNull { get; set; } yield return new object[] { "PropertyArrayNullNon", NullabilityState.Nullable, NullabilityState.NotNull }; // T?[] PropertyArrayNullNon { get; set; } yield return new object[] { "PropertyArrayNonNull", NullabilityState.Nullable, NullabilityState.Nullable }; // T[]? PropertyArrayNonNull { get; set; } yield return new object[] { "PropertyArrayNonNon", NullabilityState.Nullable, NullabilityState.NotNull }; // T[] PropertyArrayNonNon { get; set; } } [Theory] [SkipOnMono("Nullability attributes trimmed on Mono")] [MemberData(nameof(GenericArrayPropertyTestData))] public void GenericArrayPropertyTest(string propertyName, NullabilityState elementState, NullabilityState propertyState) { PropertyInfo property = genericType.GetProperty(propertyName, flags); NullabilityInfo nullability = nullabilityContext.Create(property); Assert.Equal(propertyState, nullability.ReadState); Assert.NotNull(nullability.ElementType); Assert.Equal(elementState, nullability.ElementType.ReadState); Assert.Empty(nullability.GenericTypeArguments); } public static IEnumerable<object[]> JaggedArrayPropertyTestData() { yield return new object[] { "PropertyJaggedArrayUnknown", NullabilityState.Unknown, NullabilityState.Unknown, NullabilityState.Unknown }; yield return new object[] { "PropertyJaggedArrayNullNullNull", NullabilityState.Nullable, NullabilityState.Nullable, NullabilityState.Nullable }; yield return new object[] { "PropertyJaggedArrayNullNullNon", NullabilityState.Nullable, NullabilityState.Nullable, NullabilityState.NotNull }; yield return new object[] { "PropertyJaggedArrayNullNonNull", NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.Nullable }; yield return new object[] { "PropertyJaggedArrayNonNullNull", NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.Nullable }; yield return new object[] { "PropertyJaggedArrayNullNonNon", NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.NotNull }; yield return new object[] { "PropertyJaggedArrayNonNonNull", NullabilityState.NotNull, NullabilityState.NotNull, NullabilityState.Nullable }; } [Theory] [SkipOnMono("Nullability attributes trimmed on Mono")] [MemberData(nameof(JaggedArrayPropertyTestData))] public void JaggedArrayPropertyTest(string propertyName, NullabilityState innermodtElementState, NullabilityState elementState, NullabilityState propertyState) { PropertyInfo property = testType.GetProperty(propertyName, flags); NullabilityInfo nullability = nullabilityContext.Create(property); Assert.Equal(propertyState, nullability.ReadState); Assert.NotNull(nullability.ElementType); Assert.Equal(elementState, nullability.ElementType.ReadState); Assert.NotNull(nullability.ElementType.ElementType); Assert.Equal(innermodtElementState, nullability.ElementType.ElementType.ReadState); Assert.Empty(nullability.GenericTypeArguments); } public static IEnumerable<object[]> TuplePropertyTestData() { yield return new object[] { "PropertyTupleUnknown", NullabilityState.Unknown, NullabilityState.Unknown, NullabilityState.Unknown, NullabilityState.Unknown }; yield return new object[] { "PropertyTupleNullNullNullNull", NullabilityState.Nullable, NullabilityState.Nullable, NullabilityState.Nullable, NullabilityState.Nullable }; yield return new object[] { "PropertyTupleNonNullNonNon", NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.NotNull }; yield return new object[] { "PropertyTupleNullNonNullNull", NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.Nullable }; yield return new object[] { "PropertyTupleNonNullNonNull", NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.Nullable }; yield return new object[] { "PropertyTupleNonNonNonNon", NullabilityState.NotNull, NullabilityState.NotNull, NullabilityState.NotNull, NullabilityState.NotNull }; } [Theory] [SkipOnMono("Nullability attributes trimmed on Mono")] [MemberData(nameof(TuplePropertyTestData))] public void TuplePropertyTest(string propertyName, NullabilityState genericParam1, NullabilityState genericParam2, NullabilityState genericParam3, NullabilityState propertyState) { PropertyInfo property = testType.GetProperty(propertyName, flags); NullabilityInfo nullability = nullabilityContext.Create(property); Assert.Equal(propertyState, nullability.ReadState); Assert.NotEmpty(nullability.GenericTypeArguments); Assert.Equal(genericParam1, nullability.GenericTypeArguments[0].ReadState); Assert.Equal(genericParam2, nullability.GenericTypeArguments[1].ReadState); Assert.Equal(genericParam3, nullability.GenericTypeArguments[2].ReadState); Assert.Null(nullability.ElementType); } public static IEnumerable<object[]> GenericTuplePropertyTestData() { yield return new object[] { "PropertyTupleUnknown", NullabilityState.Unknown, NullabilityState.Unknown, NullabilityState.Unknown, NullabilityState.Unknown }; yield return new object[] { "PropertyTupleNullNullNullNull", NullabilityState.Nullable, NullabilityState.Nullable, NullabilityState.Nullable, NullabilityState.Nullable }; // Tuple<T?, string?, string?>? yield return new object[] { "PropertyTupleNonNullNonNon", NullabilityState.Nullable, NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.NotNull }; // Tuple<T, T?, string> yield return new object[] { "PropertyTupleNullNonNullNull", NullabilityState.Nullable, NullabilityState.Nullable, NullabilityState.Nullable, NullabilityState.Nullable }; // Tuple<string?, T, T?>? yield return new object[] { "PropertyTupleNonNullNonNull", NullabilityState.Nullable, NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.Nullable }; // Tuple<T, string?, string>? yield return new object[] { "PropertyTupleNonNonNonNon", NullabilityState.NotNull, NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.NotNull }; // Tuple<string, string, T> } [Theory] [SkipOnMono("Nullability attributes trimmed on Mono")] [MemberData(nameof(GenericTuplePropertyTestData))] public void GenericTuplePropertyTest(string propertyName, NullabilityState genericParam1, NullabilityState genericParam2, NullabilityState genericParam3, NullabilityState propertyState) { PropertyInfo property = genericType.GetProperty(propertyName, flags); NullabilityInfo nullability = nullabilityContext.Create(property); Assert.Equal(propertyState, nullability.ReadState); Assert.NotEmpty(nullability.GenericTypeArguments); Assert.Equal(genericParam1, nullability.GenericTypeArguments[0].ReadState); Assert.Equal(genericParam2, nullability.GenericTypeArguments[1].ReadState); Assert.Equal(genericParam3, nullability.GenericTypeArguments[2].ReadState); Assert.Null(nullability.ElementType); } public static IEnumerable<object[]> DictionaryPropertyTestData() { yield return new object[] { "PropertyDictionaryUnknown", NullabilityState.Unknown, NullabilityState.Unknown, NullabilityState.Unknown, NullabilityState.Unknown }; yield return new object[] { "PropertyDictionaryNullNullNullNon", NullabilityState.Nullable, NullabilityState.Nullable, NullabilityState.Nullable, NullabilityState.NotNull }; yield return new object[] { "PropertyDictionaryNonNullNonNull", NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.Nullable }; yield return new object[] { "PropertyDictionaryNullNonNonNull", NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.NotNull, NullabilityState.Nullable }; yield return new object[] { "PropertyDictionaryNonNullNonNon", NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.NotNull }; yield return new object[] { "PropertyDictionaryNonNonNonNull", NullabilityState.NotNull, NullabilityState.NotNull, NullabilityState.NotNull, NullabilityState.Nullable }; yield return new object[] { "PropertyDictionaryNonNonNonNon", NullabilityState.NotNull, NullabilityState.NotNull, NullabilityState.NotNull, NullabilityState.NotNull }; } [Theory] [SkipOnMono("Nullability attributes trimmed on Mono")] [MemberData(nameof(DictionaryPropertyTestData))] public void DictionaryPropertyTest(string propertyName, NullabilityState keyState, NullabilityState valueElement, NullabilityState valueState, NullabilityState propertyState) { PropertyInfo property = testType.GetProperty(propertyName, flags); NullabilityInfo nullability = nullabilityContext.Create(property); Assert.Equal(propertyState, nullability.ReadState); Assert.NotEmpty(nullability.GenericTypeArguments); Assert.Equal(keyState, nullability.GenericTypeArguments[0].ReadState); Assert.Equal(valueState, nullability.GenericTypeArguments[1].ReadState); Assert.Equal(valueElement, nullability.GenericTypeArguments[1].ElementType.ReadState); Assert.Null(nullability.ElementType); } public static IEnumerable<object[]> GenericDictionaryPropertyTestData() { yield return new object[] { "PropertyDictionaryUnknown", NullabilityState.Unknown, NullabilityState.Unknown, NullabilityState.Unknown, NullabilityState.Unknown }; yield return new object[] { "PropertyDictionaryNullNullNullNon", NullabilityState.Nullable, NullabilityState.Nullable, NullabilityState.Nullable, NullabilityState.NotNull }; // IDictionary<T?, string?[]?> PropertyDictionaryNullNullNullNon { get; set; } yield return new object[] { "PropertyDictionaryNonNullNonNull", NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.Nullable }; // IDictionary<Type, T?[]>? PropertyDictionaryNonNullNonNull yield return new object[] { "PropertyDictionaryNullNonNonNull", NullabilityState.Nullable, NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.Nullable }; // IDictionary<T?, T[]>? PropertyDictionaryNullNonNonNull yield return new object[] { "PropertyDictionaryNonNullNonNon", NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.NotNull }; // IDictionary<Type, T?[]> PropertyDictionaryNonNullNonNon yield return new object[] { "PropertyDictionaryNonNonNonNull", NullabilityState.Nullable, NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.Nullable }; // IDictionary<T, T[]>? PropertyDictionaryNonNonNonNull yield return new object[] { "PropertyDictionaryNonNonNonNon", NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.NotNull, NullabilityState.NotNull }; // IDictionary<T, string[]> PropertyDictionaryNonNonNonNon } [Theory] [SkipOnMono("Nullability attributes trimmed on Mono")] [MemberData(nameof(GenericDictionaryPropertyTestData))] public void GenericDictionaryPropertyTest(string propertyName, NullabilityState keyState, NullabilityState valueElement, NullabilityState valueState, NullabilityState propertyState) { PropertyInfo property = genericType.GetProperty(propertyName, flags); NullabilityInfo nullability = nullabilityContext.Create(property); Assert.Equal(propertyState, nullability.ReadState); Assert.NotEmpty(nullability.GenericTypeArguments); Assert.Equal(keyState, nullability.GenericTypeArguments[0].ReadState); Assert.Equal(valueState, nullability.GenericTypeArguments[1].ReadState); Assert.Equal(valueElement, nullability.GenericTypeArguments[1].ElementType.ReadState); Assert.Null(nullability.ElementType); } [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] public void VerifyIsSupportedThrows() { RemoteInvokeOptions options = new RemoteInvokeOptions(); options.RuntimeConfigurationOptions.Add("System.Reflection.NullabilityInfoContext.IsSupported", "false"); using RemoteInvokeHandle remoteHandle = RemoteExecutor.Invoke(() => { FieldInfo field = testType.GetField("FieldNullable", flags); Assert.Throws<InvalidOperationException>(() => nullabilityContext.Create(field)); EventInfo @event = testType.GetEvent("EventNullable"); Assert.Throws<InvalidOperationException>(() => nullabilityContext.Create(@event)); PropertyInfo property = testType.GetProperty("PropertyNullable", flags); Assert.Throws<InvalidOperationException>(() => nullabilityContext.Create(property)); MethodInfo method = testType.GetMethod("MethodNullNonNullNonNon", flags); Assert.Throws<InvalidOperationException>(() => nullabilityContext.Create(method.ReturnParameter)); }, options); } [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] public void VerifyIsSupportedWorks() { RemoteInvokeOptions options = new RemoteInvokeOptions(); options.RuntimeConfigurationOptions.Add("System.Reflection.NullabilityInfoContext.IsSupported", "true"); using RemoteInvokeHandle remoteHandle = RemoteExecutor.Invoke(() => { FieldInfo field = testType.GetField("FieldNullable", flags); NullabilityInfo nullability = nullabilityContext.Create(field); Assert.Equal(NullabilityState.Nullable, nullability.ReadState); Assert.Equal(NullabilityState.Nullable, nullability.WriteState); }, options); } public static IEnumerable<object[]> GenericPropertyReferenceTypeTestData() { yield return new object[] { "PropertyNullable", NullabilityState.Nullable, NullabilityState.Nullable, typeof(TypeWithNotNullContext) }; yield return new object[] { "PropertyUnknown", NullabilityState.Unknown, NullabilityState.Unknown, typeof(TypeWithNotNullContext) }; yield return new object[] { "PropertyNonNullable", NullabilityState.Nullable, NullabilityState.Nullable, typeof(TypeWithNotNullContext) }; yield return new object[] { "PropertyDisallowNull", NullabilityState.Nullable, NullabilityState.NotNull, typeof(TypeWithNotNullContext) }; yield return new object[] { "PropertyAllowNull", NullabilityState.Nullable, NullabilityState.Nullable, typeof(TypeWithNotNullContext) }; yield return new object[] { "PropertyMaybeNull", NullabilityState.Nullable, NullabilityState.Nullable, typeof(TypeWithNotNullContext) }; } #nullable enable [Theory] [MemberData(nameof(GenericPropertyReferenceTypeTestData))] public void GenericPropertyReferenceTypeTest(string fieldName, NullabilityState readState, NullabilityState writeState, Type type) { PropertyInfo property = typeof(GenericTest<TypeWithNotNullContext?>).GetProperty(fieldName, flags)!; NullabilityInfo nullability = nullabilityContext.Create(property); Assert.Equal(readState, nullability.ReadState); Assert.Equal(writeState, nullability.WriteState); Assert.Equal(type, nullability.Type); Assert.Empty(nullability.GenericTypeArguments); Assert.Null(nullability.ElementType); property = typeof(GenericTest<TypeWithNotNullContext>).GetProperty(fieldName, flags)!; nullability = nullabilityContext.Create(property); Assert.Equal(readState, nullability.ReadState); Assert.Equal(writeState, nullability.WriteState); Assert.Equal(type, nullability.Type); property = typeof(GenericTest<>).GetProperty(fieldName, flags)!; nullability = nullabilityContext.Create(property); Assert.Equal(readState, nullability.ReadState); Assert.Equal(writeState, nullability.WriteState); } public static IEnumerable<object[]> GenericFieldReferenceTypeTestData() { yield return new object[] { "FieldNullable", NullabilityState.Nullable, NullabilityState.Nullable, typeof(TypeWithNotNullContext) }; yield return new object[] { "FieldUnknown", NullabilityState.Unknown, NullabilityState.Unknown, typeof(TypeWithNotNullContext) }; yield return new object[] { "FieldNonNullable", NullabilityState.Nullable, NullabilityState.Nullable, typeof(TypeWithNotNullContext) }; yield return new object[] { "FieldDisallowNull", NullabilityState.Nullable, NullabilityState.NotNull, typeof(TypeWithNotNullContext) }; yield return new object[] { "FieldAllowNull", NullabilityState.Nullable, NullabilityState.Nullable, typeof(TypeWithNotNullContext) }; yield return new object[] { "FieldMaybeNull", NullabilityState.Nullable, NullabilityState.Nullable, typeof(TypeWithNotNullContext) }; } [Theory] [MemberData(nameof(GenericFieldReferenceTypeTestData))] public void GenericFieldReferenceTypeTest(string fieldName, NullabilityState readState, NullabilityState writeState, Type type) { FieldInfo field = typeof(GenericTest<TypeWithNotNullContext?>).GetField(fieldName, flags)!; NullabilityInfo nullability = nullabilityContext.Create(field); Assert.Equal(readState, nullability.ReadState); Assert.Equal(writeState, nullability.WriteState); Assert.Equal(type, nullability.Type); Assert.Empty(nullability.GenericTypeArguments); Assert.Null(nullability.ElementType); field = typeof(GenericTest<TypeWithNotNullContext>).GetField(fieldName, flags)!; nullability = nullabilityContext.Create(field); Assert.Equal(readState, nullability.ReadState); Assert.Equal(writeState, nullability.WriteState); Assert.Equal(type, nullability.Type); field = typeof(GenericTest<>).GetField(fieldName, flags)!; nullability = nullabilityContext.Create(field); Assert.Equal(readState, nullability.ReadState); Assert.Equal(writeState, nullability.WriteState); } public static IEnumerable<object[]> GenericFieldValueTypeTestData() { yield return new object[] { "FieldNullable", typeof(int) }; yield return new object[] { "FieldUnknown", typeof(int) }; yield return new object[] { "FieldNonNullable", typeof(int) }; yield return new object[] { "FieldDisallowNull", typeof(int) }; yield return new object[] { "FieldAllowNull", typeof(int) }; yield return new object[] { "FieldMaybeNull", typeof(int) }; yield return new object[] { "FieldNotNull", typeof(int) }; } [Theory] [MemberData(nameof(GenericFieldValueTypeTestData))] public void GenericFieldValueTypeTest(string fieldName, Type type) { FieldInfo field = typeof(GenericTest<int>).GetField(fieldName, flags)!; NullabilityInfo nullability = nullabilityContext.Create(field); Assert.Equal(NullabilityState.NotNull, nullability.ReadState); Assert.Equal(NullabilityState.NotNull, nullability.WriteState); Assert.Equal(type, nullability.Type); } public static IEnumerable<object[]> GenericFieldNullableValueTypeTestData() { yield return new object[] { "FieldNullable", NullabilityState.Nullable, NullabilityState.Nullable, typeof(int?) }; yield return new object[] { "FieldUnknown", NullabilityState.Nullable, NullabilityState.Nullable, typeof(int?) }; yield return new object[] { "FieldNonNullable", NullabilityState.Nullable, NullabilityState.Nullable, typeof(int?) }; yield return new object[] { "FieldDisallowNull", NullabilityState.Nullable, NullabilityState.NotNull, typeof(int?) }; yield return new object[] { "FieldAllowNull", NullabilityState.Nullable, NullabilityState.Nullable, typeof(int?) }; yield return new object[] { "FieldMaybeNull", NullabilityState.Nullable, NullabilityState.Nullable, typeof(int?) }; yield return new object[] { "FieldNotNull", NullabilityState.NotNull, NullabilityState.Nullable, typeof(int?) }; } [Theory] [MemberData(nameof(GenericFieldNullableValueTypeTestData))] public void GenericFieldNullableValueTypeTest(string fieldName, NullabilityState readState, NullabilityState writeState, Type type) { FieldInfo field = typeof(GenericTest<int?>).GetField(fieldName, flags)!; NullabilityInfo nullability = nullabilityContext.Create(field); Assert.Equal(readState, nullability.ReadState); Assert.Equal(writeState, nullability.WriteState); Assert.Equal(type, nullability.Type); } public static IEnumerable<object[]> GenericNotNullConstraintFieldsTestData() { yield return new object[] { "FieldNullable", NullabilityState.Nullable, NullabilityState.Nullable, typeof(string) }; yield return new object[] { "FieldUnknown", NullabilityState.Unknown, NullabilityState.Unknown, typeof(string) }; yield return new object[] { "FieldNullableEnabled", NullabilityState.NotNull, NullabilityState.NotNull, typeof(string) }; } [Theory] [MemberData(nameof(GenericNotNullConstraintFieldsTestData))] public void GenericNotNullConstraintFieldsTest(string fieldName, NullabilityState readState, NullabilityState writeState, Type type) { FieldInfo field = typeof(GenericTestConstrainedNotNull<string>).GetField(fieldName, flags)!; NullabilityInfo nullability = nullabilityContext.Create(field); Assert.Equal(readState, nullability.ReadState); Assert.Equal(writeState, nullability.WriteState); Assert.Equal(type, nullability.Type); } public static IEnumerable<object[]> GenericNotnullConstraintPropertiesTestData() { yield return new object[] { "PropertyNullable", NullabilityState.Nullable, NullabilityState.Nullable, typeof(string) }; yield return new object[] { "PropertyUnknown", NullabilityState.Unknown, NullabilityState.Unknown, typeof(string) }; yield return new object[] { "PropertyNullableEnabled", NullabilityState.NotNull, NullabilityState.NotNull, typeof(string) }; } [Theory] [MemberData(nameof(GenericNotnullConstraintPropertiesTestData))] public void GenericNotNullConstraintPropertiesTest(string propertyName, NullabilityState readState, NullabilityState writeState, Type type) { PropertyInfo property = typeof(GenericTestConstrainedNotNull<string>).GetProperty(propertyName, flags)!; NullabilityInfo nullability = nullabilityContext.Create(property); Assert.Equal(readState, nullability.ReadState); Assert.Equal(writeState, nullability.WriteState); Assert.Equal(type, nullability.Type); } public static IEnumerable<object[]> GenericStructConstraintFieldsTestData() { yield return new object[] { "FieldNullable", NullabilityState.Nullable, NullabilityState.Nullable, typeof(int?) }; yield return new object[] { "FieldUnknown", NullabilityState.NotNull, NullabilityState.NotNull, typeof(int) }; yield return new object[] { "FieldNullableEnabled", NullabilityState.NotNull, NullabilityState.NotNull, typeof(int) }; } [Theory] [MemberData(nameof(GenericStructConstraintFieldsTestData))] public void GenericStructConstraintFieldsTest(string fieldName, NullabilityState readState, NullabilityState writeState, Type type) { FieldInfo field = typeof(GenericTestConstrainedStruct<int>).GetField(fieldName, flags)!; NullabilityInfo nullability = nullabilityContext.Create(field); Assert.Equal(readState, nullability.ReadState); Assert.Equal(writeState, nullability.WriteState); Assert.Equal(type, nullability.Type); } public static IEnumerable<object[]> GenericStructConstraintPropertiesTestData() { yield return new object[] { "PropertyNullable", NullabilityState.Nullable, NullabilityState.Nullable, typeof(int?) }; yield return new object[] { "PropertyUnknown", NullabilityState.NotNull, NullabilityState.NotNull, typeof(int) }; yield return new object[] { "PropertyNullableEnabled", NullabilityState.NotNull, NullabilityState.NotNull, typeof(int) }; } [Theory] [MemberData(nameof(GenericStructConstraintPropertiesTestData))] public void GenericStructConstraintPropertiesTest(string propertyName, NullabilityState readState, NullabilityState writeState, Type type) { PropertyInfo property = typeof(GenericTestConstrainedStruct<int>).GetProperty(propertyName, flags)!; NullabilityInfo nullability = nullabilityContext.Create(property); Assert.Equal(readState, nullability.ReadState); Assert.Equal(writeState, nullability.WriteState); Assert.Equal(type, nullability.Type); } [Fact] [SkipOnMono("Nullability attributes trimmed on Mono")] public void GenericListTest() { Type listNullable = typeof(List<string?>); MethodInfo addNullable = listNullable.GetMethod("Add")!; NullabilityInfo nullability = nullabilityContext.Create(addNullable.GetParameters()[0]); Assert.Equal(NullabilityState.Nullable, nullability.ReadState); Assert.Equal(NullabilityState.Nullable, nullability.WriteState); Assert.Equal(typeof(string), nullability.Type); Type listNotNull = typeof(List<string>); MethodInfo addNotNull = listNotNull.GetMethod("Add")!; nullability = nullabilityContext.Create(addNotNull.GetParameters()[0]); Assert.Equal(NullabilityState.Nullable, nullability.ReadState); Assert.Equal(typeof(string), nullability.Type); Type listOpen = typeof(List<>); MethodInfo addOpen = listOpen.GetMethod("Add")!; nullability = nullabilityContext.Create(addOpen.GetParameters()[0]); Assert.Equal(NullabilityState.Nullable, nullability.ReadState); } [Fact] [SkipOnMono("Nullability attributes trimmed on Mono")] public void GenericListAndDictionaryFieldTest() { Type typeNullable = typeof(GenericTest<string?>); FieldInfo listOfTNullable = typeNullable.GetField("FieldListOfT")!; NullabilityInfo listNullability = nullabilityContext.Create(listOfTNullable); Assert.Equal(NullabilityState.Nullable, listNullability.GenericTypeArguments[0].ReadState); Assert.Equal(typeof(string), listNullability.GenericTypeArguments[0].Type); FieldInfo dictStringToTNullable = typeNullable.GetField("FieldDictionaryStringToT")!; NullabilityInfo dictNullability = nullabilityContext.Create(dictStringToTNullable); Assert.Equal(NullabilityState.NotNull, dictNullability.GenericTypeArguments[0].ReadState); Assert.Equal(NullabilityState.Nullable, dictNullability.GenericTypeArguments[1].ReadState); Assert.Equal(typeof(string), dictNullability.GenericTypeArguments[1].Type); Type typeNonNull = typeof(GenericTest<string>); FieldInfo listOfTNotNull = typeNonNull.GetField("FieldListOfT")!; listNullability = nullabilityContext.Create(listOfTNotNull); Assert.Equal(NullabilityState.Nullable, listNullability.GenericTypeArguments[0].ReadState); Assert.Equal(typeof(string), listNullability.GenericTypeArguments[0].Type); FieldInfo dictStringToTNotNull = typeNonNull.GetField("FieldDictionaryStringToT")!; dictNullability = nullabilityContext.Create(dictStringToTNotNull); Assert.Equal(NullabilityState.NotNull, dictNullability.GenericTypeArguments[0].ReadState); Assert.Equal(NullabilityState.Nullable, dictNullability.GenericTypeArguments[1].ReadState); Assert.Equal(typeof(string), dictNullability.GenericTypeArguments[1].Type); Type typeOpen = typeof(GenericTest<>); FieldInfo listOfTOpen = typeOpen.GetField("FieldListOfT")!; listNullability = nullabilityContext.Create(listOfTOpen); Assert.Equal(NullabilityState.Nullable, listNullability.GenericTypeArguments[0].ReadState); // Assert.Equal(typeof(T), listNullability.TypeArguments[0].Type); FieldInfo dictStringToTOpen = typeOpen.GetField("FieldDictionaryStringToT")!; dictNullability = nullabilityContext.Create(dictStringToTOpen); Assert.Equal(NullabilityState.NotNull, dictNullability.GenericTypeArguments[0].ReadState); Assert.Equal(NullabilityState.Nullable, dictNullability.GenericTypeArguments[1].ReadState); } public static IEnumerable<object[]> MethodReturnParameterTestData() { yield return new object[] { "MethodReturnsUnknown", NullabilityState.Unknown, NullabilityState.Unknown }; yield return new object[] { "MethodReturnsNullNon", NullabilityState.Nullable, NullabilityState.NotNull }; yield return new object[] { "MethodReturnsNullNull", NullabilityState.Nullable, NullabilityState.Nullable }; yield return new object[] { "MethodReturnsNonNull", NullabilityState.NotNull, NullabilityState.Nullable }; yield return new object[] { "MethodReturnsNonNotNull", NullabilityState.NotNull, NullabilityState.NotNull }; yield return new object[] { "MethodReturnsNonMaybeNull", NullabilityState.NotNull, NullabilityState.Nullable }; yield return new object[] { "MethodReturnsNonNon", NullabilityState.NotNull, NullabilityState.NotNull }; } [Theory] [SkipOnMono("Nullability attributes trimmed on Mono")] [MemberData(nameof(MethodReturnParameterTestData))] public void MethodReturnParameterTest(string methodName, NullabilityState elementState, NullabilityState readState) { MethodInfo method = testType.GetMethod(methodName, flags)!; NullabilityInfo nullability = nullabilityContext.Create(method.ReturnParameter); Assert.Equal(readState, nullability.ReadState); //Assert.Equal(readState, nullability.WriteState); Assert.NotNull(nullability.ElementType); Assert.Equal(elementState, nullability.ElementType!.ReadState); Assert.Empty(nullability.GenericTypeArguments); } public static IEnumerable<object[]> MethodReturnsTupleTestData() { // public Tuple<string?, string>? MethodReturnsTupleNullNonNull() => null; yield return new object[] { "MethodReturnsTupleNullNonNull", NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.Nullable }; // public Tuple<string?, int> MethodReturnsTupleNullNonNot() => null! yield return new object[] { "MethodReturnsTupleNullNonNot", NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.NotNull }; // public (int?, string)? MethodReturnsValueTupleNullNonNull() => null; yield return new object[] { "MethodReturnsValueTupleNullNonNull", NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.Nullable }; // public (string?, string) MethodReturnsValueTupleNullNonNon() => (null, string.Empty); yield return new object[] { "MethodReturnsValueTupleNullNonNon", NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.NotNull }; } [Theory] [SkipOnMono("Nullability attributes trimmed on Mono")] [MemberData(nameof(MethodReturnsTupleTestData))] public void MethodReturnsTupleTest(string methodName, NullabilityState param1, NullabilityState param2, NullabilityState readState) { MethodInfo method = testType.GetMethod(methodName, flags)!; NullabilityInfo nullability = nullabilityContext.Create(method.ReturnParameter); Assert.Equal(readState, nullability.ReadState); Assert.Null(nullability.ElementType); Assert.Equal(param1, nullability.GenericTypeArguments[0].ReadState); Assert.Equal(param2, nullability.GenericTypeArguments[1].ReadState); } public static IEnumerable<object[]> MethodGenericReturnParameterTestData() { yield return new object[] { "MethodReturnsUnknown", NullabilityState.Unknown, NullabilityState.Unknown }; yield return new object[] { "MethodReturnsGeneric", NullabilityState.Nullable, NullabilityState.Unknown }; yield return new object[] { "MethodReturnsNullGeneric", NullabilityState.Nullable, NullabilityState.Unknown }; yield return new object[] { "MethodReturnsGenericNotNull", NullabilityState.NotNull, NullabilityState.Unknown }; yield return new object[] { "MethodReturnsGenericMaybeNull", NullabilityState.Nullable, NullabilityState.Unknown }; yield return new object[] { "MethodNonNullListNullGeneric", NullabilityState.NotNull, NullabilityState.Nullable }; yield return new object[] { "MethodNullListNonNullGeneric", NullabilityState.Nullable, NullabilityState.Nullable }; } [Theory] [SkipOnMono("Nullability attributes trimmed on Mono")] [MemberData(nameof(MethodGenericReturnParameterTestData))] public void MethodGenericReturnParameterTest(string methodName, NullabilityState readState, NullabilityState elementState) { MethodInfo method = typeof(GenericTest<TypeWithNotNullContext?>).GetMethod(methodName, flags)!; NullabilityInfo nullability = nullabilityContext.Create(method.ReturnParameter); Assert.Equal(readState, nullability.ReadState); if (nullability.GenericTypeArguments.Length > 0) { Assert.Equal(elementState, nullability.GenericTypeArguments[0].ReadState); } } public static IEnumerable<object[]> MethodParametersTestData() { yield return new object[] { "MethodParametersUnknown", NullabilityState.Unknown, NullabilityState.Unknown, NullabilityState.Unknown, NullabilityState.Unknown, NullabilityState.Unknown }; yield return new object[] { "MethodNullNonNullNonNon", NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.NotNull }; yield return new object[] { "MethodNonNullNonNullNotNull", NullabilityState.NotNull, NullabilityState.NotNull, NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.NotNull }; yield return new object[] { "MethodNullNonNullNullNon", NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.Nullable, NullabilityState.NotNull }; yield return new object[] { "MethodAllowNullNonNonNonNull", NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.NotNull, NullabilityState.NotNull, NullabilityState.Nullable }; } [Theory] [SkipOnMono("Nullability attributes trimmed on Mono")] [MemberData(nameof(MethodParametersTestData))] public void MethodParametersTest(string methodName, NullabilityState stringState, NullabilityState dictKey, NullabilityState dictValueElement, NullabilityState dictValue, NullabilityState dictionaryState) { ParameterInfo[] parameters = testType.GetMethod(methodName, flags)!.GetParameters(); NullabilityInfo stringNullability = nullabilityContext.Create(parameters[0]); NullabilityInfo dictionaryNullability = nullabilityContext.Create(parameters[1]); Assert.Equal(stringState, stringNullability.WriteState); Assert.Equal(dictionaryState, dictionaryNullability.ReadState); Assert.NotEmpty(dictionaryNullability.GenericTypeArguments); Assert.Equal(dictKey, dictionaryNullability.GenericTypeArguments[0].ReadState); Assert.Equal(dictValue, dictionaryNullability.GenericTypeArguments[1].ReadState); Assert.Equal(dictValueElement, dictionaryNullability.GenericTypeArguments[1].ElementType!.ReadState); Assert.Null(dictionaryNullability.ElementType); } public static IEnumerable<object[]> MethodGenericParametersTestData() { yield return new object[] { "MethodParametersUnknown", NullabilityState.Unknown, NullabilityState.Unknown, NullabilityState.Unknown, NullabilityState.Unknown }; yield return new object[] { "MethodArgsNullGenericNullDictValueGeneric", NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.Nullable }; yield return new object[] { "MethodArgsGenericDictValueNullGeneric", NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.NotNull }; } [Theory] [SkipOnMono("Nullability attributes trimmed on Mono")] [MemberData(nameof(MethodGenericParametersTestData))] public void MethodGenericParametersTest(string methodName, NullabilityState param1State, NullabilityState dictKey, NullabilityState dictValue, NullabilityState dictionaryState) { ParameterInfo[] parameters = typeof(GenericTest<TypeWithNotNullContext>).GetMethod(methodName, flags)!.GetParameters(); NullabilityInfo stringNullability = nullabilityContext.Create(parameters[0]); NullabilityInfo dictionaryNullability = nullabilityContext.Create(parameters[1]); Assert.Equal(param1State, stringNullability.WriteState); Assert.Equal(dictionaryState, dictionaryNullability.ReadState); Assert.NotEmpty(dictionaryNullability.GenericTypeArguments); Assert.Equal(dictKey, dictionaryNullability.GenericTypeArguments[0].ReadState); Assert.Equal(dictValue, dictionaryNullability.GenericTypeArguments[1].ReadState); } public static IEnumerable<object[]> StringTypeTestData() { yield return new object[] { "Format", NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.Nullable, new Type[] { typeof(string), typeof(object), typeof(object) } }; yield return new object[] { "ReplaceCore", NullabilityState.Unknown, NullabilityState.Unknown, NullabilityState.Unknown, new Type[] { typeof(string), typeof(string), typeof(CompareInfo), typeof(CompareOptions) } }; yield return new object[] { "Join", NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.NotNull, new Type[] { typeof(string), typeof(String?[]), typeof(int), typeof(int) } }; } [Theory] [SkipOnMono("Nullability attributes trimmed on Mono")] [MemberData(nameof(StringTypeTestData))] public void NullablePublicOnlyStringTypeTest(string methodName, NullabilityState param1State, NullabilityState param2State, NullabilityState param3State, Type[] types) { ParameterInfo[] parameters = stringType.GetMethod(methodName, flags, types)!.GetParameters(); NullabilityInfo param1 = nullabilityContext.Create(parameters[0]); NullabilityInfo param2 = nullabilityContext.Create(parameters[1]); NullabilityInfo param3 = nullabilityContext.Create(parameters[2]); Assert.Equal(param1State, param1.ReadState); Assert.Equal(param2State, param2.ReadState); Assert.Equal(param3State, param3.ReadState); if (param2.ElementType != null) { Assert.Equal(NullabilityState.Nullable, param2.ElementType.ReadState); } } [Fact] [SkipOnMono("Nullability attributes trimmed on Mono")] public void NullablePublicOnlyOtherTypesTest() { Type type = typeof(Type); FieldInfo privateNullableField = type.GetField("s_defaultBinder", flags)!; NullabilityInfo info = nullabilityContext.Create(privateNullableField); Assert.Equal(NullabilityState.Unknown, info.ReadState); Assert.Equal(NullabilityState.Unknown, info.WriteState); MethodInfo internalNotNullableMethod = type.GetMethod("GetRootElementType", flags)!; info = nullabilityContext.Create(internalNotNullableMethod.ReturnParameter); Assert.Equal(NullabilityState.NotNull, info.ReadState); Assert.Equal(NullabilityState.NotNull, info.WriteState); PropertyInfo publicNullableProperty = type.GetProperty("DeclaringType", flags)!; info = nullabilityContext.Create(publicNullableProperty); Assert.Equal(NullabilityState.Nullable, info.ReadState); Assert.Equal(NullabilityState.Unknown, info.WriteState); PropertyInfo publicGetPrivateSetNullableProperty = typeof(FileSystemEntry).GetProperty("Directory", flags)!; info = nullabilityContext.Create(publicGetPrivateSetNullableProperty); Assert.Equal(NullabilityState.NotNull, info.ReadState); Assert.Equal(NullabilityState.NotNull, info.WriteState); MethodInfo protectedNullableReturnMethod = type.GetMethod("GetPropertyImpl", flags)!; info = nullabilityContext.Create(protectedNullableReturnMethod.ReturnParameter); Assert.Equal(NullabilityState.Nullable, info.ReadState); Assert.Equal(NullabilityState.Nullable, info.WriteState); MethodInfo privateValueTypeReturnMethod = type.GetMethod("BinarySearch", flags)!; info = nullabilityContext.Create(privateValueTypeReturnMethod.ReturnParameter); Assert.Equal(NullabilityState.NotNull, info.ReadState); Assert.Equal(NullabilityState.NotNull, info.WriteState); Type regexType = typeof(Regex); FieldInfo protectedInternalNullableField = regexType.GetField("pattern", flags)!; info = nullabilityContext.Create(protectedInternalNullableField); Assert.Equal(NullabilityState.Nullable, info.ReadState); Assert.Equal(NullabilityState.Nullable, info.WriteState); privateNullableField = regexType.GetField("_runner", flags)!; info = nullabilityContext.Create(privateNullableField); Assert.Equal(NullabilityState.Unknown, info.ReadState); Assert.Equal(NullabilityState.Unknown, info.WriteState); ConstructorInfo privateConstructor = typeof(IndexOutOfRangeException) .GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, new[] { typeof(SerializationInfo), typeof(StreamingContext) })!; info = nullabilityContext.Create(privateConstructor.GetParameters()[0]); Assert.Equal(NullabilityState.Unknown, info.WriteState); } public static IEnumerable<object[]> DifferentContextTestData() { yield return new object[] { "PropertyDisabled", NullabilityState.Unknown, NullabilityState.Unknown, typeof(string) }; yield return new object[] { "PropertyDisabledAllowNull", NullabilityState.Unknown, NullabilityState.Nullable, typeof(string) }; yield return new object[] { "PropertyDisabledMaybeNull", NullabilityState.Nullable, NullabilityState.Unknown, typeof(string) }; yield return new object[] { "PropertyEnabledAllowNull", NullabilityState.NotNull, NullabilityState.Nullable, typeof(string) }; yield return new object[] { "PropertyEnabledNotNull", NullabilityState.NotNull, NullabilityState.Nullable, typeof(string) }; yield return new object[] { "PropertyEnabledMaybeNull", NullabilityState.Nullable, NullabilityState.NotNull, typeof(string) }; yield return new object[] { "PropertyEnabledDisallowNull", NullabilityState.Nullable, NullabilityState.NotNull, typeof(string) }; yield return new object[] { "PropertyEnabledNullable", NullabilityState.Nullable, NullabilityState.Nullable, typeof(string) }; yield return new object[] { "PropertyEnabledNonNullable", NullabilityState.NotNull, NullabilityState.NotNull, typeof(string) }; } [Theory] [MemberData(nameof(DifferentContextTestData))] public void NullabilityDifferentContextTest(string propertyName, NullabilityState readState, NullabilityState writeState, Type type) { Type noContext = typeof(TypeWithNoContext); PropertyInfo property = noContext.GetProperty(propertyName, flags)!; NullabilityInfo nullability = nullabilityContext.Create(property); Assert.Equal(readState, nullability.ReadState); Assert.Equal(writeState, nullability.WriteState); Assert.Equal(type, nullability.Type); Type nullableContext = typeof(TypeWithNullableContext); property = nullableContext.GetProperty(propertyName, flags)!; nullability = nullabilityContext.Create(property); Assert.Equal(readState, nullability.ReadState); Assert.Equal(writeState, nullability.WriteState); Assert.Equal(type, nullability.Type); } [Fact] public void AttributedParametersTest() { Type type = typeof(TypeWithNullableContext); // bool NotNullWhenParameter([DisallowNull] string? disallowNull, [NotNullWhen(true)] ref string? notNullWhen, Type? nullableType); ParameterInfo[] notNullWhenParameters = type.GetMethod("NotNullWhenParameter", flags)!.GetParameters(); NullabilityInfo disallowNull = nullabilityContext.Create(notNullWhenParameters[0]); NullabilityInfo notNullWhen = nullabilityContext.Create(notNullWhenParameters[1]); Assert.Equal(NullabilityState.Nullable, disallowNull.ReadState); Assert.Equal(NullabilityState.NotNull, disallowNull.WriteState); Assert.Equal(NullabilityState.Nullable, notNullWhen.ReadState); Assert.Equal(NullabilityState.Nullable, notNullWhen.WriteState); Assert.Equal(NullabilityState.Nullable, nullabilityContext.Create(notNullWhenParameters[1]).ReadState); // bool MaybeNullParameters([MaybeNull] string maybeNull, [MaybeNullWhen(false)] out string maybeNullWhen, Type? nullableType) ParameterInfo[] maybeNullParameters = type.GetMethod("MaybeNullParameters", flags)!.GetParameters(); NullabilityInfo maybeNull = nullabilityContext.Create(maybeNullParameters[0]); NullabilityInfo maybeNullWhen = nullabilityContext.Create(maybeNullParameters[1]); Assert.Equal(NullabilityState.Nullable, maybeNull.ReadState); Assert.Equal(NullabilityState.NotNull, maybeNull.WriteState); Assert.Equal(NullabilityState.Nullable, maybeNullWhen.ReadState); Assert.Equal(NullabilityState.NotNull, maybeNullWhen.WriteState); Assert.Equal(NullabilityState.Nullable, nullabilityContext.Create(maybeNullParameters[1]).ReadState); // string? AllowNullParameter([AllowNull] string allowNull, [NotNullIfNotNull("allowNull")] string? notNullIfNotNull) ParameterInfo[] allowNullParameter = type.GetMethod("AllowNullParameter", flags)!.GetParameters(); NullabilityInfo allowNull = nullabilityContext.Create(allowNullParameter[0]); NullabilityInfo notNullIfNotNull = nullabilityContext.Create(allowNullParameter[1]); Assert.Equal(NullabilityState.NotNull, allowNull.ReadState); Assert.Equal(NullabilityState.Nullable, allowNull.WriteState); Assert.Equal(NullabilityState.Nullable, notNullIfNotNull.ReadState); Assert.Equal(NullabilityState.Nullable, notNullIfNotNull.WriteState); Assert.Equal(NullabilityState.Nullable, nullabilityContext.Create(allowNullParameter[1]).ReadState); // [return: NotNullIfNotNull("nullable")] public string? NullableNotNullIfNotNullReturn(string? nullable, [NotNull] ref string? readNotNull) ParameterInfo[] nullableNotNullIfNotNullReturn = type.GetMethod("NullableNotNullIfNotNullReturn", flags)!.GetParameters(); NullabilityInfo returnNotNullIfNotNull = nullabilityContext.Create(type.GetMethod("NullableNotNullIfNotNullReturn", flags)!.ReturnParameter); NullabilityInfo readNotNull = nullabilityContext.Create(nullableNotNullIfNotNullReturn[1]); Assert.Equal(NullabilityState.Nullable, returnNotNullIfNotNull.ReadState); Assert.Equal(NullabilityState.Nullable, returnNotNullIfNotNull.WriteState); Assert.Equal(NullabilityState.NotNull, readNotNull.ReadState); Assert.Equal(NullabilityState.Nullable, readNotNull.WriteState); Assert.Equal(NullabilityState.Nullable, nullabilityContext.Create(nullableNotNullIfNotNullReturn[0]).ReadState); // public bool TryGetOutParameters(string id, [NotNullWhen(true)] out string? value, [MaybeNullWhen(false)] out string value2) ParameterInfo[] tryGetOutParameters = type.GetMethod("TryGetOutParameters", flags)!.GetParameters(); NullabilityInfo notNullWhenParam = nullabilityContext.Create(tryGetOutParameters[1]); NullabilityInfo maybeNullWhenParam = nullabilityContext.Create(tryGetOutParameters[2]); Assert.Equal(NullabilityState.Nullable, notNullWhenParam.ReadState); Assert.Equal(NullabilityState.Nullable, notNullWhenParam.WriteState); Assert.Equal(NullabilityState.Nullable, maybeNullWhenParam.ReadState); Assert.Equal(NullabilityState.NotNull, maybeNullWhenParam.WriteState); Assert.Equal(NullabilityState.NotNull, nullabilityContext.Create(tryGetOutParameters[0]).ReadState); } public static IEnumerable<object[]> NestedGenericsCorrectOrderData() { yield return new object[] { "MethodReturnsNonTupleNonTupleNullStringNullStringNullString", new[] { NullabilityState.NotNull, NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.Nullable, NullabilityState.Nullable }, new[] { typeof(Tuple<Tuple<string, string>, string>), typeof(Tuple<string, string>), typeof(string), typeof(string), typeof(string) } }; yield return new object[] { "MethodReturnsNonTupleNonTupleNullStringNullStringNonString", new[] { NullabilityState.NotNull, NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.Nullable, NullabilityState.NotNull }, new[] { typeof(Tuple<Tuple<string, string>, string>), typeof(Tuple<string, string>), typeof(string), typeof(string), typeof(string) } }; } [Theory] [MemberData(nameof(NestedGenericsCorrectOrderData))] [SkipOnMono("Nullability attributes trimmed on Mono")] public void NestedGenericsCorrectOrderTest(string methodName, NullabilityState[] nullStates, Type[] types) { NullabilityInfo parentInfo = nullabilityContext.Create(typeof(TypeWithNotNullContext).GetMethod(methodName)!.ReturnParameter); var dataIndex = 0; Examine(parentInfo); Assert.Equal(nullStates.Length, dataIndex); Assert.Equal(types.Length, dataIndex); void Examine(NullabilityInfo info) { Assert.Equal(types[dataIndex], info.Type); Assert.Equal(nullStates[dataIndex++], info.ReadState); for (var i = 0; i < info.GenericTypeArguments.Length; i++) { Examine(info.GenericTypeArguments[i]); } } } public static IEnumerable<object[]> NestedGenericsReturnParameterData() { // public IEnumerable<Tuple<(string name, object? value), int>?> MethodReturnsEnumerableNonTupleNonNonNullValueTupleNonNullNon() => null!; yield return new object[] { "MethodReturnsEnumerableNonTupleNonNonNullValueTupleNonNullNon", NullabilityState.NotNull, NullabilityState.NotNull, NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.Nullable }; // public IEnumerable<Tuple<(string? name, object value)?, int>?>? MethodReturnsEnumerableNullTupleNullNonNullValueTupleNullNonNull() => null!; yield return new object[] { "MethodReturnsEnumerableNullTupleNullNonNullValueTupleNullNonNull", NullabilityState.Nullable, NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.Nullable, NullabilityState.NotNull }; // public IEnumerable<Tuple<Tuple<string, object?>, int>?> MethodReturnsEnumerableNonTupleNonNonNullTupleNonNullNon() => null!; yield return new object[] { "MethodReturnsEnumerableNonTupleNonNonNullTupleNonNullNon", NullabilityState.NotNull, NullabilityState.NotNull, NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.Nullable }; // public IEnumerable<GenericStruct<Tuple<string, object?>?, int>?>? MethodReturnsEnumerableNullStructNullNonNonTupleNonNullNull() => null; yield return new object[] { "MethodReturnsEnumerableNullStructNullNonNullTupleNonNullNull", NullabilityState.Nullable, NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.Nullable }; // public IEnumerable<Tuple<GenericStruct<string, object?>?, int>?>? MethodReturnsEnumerableNullTupleNullNonNullStructNonNullNull() => null; yield return new object[] { "MethodReturnsEnumerableNullTupleNullNonNullStructNonNullNull", NullabilityState.Nullable, NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.Nullable }; // public IEnumerable<(GenericStruct<string, object?> str, int? count)> MethodReturnsEnumerableNonValueTupleNonNullNonTupleNonNullNon() => null!; yield return new object[] { "MethodReturnsEnumerableNonValueTupleNonNullNonStructNonNullNon", NullabilityState.NotNull, NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.NotNull, NullabilityState.Nullable }; } [Theory] [MemberData(nameof(NestedGenericsReturnParameterData))] [SkipOnMono("Nullability attributes trimmed on Mono")] public void NestedGenericsReturnParameterTest(string methodName, NullabilityState enumState, NullabilityState innerTupleState, NullabilityState intState, NullabilityState outerTupleState, NullabilityState stringState, NullabilityState objectState) { NullabilityInfo enumerabeNullability = nullabilityContext.Create(typeof(TypeWithNotNullContext).GetMethod(methodName, flags)!.ReturnParameter); Assert.Equal(enumState, enumerabeNullability.ReadState); NullabilityInfo tupleNullability = enumerabeNullability.GenericTypeArguments[0]; Assert.Equal(outerTupleState, tupleNullability.ReadState); Assert.Equal(innerTupleState, tupleNullability.GenericTypeArguments[0].ReadState); Assert.Equal(intState, tupleNullability.GenericTypeArguments[1].ReadState); NullabilityInfo valueTupleNullability = tupleNullability.GenericTypeArguments[0]; Assert.Equal(innerTupleState, valueTupleNullability.ReadState); Assert.Equal(stringState, valueTupleNullability.GenericTypeArguments[0].ReadState); Assert.Equal(objectState, valueTupleNullability.GenericTypeArguments[1].ReadState); } public static IEnumerable<object[]> RefReturnData() { yield return new object[] { "RefReturnUnknown", NullabilityState.Unknown, NullabilityState.Unknown, NullabilityState.Unknown, NullabilityState.Unknown }; // [return: MaybeNull] public ref string RefReturnMaybeNull([DisallowNull] ref string? id) yield return new object[] { "RefReturnMaybeNull", NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.NotNull }; // public ref string RefReturnNotNullable([MaybeNull] ref string id) yield return new object[] { "RefReturnNotNullable", NullabilityState.NotNull, NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.NotNull }; // [return: NotNull]public ref string? RefReturnNotNull([NotNull] ref string? id) yield return new object[] { "RefReturnNotNull", NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.Nullable }; // publiic ref string? RefReturnNullable([AllowNull] ref string id) yield return new object[] { "RefReturnNullable", NullabilityState.Nullable, NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.Nullable }; } [Theory] [MemberData(nameof(RefReturnData))] public void RefReturnTestTest(string methodName, NullabilityState retReadState, NullabilityState retWriteState, NullabilityState paramReadState, NullabilityState paramWriteState) { MethodInfo method = typeof(TypeWithNullableContext).GetMethod(methodName, flags)!; NullabilityInfo returnNullability = nullabilityContext.Create(method.ReturnParameter); NullabilityInfo paramNullability = nullabilityContext.Create(method.GetParameters()[0]); Assert.Equal(retReadState, returnNullability.ReadState); Assert.Equal(retWriteState, returnNullability.WriteState); Assert.Equal(paramReadState, paramNullability.ReadState); Assert.Equal(paramWriteState, paramNullability.WriteState); } public static IEnumerable<object[]> ValueTupleTestData() { // public (int, string) UnknownValueTuple; [0] yield return new object[] { "UnknownValueTuple", NullabilityState.NotNull, NullabilityState.Unknown, NullabilityState.NotNull }; // public (string?, object) NullNonNonValueTuple; [0, 2, 1] yield return new object[] { "Null_Non_Non_ValueTuple", NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.NotNull }; // public (string?, object)? Null_Non_Null_ValueTuple; [0, 2, 1] yield return new object[] { "Null_Non_Null_ValueTuple", NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.Nullable }; // public (int, int?)? Non_Null_Null_ValueTuple; [0] yield return new object[] { "Non_Null_Null_ValueTuple", NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.Nullable }; // public (int, string) Non_Non_Non_ValueTuple; [0, 1] yield return new object[] { "Non_Non_Non_ValueTuple", NullabilityState.NotNull, NullabilityState.NotNull, NullabilityState.NotNull }; // public (int, string?) Non_Null_Non_ValueTuple; [0, 2] yield return new object[] { "Non_Null_Non_ValueTuple", NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.NotNull }; } [Theory] [MemberData(nameof(ValueTupleTestData))] [SkipOnMono("Nullability attributes trimmed on Mono")] public void TestValueTupleGenericTypeParameters(string fieldName, NullabilityState param1, NullabilityState param2, NullabilityState fieldState) { var tupleInfo = nullabilityContext.Create(testType.GetField(fieldName)!); Assert.Equal(fieldState, tupleInfo.ReadState); Assert.Equal(param1, tupleInfo.GenericTypeArguments[0].ReadState); Assert.Equal(param2, tupleInfo.GenericTypeArguments[1].ReadState); } public static IEnumerable<object?[]> GenericInheritanceTestData() { yield return new object?[] { typeof(ListOfUnconstrained<string?>), NullabilityState.Nullable, null }; yield return new object?[] { typeof(ListUnconstrainedOfNullable<string>), NullabilityState.Nullable, null }; yield return new object?[] { typeof(ListUnconstrainedOfNullableOfObject<>), NullabilityState.NotNull, null }; yield return new object?[] { typeof(ListOfArrayOfNullableString), NullabilityState.NotNull, NullabilityState.Nullable }; yield return new object?[] { typeof(ListOfNotNull<ListOfNotNull<object>>), NullabilityState.NotNull, NullabilityState.NotNull }; yield return new object?[] { typeof(ListOfListOfObject<string?>), NullabilityState.NotNull, NullabilityState.NotNull }; yield return new object?[] { typeof(ListMultiGenericOfNotNull<object?, string, string?>), NullabilityState.NotNull, null }; } [Theory] [MemberData(nameof(GenericInheritanceTestData))] [SkipOnMono("Nullability attributes trimmed on Mono")] public void TestGenericInheritance(Type listType, NullabilityState parameterState, NullabilityState? subState) { var addParameterInfo = nullabilityContext.Create(listType.GetMethod("Add")!.GetParameters()[0]); Validate(addParameterInfo); var copyToParameterInfo = nullabilityContext.Create( listType.GetMethod("CopyTo", new[] { addParameterInfo.Type.MakeArrayType() })! .GetParameters()[0]); Assert.Equal(NullabilityState.NotNull, copyToParameterInfo.ReadState); Assert.Equal(NullabilityState.NotNull, copyToParameterInfo.WriteState); Assert.NotNull(copyToParameterInfo.ElementType); Validate(copyToParameterInfo.ElementType!); void Validate(NullabilityInfo info) { Assert.Equal(parameterState, info.ReadState); Assert.Equal(parameterState, info.WriteState); if (subState != null) { NullabilityInfo subInfo = info.ElementType ?? info.GenericTypeArguments[0]; Assert.Equal(subState, subInfo.ReadState); Assert.Equal(subState, subInfo.WriteState); Assert.True(info.GenericTypeArguments.Length <= 1); } else { Assert.Null(info.ElementType); Assert.Empty(info.GenericTypeArguments); } } } [Fact] [SkipOnMono("Nullability attributes trimmed on Mono")] public void TestDeeplyNestedGenericInheritance() { var copyToMethodInfo = nullabilityContext.Create( typeof(ListOfTupleOfDictionaryOfStringNullableBoolIntNullableObject).GetMethod("CopyTo", new[] { typeof((Dictionary<string, bool?>, int, object?)[]) })! .GetParameters()[0]); Validate(copyToMethodInfo, typeof((Dictionary<string, bool?>, int, object?)[]), NullabilityState.NotNull); Assert.NotNull(copyToMethodInfo.ElementType); var tupleInfo = copyToMethodInfo.ElementType!; Validate(tupleInfo, typeof((Dictionary<string, bool?>, int, object?)), NullabilityState.NotNull); var dictionaryInfo = tupleInfo.GenericTypeArguments[0]; Validate(dictionaryInfo, typeof(Dictionary<string, bool?>), NullabilityState.NotNull); var stringInfo = dictionaryInfo.GenericTypeArguments[0]; Validate(stringInfo, typeof(string), NullabilityState.NotNull); var nullableBoolInfo = dictionaryInfo.GenericTypeArguments[1]; Validate(nullableBoolInfo, typeof(bool?), NullabilityState.Nullable); var intInfo = tupleInfo.GenericTypeArguments[1]; Validate(intInfo, typeof(int), NullabilityState.NotNull); var objectInfo = tupleInfo.GenericTypeArguments[2]; Validate(objectInfo, typeof(object), NullabilityState.Nullable); void Validate(NullabilityInfo info, Type type, NullabilityState state) { Assert.Equal(type, info.Type); Assert.Equal(state, info.ReadState); Assert.Equal(state, info.WriteState); Assert.Equal(type.IsGenericType && type.GetGenericTypeDefinition() != typeof(Nullable<>) ? type.GetGenericArguments().Length : 0, info.GenericTypeArguments.Length); Assert.Equal(type.IsArray, info.ElementType is not null); } } [Fact] [SkipOnMono("Nullability attributes trimmed on Mono")] public void TestNestedGenericInheritanceWithMultipleParameters() { var item3Info = nullabilityContext.Create(typeof(DerivesFromTupleOfNestedGenerics).GetProperty("Item3")!); Assert.Equal(typeof(IDisposable[]), item3Info.Type); Assert.Equal(NullabilityState.Nullable, item3Info.ReadState); Assert.Equal(NullabilityState.Unknown, item3Info.WriteState); // read-only property Assert.Equal(NullabilityState.NotNull, item3Info.ElementType!.ReadState); Assert.Equal(NullabilityState.NotNull, item3Info.ElementType.WriteState); } } #pragma warning disable CS0649, CS0067, CS0414 public class TypeWithNullableContext { #nullable disable [AllowNull] public string PropertyDisabledAllowNull { get; set; } [MaybeNull] public string PropertyDisabledMaybeNull { get; set; } public string PropertyDisabled { get; set; } public ref string RefReturnUnknown(ref string id) { return ref id; } #nullable enable [AllowNull] public string PropertyEnabledAllowNull { get; set; } [NotNull] public string? PropertyEnabledNotNull { get; set; } = null!; [DisallowNull] public string? PropertyEnabledDisallowNull { get; set; } = null!; [MaybeNull] public string PropertyEnabledMaybeNull { get; set; } public string? PropertyEnabledNullable { get; set; } public string PropertyEnabledNonNullable { get; set; } = null!; bool NotNullWhenParameter([DisallowNull] string? disallowNull, [NotNullWhen(true)] ref string? notNullWhen, Type? nullableType) { return false; } public bool MaybeNullParameters([MaybeNull] string maybeNull, [MaybeNullWhen(false)] out string maybeNullWhen, Type? nullableType) { maybeNullWhen = null; return false; } public string? AllowNullParameter([AllowNull] string allowNull, [NotNullIfNotNull("allowNull")] string? notNullIfNotNull) { return null; } [return: NotNullIfNotNull("nullable")] public string? NullableNotNullIfNotNullReturn(string? nullable, [NotNull] ref string? readNotNull) { readNotNull = string.Empty; return null!; } public ref string? RefReturnNullable([AllowNull] ref string id) { return ref id!; } [return: MaybeNull] public ref string RefReturnMaybeNull([DisallowNull] ref string? id) { return ref id; } [return: NotNull] public ref string? RefReturnNotNull([NotNull] ref string? id) { id = string.Empty; return ref id!; } public ref string RefReturnNotNullable([MaybeNull] ref string id) { return ref id; } public bool TryGetOutParameters(string id, [NotNullWhen(true)] out string? value, [MaybeNullWhen(false)] out string value2) { value = null; value2 = null; return false; } public IEnumerable<Tuple<(string name, object? value), object>?> MethodReturnsEnumerableNonTupleNonNonNullValueTupleNonNullNon() => null!; } public class TypeWithNoContext { #nullable disable [AllowNull] public string PropertyDisabledAllowNull { get; set; } [MaybeNull] public string PropertyDisabledMaybeNull { get; set; } public string PropertyDisabled { get; set; } #nullable enable [AllowNull] public string PropertyEnabledAllowNull { get; set; } [NotNull] public string? PropertyEnabledNotNull { get; set; } = null!; [DisallowNull] public string? PropertyEnabledDisallowNull { get; set; } = null!; [MaybeNull] public string PropertyEnabledMaybeNull { get; set; } public string? PropertyEnabledNullable { get; set; } public string PropertyEnabledNonNullable { get; set; } = null!; #nullable disable } public class TypeWithNotNullContext { public string PropertyUnknown { get; set; } short PropertyValueTypeUnknown { get; set; } public string[] PropertyArrayUnknown { get; set; } private string[][] PropertyJaggedArrayUnknown { get; set; } protected Tuple<string, string, string> PropertyTupleUnknown { get; set; } protected internal IDictionary<Type, string[]> PropertyDictionaryUnknown { get; set; } public (int, string) UnknownValueTuple; internal TypeWithNotNullContext FieldUnknown; public int FieldValueTypeUnknown; public event EventHandler EventUnknown; public string[] MethodReturnsUnknown() => null!; public void MethodParametersUnknown(string s, IDictionary<Type, string[]> dict) { } #nullable enable public TypeWithNotNullContext? PropertyNullable { get; set; } public TypeWithNotNullContext? PropertyNullableReadOnly { get; } private NullabilityInfoContextTests PropertyNonNullable { get; set; } = null!; internal float PropertyValueType { get; set; } protected long? PropertyValueTypeNullable { get; set; } [DisallowNull] public int? PropertyValueTypeDisallowNull { get; set; } [NotNull] protected int? PropertyValueTypeNotNull { get; set; } [MaybeNull] public byte PropertyValueTypeMaybeNull { get; set; } [AllowNull] public byte PropertyValueTypeAllowNull { get; set; } [DisallowNull] public string? PropertyDisallowNull { get; set; } [AllowNull] public string PropertyAllowNull { get; set; } [NotNull] public string? PropertyNotNull { get; set; } [MaybeNull] public string PropertyMaybeNull { get; set; } // only DisallowNull matters [AllowNull, DisallowNull] public string PropertyAllowNull2 { get; set; } // only AllowNull matters [AllowNull, DisallowNull] public string? PropertyDisallowNull2 { get; set; } // only NotNull matters [NotNull, MaybeNull] public string? PropertyNotNull2 { get; set; } // only NotNull matters [NotNull, MaybeNull] public string PropertyMaybeNull2 { get; set; } [DisallowNull] public string? this[int i] { get => null; set { } } private protected string?[]?[]? PropertyJaggedArrayNullNullNull { get; set; } public static string?[]?[] PropertyJaggedArrayNullNullNon { get; set; } = null!; public string?[][]? PropertyJaggedArrayNullNonNull { get; set; } public static string[]?[]? PropertyJaggedArrayNonNullNull { get; set; } public string?[][] PropertyJaggedArrayNullNonNon { get; set; } = null!; private static string[][]? PropertyJaggedArrayNonNonNull { get; set; } public string?[]? PropertyArrayNullNull { get; set; } static string?[] PropertyArrayNullNon { get; set; } = null!; public string[]? PropertyArrayNonNull { get; } = null; public string[] PropertyArrayNonNon { get; set; } = null!; public Tuple<string?, string?, string?>? PropertyTupleNullNullNullNull { get; set; } public Tuple<string, string?, string> PropertyTupleNonNullNonNon { get; set; } = null!; internal Tuple<string?, string, string?>? PropertyTupleNullNonNullNull { get; set; } public Tuple<string, string?, string>? PropertyTupleNonNullNonNull { get; set; } protected Tuple<string, string, string> PropertyTupleNonNonNonNon { get; set; } = null!; public IDictionary<Type?, string?[]?> PropertyDictionaryNullNullNullNon { get; set; } = null!; public IDictionary<Type, string?[]>? PropertyDictionaryNonNullNonNull { get; set; } IDictionary<Type?, string[]>? PropertyDictionaryNullNonNonNull { get; set; } public IDictionary<Type, string?[]> PropertyDictionaryNonNullNonNon { get; set; } = null!; private IDictionary<Type, string[]>? PropertyDictionaryNonNonNonNull { get; set; } public IDictionary<Type, string[]> PropertyDictionaryNonNonNonNon { get; set; } = null!; public (string?, object) Null_Non_Non_ValueTuple; public (string?, object)? Null_Non_Null_ValueTuple; public (int, int?)? Non_Null_Null_ValueTuple; public (int, string) Non_Non_Non_ValueTuple; public (int, string?) Non_Null_Non_ValueTuple; private const string? FieldNullable = null; protected static NullabilityInfoContextTests FieldNonNullable = null!; public static double FieldValueTypeNotNull; public readonly int? FieldValueTypeNullable; [DisallowNull] public string? FieldDisallowNull; [AllowNull] public string FieldAllowNull; [NotNull] string? FieldNotNull = null; [MaybeNull] public string FieldMaybeNull; [AllowNull, DisallowNull] public string FieldAllowNull2; [AllowNull, DisallowNull] public string? FieldDisallowNull2; [NotNull, MaybeNull] internal string? FieldNotNull2; [NotNull, MaybeNull] public string FieldMaybeNull2; public event EventHandler? EventNullable; public event EventHandler EventNotNull = null!; public string?[] MethodReturnsNullNon() => null!; public string?[]? MethodReturnsNullNull() => null; public string[]? MethodReturnsNonNull() => null; [return: NotNull, MaybeNull] public string[]? MethodReturnsNonNotNull() => null!; // only NotNull is applicable [return: MaybeNull] public string[] MethodReturnsNonMaybeNull() => null; public string[] MethodReturnsNonNon() => null!; public Tuple<string?, string>? MethodReturnsTupleNullNonNull() => null; public Tuple<string?, int> MethodReturnsTupleNullNonNot() => null!; public (int?, string)? MethodReturnsValueTupleNullNonNull() => null; public (string?, string) MethodReturnsValueTupleNullNonNon() => (null, string.Empty); public IEnumerable<Tuple<(string name, object? value), int>?> MethodReturnsEnumerableNonTupleNonNonNullValueTupleNonNullNon() => null!; public IEnumerable<Tuple<(string? name, object value)?, int>?>? MethodReturnsEnumerableNullTupleNullNonNullValueTupleNullNonNull() => null!; public IEnumerable<Tuple<Tuple<string, object?>, int>?> MethodReturnsEnumerableNonTupleNonNonNullTupleNonNullNon() => null!; public IEnumerable<GenericStruct<Tuple<string, object?>?, int>?>? MethodReturnsEnumerableNullStructNullNonNullTupleNonNullNull() => null; public IEnumerable<Tuple<GenericStruct<string, object?>?, int>?>? MethodReturnsEnumerableNullTupleNullNonNullStructNonNullNull() => null; public IEnumerable<(GenericStruct<string, object?> str, int? count)> MethodReturnsEnumerableNonValueTupleNonNullNonStructNonNullNon() => null!; public Tuple<Tuple<string?, string?>, string?> MethodReturnsNonTupleNonTupleNullStringNullStringNullString() => null!; public Tuple<Tuple<string?, string?>, string> MethodReturnsNonTupleNonTupleNullStringNullStringNonString() => null!; public void MethodNullNonNullNonNon(string? s, IDictionary<Type, string?[]> dict) { } public void MethodNonNullNonNullNotNull(string s, [NotNull] IDictionary<Type, string[]?>? dict) { dict = new Dictionary<Type, string[]?>(); } public void MethodNullNonNullNullNon(string? s, IDictionary<Type, string?[]?> dict) { } public void MethodAllowNullNonNonNonNull([AllowNull] string s, IDictionary<Type, string[]>? dict) { } } public struct GenericStruct<T, Y> { } internal class GenericTest<T> { #nullable disable public T PropertyUnknown { get; set; } protected T[] PropertyArrayUnknown { get; set; } public Tuple<T, string, TypeWithNotNullContext> PropertyTupleUnknown { get; set; } private IDictionary<Type, T[]> PropertyDictionaryUnknown { get; set; } public T FieldUnknown; public T MethodReturnsUnknown() => default!; public void MethodParametersUnknown(T s, IDictionary<Type, T> dict) { } #nullable enable public T PropertyNonNullable { get; set; } = default!; public T? PropertyNullable { get; set; } [DisallowNull] public T PropertyDisallowNull { get; set; } = default!; [NotNull] public T PropertyNotNull { get; set; } = default!; [MaybeNull] public T PropertyMaybeNull { get; set; } [AllowNull] public T PropertyAllowNull { get; set; } internal T?[]? PropertyArrayNullNull { get; set; } public T?[] PropertyArrayNullNon { get; set; } = null!; T[]? PropertyArrayNonNull { get; set; } public T[] PropertyArrayNonNon { get; set; } = null!; public Tuple<T?, string?, string?>? PropertyTupleNullNullNullNull { get; set; } public Tuple<T, T?, string> PropertyTupleNonNullNonNon { get; set; } = null!; Tuple<string?, T, T?>? PropertyTupleNullNonNullNull { get; set; } public Tuple<T, int?, string>? PropertyTupleNonNullNonNull { get; set; } public Tuple<int, string, T> PropertyTupleNonNonNonNon { get; set; } = null!; private IDictionary<T?, string?[]?> PropertyDictionaryNullNullNullNon { get; set; } = null!; static IDictionary<Type, T?[]>? PropertyDictionaryNonNullNonNull { get; set; } public static IDictionary<T?, T[]>? PropertyDictionaryNullNonNonNull { get; set; } public IDictionary<Type, T?[]> PropertyDictionaryNonNullNonNon { get; set; } = null!; protected IDictionary<T, T[]>? PropertyDictionaryNonNonNonNull { get; set; } public IDictionary<T, int[]> PropertyDictionaryNonNonNonNon { get; set; } = null!; static T? FieldNullable = default; public T FieldNonNullable = default!; [DisallowNull] public T? FieldDisallowNull; [AllowNull] protected T FieldAllowNull; [NotNull] public T? FieldNotNull = default; [MaybeNull] protected internal T FieldMaybeNull = default!; public List<T> FieldListOfT = default!; public Dictionary<string, T> FieldDictionaryStringToT = default!; public T MethodReturnsGeneric() => default!; public T? MethodReturnsNullGeneric() => default; [return: NotNull] public T MethodReturnsGenericNotNull() => default!; [return: MaybeNull] public T MethodReturnsGenericMaybeNull() => default; public List<T?> MethodNonNullListNullGeneric() => null!; public List<T>? MethodNullListNonNullGeneric() => null; public void MethodArgsNullGenericNullDictValueGeneric(T? s, IDictionary<Type, T>? dict) { } public void MethodArgsGenericDictValueNullGeneric(T s, IDictionary<string, T?> dict) { } } internal class GenericTestConstrainedNotNull<T> where T : notnull { #nullable disable public T FieldUnknown; public T PropertyUnknown { get; set; } #nullable enable public T FieldNullableEnabled = default!; public T? FieldNullable; public T PropertyNullableEnabled { get; set; } = default!; public T? PropertyNullable { get; set; } = default!; } internal class GenericTestConstrainedStruct<T> where T : struct { #nullable disable public T FieldUnknown; public T PropertyUnknown { get; set; } #nullable enable public T FieldNullableEnabled; public T? FieldNullable; public T PropertyNullableEnabled { get; set; } public T? PropertyNullable { get; set; } } public class ListOfUnconstrained<T> : List<T> { } public class ListUnconstrainedOfNullable<T> : ListOfUnconstrained<T> where T : class? { } public class ListUnconstrainedOfNullableOfObject<T> : ListUnconstrainedOfNullable<object> { } public class ListOfArrayOfNullableString : List<string?[]> { } public class ListOfNotNull<T> : List<T> where T : notnull { } public class ListOfListOfObject<T> : List<List<object>> { } public class ListMultiGenericOfNotNull<T, U, V> : List<U> where T : class? where U : class where V : class? { } public class ListOfTupleOfDictionaryOfStringNullableBoolIntNullableObject : List<(Dictionary<string, bool?>, int, object?)> { } public class DerivesFromTupleOfNestedGenerics : Tuple<List<string[]>, Dictionary<object[], List<object>>, IDisposable[]?> { public DerivesFromTupleOfNestedGenerics(List<string[]> item1, Dictionary<object[], List<object>> item2, IDisposable[]? item3) : base(item1, item2, item3) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO.Enumeration; using System.Runtime.Serialization; using System.Text.RegularExpressions; using Microsoft.DotNet.RemoteExecutor; using Xunit; namespace System.Reflection.Tests { public class NullabilityInfoContextTests { private static readonly NullabilityInfoContext nullabilityContext = new NullabilityInfoContext(); private static readonly Type testType = typeof(TypeWithNotNullContext); private static readonly Type genericType = typeof(GenericTest<TypeWithNotNullContext>); private static readonly Type stringType = typeof(string); private static readonly BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static; public static IEnumerable<object[]> FieldTestData() { yield return new object[] { "FieldNullable", NullabilityState.Nullable, NullabilityState.Nullable, typeof(string) }; yield return new object[] { "FieldUnknown", NullabilityState.Unknown, NullabilityState.Unknown, typeof(TypeWithNotNullContext) }; yield return new object[] { "FieldNonNullable", NullabilityState.NotNull, NullabilityState.NotNull, typeof(NullabilityInfoContextTests) }; yield return new object[] { "FieldValueTypeUnknown", NullabilityState.NotNull, NullabilityState.NotNull, typeof(int) }; yield return new object[] { "FieldValueTypeNotNull", NullabilityState.NotNull, NullabilityState.NotNull, typeof(double) }; yield return new object[] { "FieldValueTypeNullable", NullabilityState.Nullable, NullabilityState.Nullable, typeof(int?) }; yield return new object[] { "FieldDisallowNull", NullabilityState.Nullable, NullabilityState.NotNull, typeof(string) }; yield return new object[] { "FieldAllowNull", NullabilityState.NotNull, NullabilityState.Nullable, typeof(string) }; yield return new object[] { "FieldDisallowNull2", NullabilityState.Nullable, NullabilityState.NotNull, typeof(string) }; yield return new object[] { "FieldAllowNull2", NullabilityState.NotNull, NullabilityState.NotNull, typeof(string) }; yield return new object[] { "FieldNotNull", NullabilityState.NotNull, NullabilityState.Nullable, typeof(string) }; yield return new object[] { "FieldMaybeNull", NullabilityState.Nullable, NullabilityState.NotNull, typeof(string) }; yield return new object[] { "FieldMaybeNull2", NullabilityState.NotNull, NullabilityState.NotNull, typeof(string) }; yield return new object[] { "FieldNotNull2", NullabilityState.NotNull, NullabilityState.Nullable, typeof(string) }; } [Theory] [MemberData(nameof(FieldTestData))] public void FieldTest(string fieldName, NullabilityState readState, NullabilityState writeState, Type type) { FieldInfo field = testType.GetField(fieldName, flags); NullabilityInfo nullability = nullabilityContext.Create(field); Assert.Equal(readState, nullability.ReadState); Assert.Equal(writeState, nullability.WriteState); Assert.Equal(type, nullability.Type); Assert.Empty(nullability.GenericTypeArguments); Assert.Null(nullability.ElementType); } public static IEnumerable<object[]> EventTestData() { yield return new object[] { "EventNullable", NullabilityState.Nullable, NullabilityState.Nullable, typeof(EventHandler) }; yield return new object[] { "EventUnknown", NullabilityState.Unknown, NullabilityState.Unknown, typeof(EventHandler) }; yield return new object[] { "EventNotNull", NullabilityState.NotNull, NullabilityState.NotNull, typeof(EventHandler) }; } [Theory] [MemberData(nameof(EventTestData))] public void EventTest(string eventName, NullabilityState readState, NullabilityState writeState, Type type) { EventInfo @event = testType.GetEvent(eventName); NullabilityInfo nullability = nullabilityContext.Create(@event); Assert.Equal(readState, nullability.ReadState); Assert.Equal(writeState, nullability.WriteState); Assert.Equal(type, nullability.Type); Assert.Empty(nullability.GenericTypeArguments); Assert.Null(nullability.ElementType); } public static IEnumerable<object[]> PropertyTestData() { yield return new object[] { "PropertyNullable", NullabilityState.Nullable, NullabilityState.Nullable, typeof(TypeWithNotNullContext) }; yield return new object[] { "PropertyNullableReadOnly", NullabilityState.Nullable, NullabilityState.Unknown, typeof(TypeWithNotNullContext) }; yield return new object[] { "PropertyUnknown", NullabilityState.Unknown, NullabilityState.Unknown, typeof(string) }; yield return new object[] { "PropertyNonNullable", NullabilityState.NotNull, NullabilityState.NotNull, typeof(NullabilityInfoContextTests) }; yield return new object[] { "PropertyValueTypeUnknown", NullabilityState.NotNull, NullabilityState.NotNull, typeof(short) }; yield return new object[] { "PropertyValueType", NullabilityState.NotNull, NullabilityState.NotNull, typeof(float) }; yield return new object[] { "PropertyValueTypeNullable", NullabilityState.Nullable, NullabilityState.Nullable, typeof(long?) }; yield return new object[] { "PropertyValueTypeDisallowNull", NullabilityState.Nullable, NullabilityState.NotNull, typeof(int?) }; yield return new object[] { "PropertyValueTypeAllowNull", NullabilityState.NotNull, NullabilityState.NotNull, typeof(byte) }; yield return new object[] { "PropertyValueTypeNotNull", NullabilityState.NotNull, NullabilityState.Nullable, typeof(int?) }; yield return new object[] { "PropertyValueTypeMaybeNull", NullabilityState.NotNull, NullabilityState.NotNull, typeof(byte) }; yield return new object[] { "PropertyDisallowNull", NullabilityState.Nullable, NullabilityState.NotNull, typeof(string) }; yield return new object[] { "PropertyAllowNull", NullabilityState.NotNull, NullabilityState.Nullable, typeof(string) }; yield return new object[] { "PropertyDisallowNull2", NullabilityState.Nullable, NullabilityState.NotNull, typeof(string) }; yield return new object[] { "PropertyAllowNull2", NullabilityState.NotNull, NullabilityState.NotNull, typeof(string) }; yield return new object[] { "PropertyNotNull", NullabilityState.NotNull, NullabilityState.Nullable, typeof(string) }; yield return new object[] { "PropertyMaybeNull", NullabilityState.Nullable, NullabilityState.NotNull, typeof(string) }; yield return new object[] { "PropertyMaybeNull2", NullabilityState.NotNull, NullabilityState.NotNull, typeof(string) }; yield return new object[] { "PropertyNotNull2", NullabilityState.NotNull, NullabilityState.Nullable, typeof(string) }; yield return new object[] { "Item", NullabilityState.Nullable, NullabilityState.NotNull, typeof(string) }; } [Theory] [MemberData(nameof(PropertyTestData))] public void PropertyTest(string propertyName, NullabilityState readState, NullabilityState writeState, Type type) { PropertyInfo property = testType.GetProperty(propertyName, flags); NullabilityInfo nullability = nullabilityContext.Create(property); Assert.Equal(readState, nullability.ReadState); Assert.Equal(readState, nullabilityContext.Create(property.GetMethod.ReturnParameter).ReadState); Assert.Equal(writeState, nullability.WriteState); if (property.SetMethod != null) { Assert.Equal(writeState, nullabilityContext.Create(property.SetMethod.GetParameters()[0]).WriteState); } Assert.Equal(type, nullability.Type); Assert.Empty(nullability.GenericTypeArguments); Assert.Null(nullability.ElementType); } public static IEnumerable<object[]> ArrayPropertyTestData() { yield return new object[] { "PropertyArrayUnknown", NullabilityState.Unknown, NullabilityState.Unknown }; yield return new object[] { "PropertyArrayNullNull", NullabilityState.Nullable, NullabilityState.Nullable }; yield return new object[] { "PropertyArrayNullNon", NullabilityState.Nullable, NullabilityState.NotNull }; yield return new object[] { "PropertyArrayNonNull", NullabilityState.NotNull, NullabilityState.Nullable }; yield return new object[] { "PropertyArrayNonNon", NullabilityState.NotNull, NullabilityState.NotNull }; } [Theory] [SkipOnMono("Nullability attributes trimmed on Mono")] [MemberData(nameof(ArrayPropertyTestData))] public void ArrayPropertyTest(string propertyName, NullabilityState elementState, NullabilityState propertyState) { PropertyInfo property = testType.GetProperty(propertyName, flags); NullabilityInfo nullability = nullabilityContext.Create(property); Assert.Equal(propertyState, nullability.ReadState); Assert.NotNull(nullability.ElementType); Assert.Equal(elementState, nullability.ElementType.ReadState); Assert.Empty(nullability.GenericTypeArguments); } public static IEnumerable<object[]> GenericArrayPropertyTestData() { yield return new object[] { "PropertyArrayUnknown", NullabilityState.Unknown, NullabilityState.Unknown }; yield return new object[] { "PropertyArrayNullNull", NullabilityState.Nullable, NullabilityState.Nullable }; // T?[]? PropertyArrayNullNull { get; set; } yield return new object[] { "PropertyArrayNullNon", NullabilityState.Nullable, NullabilityState.NotNull }; // T?[] PropertyArrayNullNon { get; set; } yield return new object[] { "PropertyArrayNonNull", NullabilityState.Nullable, NullabilityState.Nullable }; // T[]? PropertyArrayNonNull { get; set; } yield return new object[] { "PropertyArrayNonNon", NullabilityState.Nullable, NullabilityState.NotNull }; // T[] PropertyArrayNonNon { get; set; } } [Theory] [SkipOnMono("Nullability attributes trimmed on Mono")] [MemberData(nameof(GenericArrayPropertyTestData))] public void GenericArrayPropertyTest(string propertyName, NullabilityState elementState, NullabilityState propertyState) { PropertyInfo property = genericType.GetProperty(propertyName, flags); NullabilityInfo nullability = nullabilityContext.Create(property); Assert.Equal(propertyState, nullability.ReadState); Assert.NotNull(nullability.ElementType); Assert.Equal(elementState, nullability.ElementType.ReadState); Assert.Empty(nullability.GenericTypeArguments); } public static IEnumerable<object[]> JaggedArrayPropertyTestData() { yield return new object[] { "PropertyJaggedArrayUnknown", NullabilityState.Unknown, NullabilityState.Unknown, NullabilityState.Unknown }; yield return new object[] { "PropertyJaggedArrayNullNullNull", NullabilityState.Nullable, NullabilityState.Nullable, NullabilityState.Nullable }; yield return new object[] { "PropertyJaggedArrayNullNullNon", NullabilityState.Nullable, NullabilityState.Nullable, NullabilityState.NotNull }; yield return new object[] { "PropertyJaggedArrayNullNonNull", NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.Nullable }; yield return new object[] { "PropertyJaggedArrayNonNullNull", NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.Nullable }; yield return new object[] { "PropertyJaggedArrayNullNonNon", NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.NotNull }; yield return new object[] { "PropertyJaggedArrayNonNonNull", NullabilityState.NotNull, NullabilityState.NotNull, NullabilityState.Nullable }; } [Theory] [SkipOnMono("Nullability attributes trimmed on Mono")] [MemberData(nameof(JaggedArrayPropertyTestData))] public void JaggedArrayPropertyTest(string propertyName, NullabilityState innermodtElementState, NullabilityState elementState, NullabilityState propertyState) { PropertyInfo property = testType.GetProperty(propertyName, flags); NullabilityInfo nullability = nullabilityContext.Create(property); Assert.Equal(propertyState, nullability.ReadState); Assert.NotNull(nullability.ElementType); Assert.Equal(elementState, nullability.ElementType.ReadState); Assert.NotNull(nullability.ElementType.ElementType); Assert.Equal(innermodtElementState, nullability.ElementType.ElementType.ReadState); Assert.Empty(nullability.GenericTypeArguments); } public static IEnumerable<object[]> TuplePropertyTestData() { yield return new object[] { "PropertyTupleUnknown", NullabilityState.Unknown, NullabilityState.Unknown, NullabilityState.Unknown, NullabilityState.Unknown }; yield return new object[] { "PropertyTupleNullNullNullNull", NullabilityState.Nullable, NullabilityState.Nullable, NullabilityState.Nullable, NullabilityState.Nullable }; yield return new object[] { "PropertyTupleNonNullNonNon", NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.NotNull }; yield return new object[] { "PropertyTupleNullNonNullNull", NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.Nullable }; yield return new object[] { "PropertyTupleNonNullNonNull", NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.Nullable }; yield return new object[] { "PropertyTupleNonNonNonNon", NullabilityState.NotNull, NullabilityState.NotNull, NullabilityState.NotNull, NullabilityState.NotNull }; } [Theory] [SkipOnMono("Nullability attributes trimmed on Mono")] [MemberData(nameof(TuplePropertyTestData))] public void TuplePropertyTest(string propertyName, NullabilityState genericParam1, NullabilityState genericParam2, NullabilityState genericParam3, NullabilityState propertyState) { PropertyInfo property = testType.GetProperty(propertyName, flags); NullabilityInfo nullability = nullabilityContext.Create(property); Assert.Equal(propertyState, nullability.ReadState); Assert.NotEmpty(nullability.GenericTypeArguments); Assert.Equal(genericParam1, nullability.GenericTypeArguments[0].ReadState); Assert.Equal(genericParam2, nullability.GenericTypeArguments[1].ReadState); Assert.Equal(genericParam3, nullability.GenericTypeArguments[2].ReadState); Assert.Null(nullability.ElementType); } public static IEnumerable<object[]> GenericTuplePropertyTestData() { yield return new object[] { "PropertyTupleUnknown", NullabilityState.Unknown, NullabilityState.Unknown, NullabilityState.Unknown, NullabilityState.Unknown }; yield return new object[] { "PropertyTupleNullNullNullNull", NullabilityState.Nullable, NullabilityState.Nullable, NullabilityState.Nullable, NullabilityState.Nullable }; // Tuple<T?, string?, string?>? yield return new object[] { "PropertyTupleNonNullNonNon", NullabilityState.Nullable, NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.NotNull }; // Tuple<T, T?, string> yield return new object[] { "PropertyTupleNullNonNullNull", NullabilityState.Nullable, NullabilityState.Nullable, NullabilityState.Nullable, NullabilityState.Nullable }; // Tuple<string?, T, T?>? yield return new object[] { "PropertyTupleNonNullNonNull", NullabilityState.Nullable, NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.Nullable }; // Tuple<T, string?, string>? yield return new object[] { "PropertyTupleNonNonNonNon", NullabilityState.NotNull, NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.NotNull }; // Tuple<string, string, T> } [Theory] [SkipOnMono("Nullability attributes trimmed on Mono")] [MemberData(nameof(GenericTuplePropertyTestData))] public void GenericTuplePropertyTest(string propertyName, NullabilityState genericParam1, NullabilityState genericParam2, NullabilityState genericParam3, NullabilityState propertyState) { PropertyInfo property = genericType.GetProperty(propertyName, flags); NullabilityInfo nullability = nullabilityContext.Create(property); Assert.Equal(propertyState, nullability.ReadState); Assert.NotEmpty(nullability.GenericTypeArguments); Assert.Equal(genericParam1, nullability.GenericTypeArguments[0].ReadState); Assert.Equal(genericParam2, nullability.GenericTypeArguments[1].ReadState); Assert.Equal(genericParam3, nullability.GenericTypeArguments[2].ReadState); Assert.Null(nullability.ElementType); } public static IEnumerable<object[]> DictionaryPropertyTestData() { yield return new object[] { "PropertyDictionaryUnknown", NullabilityState.Unknown, NullabilityState.Unknown, NullabilityState.Unknown, NullabilityState.Unknown }; yield return new object[] { "PropertyDictionaryNullNullNullNon", NullabilityState.Nullable, NullabilityState.Nullable, NullabilityState.Nullable, NullabilityState.NotNull }; yield return new object[] { "PropertyDictionaryNonNullNonNull", NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.Nullable }; yield return new object[] { "PropertyDictionaryNullNonNonNull", NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.NotNull, NullabilityState.Nullable }; yield return new object[] { "PropertyDictionaryNonNullNonNon", NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.NotNull }; yield return new object[] { "PropertyDictionaryNonNonNonNull", NullabilityState.NotNull, NullabilityState.NotNull, NullabilityState.NotNull, NullabilityState.Nullable }; yield return new object[] { "PropertyDictionaryNonNonNonNon", NullabilityState.NotNull, NullabilityState.NotNull, NullabilityState.NotNull, NullabilityState.NotNull }; } [Theory] [SkipOnMono("Nullability attributes trimmed on Mono")] [MemberData(nameof(DictionaryPropertyTestData))] public void DictionaryPropertyTest(string propertyName, NullabilityState keyState, NullabilityState valueElement, NullabilityState valueState, NullabilityState propertyState) { PropertyInfo property = testType.GetProperty(propertyName, flags); NullabilityInfo nullability = nullabilityContext.Create(property); Assert.Equal(propertyState, nullability.ReadState); Assert.NotEmpty(nullability.GenericTypeArguments); Assert.Equal(keyState, nullability.GenericTypeArguments[0].ReadState); Assert.Equal(valueState, nullability.GenericTypeArguments[1].ReadState); Assert.Equal(valueElement, nullability.GenericTypeArguments[1].ElementType.ReadState); Assert.Null(nullability.ElementType); } public static IEnumerable<object[]> GenericDictionaryPropertyTestData() { yield return new object[] { "PropertyDictionaryUnknown", NullabilityState.Unknown, NullabilityState.Unknown, NullabilityState.Unknown, NullabilityState.Unknown }; yield return new object[] { "PropertyDictionaryNullNullNullNon", NullabilityState.Nullable, NullabilityState.Nullable, NullabilityState.Nullable, NullabilityState.NotNull }; // IDictionary<T?, string?[]?> PropertyDictionaryNullNullNullNon { get; set; } yield return new object[] { "PropertyDictionaryNonNullNonNull", NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.Nullable }; // IDictionary<Type, T?[]>? PropertyDictionaryNonNullNonNull yield return new object[] { "PropertyDictionaryNullNonNonNull", NullabilityState.Nullable, NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.Nullable }; // IDictionary<T?, T[]>? PropertyDictionaryNullNonNonNull yield return new object[] { "PropertyDictionaryNonNullNonNon", NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.NotNull }; // IDictionary<Type, T?[]> PropertyDictionaryNonNullNonNon yield return new object[] { "PropertyDictionaryNonNonNonNull", NullabilityState.Nullable, NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.Nullable }; // IDictionary<T, T[]>? PropertyDictionaryNonNonNonNull yield return new object[] { "PropertyDictionaryNonNonNonNon", NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.NotNull, NullabilityState.NotNull }; // IDictionary<T, string[]> PropertyDictionaryNonNonNonNon } [Theory] [SkipOnMono("Nullability attributes trimmed on Mono")] [MemberData(nameof(GenericDictionaryPropertyTestData))] public void GenericDictionaryPropertyTest(string propertyName, NullabilityState keyState, NullabilityState valueElement, NullabilityState valueState, NullabilityState propertyState) { PropertyInfo property = genericType.GetProperty(propertyName, flags); NullabilityInfo nullability = nullabilityContext.Create(property); Assert.Equal(propertyState, nullability.ReadState); Assert.NotEmpty(nullability.GenericTypeArguments); Assert.Equal(keyState, nullability.GenericTypeArguments[0].ReadState); Assert.Equal(valueState, nullability.GenericTypeArguments[1].ReadState); Assert.Equal(valueElement, nullability.GenericTypeArguments[1].ElementType.ReadState); Assert.Null(nullability.ElementType); } [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] public void VerifyIsSupportedThrows() { RemoteInvokeOptions options = new RemoteInvokeOptions(); options.RuntimeConfigurationOptions.Add("System.Reflection.NullabilityInfoContext.IsSupported", "false"); using RemoteInvokeHandle remoteHandle = RemoteExecutor.Invoke(() => { FieldInfo field = testType.GetField("FieldNullable", flags); Assert.Throws<InvalidOperationException>(() => nullabilityContext.Create(field)); EventInfo @event = testType.GetEvent("EventNullable"); Assert.Throws<InvalidOperationException>(() => nullabilityContext.Create(@event)); PropertyInfo property = testType.GetProperty("PropertyNullable", flags); Assert.Throws<InvalidOperationException>(() => nullabilityContext.Create(property)); MethodInfo method = testType.GetMethod("MethodNullNonNullNonNon", flags); Assert.Throws<InvalidOperationException>(() => nullabilityContext.Create(method.ReturnParameter)); }, options); } [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] public void VerifyIsSupportedWorks() { RemoteInvokeOptions options = new RemoteInvokeOptions(); options.RuntimeConfigurationOptions.Add("System.Reflection.NullabilityInfoContext.IsSupported", "true"); using RemoteInvokeHandle remoteHandle = RemoteExecutor.Invoke(() => { FieldInfo field = testType.GetField("FieldNullable", flags); NullabilityInfo nullability = nullabilityContext.Create(field); Assert.Equal(NullabilityState.Nullable, nullability.ReadState); Assert.Equal(NullabilityState.Nullable, nullability.WriteState); }, options); } public static IEnumerable<object[]> GenericPropertyReferenceTypeTestData() { yield return new object[] { "PropertyNullable", NullabilityState.Nullable, NullabilityState.Nullable, typeof(TypeWithNotNullContext) }; yield return new object[] { "PropertyUnknown", NullabilityState.Unknown, NullabilityState.Unknown, typeof(TypeWithNotNullContext) }; yield return new object[] { "PropertyNonNullable", NullabilityState.Nullable, NullabilityState.Nullable, typeof(TypeWithNotNullContext) }; yield return new object[] { "PropertyDisallowNull", NullabilityState.Nullable, NullabilityState.NotNull, typeof(TypeWithNotNullContext) }; yield return new object[] { "PropertyAllowNull", NullabilityState.Nullable, NullabilityState.Nullable, typeof(TypeWithNotNullContext) }; yield return new object[] { "PropertyMaybeNull", NullabilityState.Nullable, NullabilityState.Nullable, typeof(TypeWithNotNullContext) }; } #nullable enable [Theory] [MemberData(nameof(GenericPropertyReferenceTypeTestData))] public void GenericPropertyReferenceTypeTest(string fieldName, NullabilityState readState, NullabilityState writeState, Type type) { PropertyInfo property = typeof(GenericTest<TypeWithNotNullContext?>).GetProperty(fieldName, flags)!; NullabilityInfo nullability = nullabilityContext.Create(property); Assert.Equal(readState, nullability.ReadState); Assert.Equal(writeState, nullability.WriteState); Assert.Equal(type, nullability.Type); Assert.Empty(nullability.GenericTypeArguments); Assert.Null(nullability.ElementType); property = typeof(GenericTest<TypeWithNotNullContext>).GetProperty(fieldName, flags)!; nullability = nullabilityContext.Create(property); Assert.Equal(readState, nullability.ReadState); Assert.Equal(writeState, nullability.WriteState); Assert.Equal(type, nullability.Type); property = typeof(GenericTest<>).GetProperty(fieldName, flags)!; nullability = nullabilityContext.Create(property); Assert.Equal(readState, nullability.ReadState); Assert.Equal(writeState, nullability.WriteState); } public static IEnumerable<object[]> GenericFieldReferenceTypeTestData() { yield return new object[] { "FieldNullable", NullabilityState.Nullable, NullabilityState.Nullable, typeof(TypeWithNotNullContext) }; yield return new object[] { "FieldUnknown", NullabilityState.Unknown, NullabilityState.Unknown, typeof(TypeWithNotNullContext) }; yield return new object[] { "FieldNonNullable", NullabilityState.Nullable, NullabilityState.Nullable, typeof(TypeWithNotNullContext) }; yield return new object[] { "FieldDisallowNull", NullabilityState.Nullable, NullabilityState.NotNull, typeof(TypeWithNotNullContext) }; yield return new object[] { "FieldAllowNull", NullabilityState.Nullable, NullabilityState.Nullable, typeof(TypeWithNotNullContext) }; yield return new object[] { "FieldMaybeNull", NullabilityState.Nullable, NullabilityState.Nullable, typeof(TypeWithNotNullContext) }; } [Theory] [MemberData(nameof(GenericFieldReferenceTypeTestData))] public void GenericFieldReferenceTypeTest(string fieldName, NullabilityState readState, NullabilityState writeState, Type type) { FieldInfo field = typeof(GenericTest<TypeWithNotNullContext?>).GetField(fieldName, flags)!; NullabilityInfo nullability = nullabilityContext.Create(field); Assert.Equal(readState, nullability.ReadState); Assert.Equal(writeState, nullability.WriteState); Assert.Equal(type, nullability.Type); Assert.Empty(nullability.GenericTypeArguments); Assert.Null(nullability.ElementType); field = typeof(GenericTest<TypeWithNotNullContext>).GetField(fieldName, flags)!; nullability = nullabilityContext.Create(field); Assert.Equal(readState, nullability.ReadState); Assert.Equal(writeState, nullability.WriteState); Assert.Equal(type, nullability.Type); field = typeof(GenericTest<>).GetField(fieldName, flags)!; nullability = nullabilityContext.Create(field); Assert.Equal(readState, nullability.ReadState); Assert.Equal(writeState, nullability.WriteState); } public static IEnumerable<object[]> GenericFieldValueTypeTestData() { yield return new object[] { "FieldNullable", typeof(int) }; yield return new object[] { "FieldUnknown", typeof(int) }; yield return new object[] { "FieldNonNullable", typeof(int) }; yield return new object[] { "FieldDisallowNull", typeof(int) }; yield return new object[] { "FieldAllowNull", typeof(int) }; yield return new object[] { "FieldMaybeNull", typeof(int) }; yield return new object[] { "FieldNotNull", typeof(int) }; } [Theory] [MemberData(nameof(GenericFieldValueTypeTestData))] public void GenericFieldValueTypeTest(string fieldName, Type type) { FieldInfo field = typeof(GenericTest<int>).GetField(fieldName, flags)!; NullabilityInfo nullability = nullabilityContext.Create(field); Assert.Equal(NullabilityState.NotNull, nullability.ReadState); Assert.Equal(NullabilityState.NotNull, nullability.WriteState); Assert.Equal(type, nullability.Type); } public static IEnumerable<object[]> GenericFieldNullableValueTypeTestData() { yield return new object[] { "FieldNullable", NullabilityState.Nullable, NullabilityState.Nullable, typeof(int?) }; yield return new object[] { "FieldUnknown", NullabilityState.Nullable, NullabilityState.Nullable, typeof(int?) }; yield return new object[] { "FieldNonNullable", NullabilityState.Nullable, NullabilityState.Nullable, typeof(int?) }; yield return new object[] { "FieldDisallowNull", NullabilityState.Nullable, NullabilityState.NotNull, typeof(int?) }; yield return new object[] { "FieldAllowNull", NullabilityState.Nullable, NullabilityState.Nullable, typeof(int?) }; yield return new object[] { "FieldMaybeNull", NullabilityState.Nullable, NullabilityState.Nullable, typeof(int?) }; yield return new object[] { "FieldNotNull", NullabilityState.NotNull, NullabilityState.Nullable, typeof(int?) }; } [Theory] [MemberData(nameof(GenericFieldNullableValueTypeTestData))] public void GenericFieldNullableValueTypeTest(string fieldName, NullabilityState readState, NullabilityState writeState, Type type) { FieldInfo field = typeof(GenericTest<int?>).GetField(fieldName, flags)!; NullabilityInfo nullability = nullabilityContext.Create(field); Assert.Equal(readState, nullability.ReadState); Assert.Equal(writeState, nullability.WriteState); Assert.Equal(type, nullability.Type); } public static IEnumerable<object[]> GenericNotNullConstraintFieldsTestData() { yield return new object[] { "FieldNullable", NullabilityState.Nullable, NullabilityState.Nullable, typeof(string) }; yield return new object[] { "FieldUnknown", NullabilityState.Unknown, NullabilityState.Unknown, typeof(string) }; yield return new object[] { "FieldNullableEnabled", NullabilityState.NotNull, NullabilityState.NotNull, typeof(string) }; } [Theory] [MemberData(nameof(GenericNotNullConstraintFieldsTestData))] public void GenericNotNullConstraintFieldsTest(string fieldName, NullabilityState readState, NullabilityState writeState, Type type) { FieldInfo field = typeof(GenericTestConstrainedNotNull<string>).GetField(fieldName, flags)!; NullabilityInfo nullability = nullabilityContext.Create(field); Assert.Equal(readState, nullability.ReadState); Assert.Equal(writeState, nullability.WriteState); Assert.Equal(type, nullability.Type); } public static IEnumerable<object[]> GenericNotnullConstraintPropertiesTestData() { yield return new object[] { "PropertyNullable", NullabilityState.Nullable, NullabilityState.Nullable, typeof(string) }; yield return new object[] { "PropertyUnknown", NullabilityState.Unknown, NullabilityState.Unknown, typeof(string) }; yield return new object[] { "PropertyNullableEnabled", NullabilityState.NotNull, NullabilityState.NotNull, typeof(string) }; } [Theory] [MemberData(nameof(GenericNotnullConstraintPropertiesTestData))] public void GenericNotNullConstraintPropertiesTest(string propertyName, NullabilityState readState, NullabilityState writeState, Type type) { PropertyInfo property = typeof(GenericTestConstrainedNotNull<string>).GetProperty(propertyName, flags)!; NullabilityInfo nullability = nullabilityContext.Create(property); Assert.Equal(readState, nullability.ReadState); Assert.Equal(writeState, nullability.WriteState); Assert.Equal(type, nullability.Type); } public static IEnumerable<object[]> GenericStructConstraintFieldsTestData() { yield return new object[] { "FieldNullable", NullabilityState.Nullable, NullabilityState.Nullable, typeof(int?) }; yield return new object[] { "FieldUnknown", NullabilityState.NotNull, NullabilityState.NotNull, typeof(int) }; yield return new object[] { "FieldNullableEnabled", NullabilityState.NotNull, NullabilityState.NotNull, typeof(int) }; } [Theory] [MemberData(nameof(GenericStructConstraintFieldsTestData))] public void GenericStructConstraintFieldsTest(string fieldName, NullabilityState readState, NullabilityState writeState, Type type) { FieldInfo field = typeof(GenericTestConstrainedStruct<int>).GetField(fieldName, flags)!; NullabilityInfo nullability = nullabilityContext.Create(field); Assert.Equal(readState, nullability.ReadState); Assert.Equal(writeState, nullability.WriteState); Assert.Equal(type, nullability.Type); } public static IEnumerable<object[]> GenericStructConstraintPropertiesTestData() { yield return new object[] { "PropertyNullable", NullabilityState.Nullable, NullabilityState.Nullable, typeof(int?) }; yield return new object[] { "PropertyUnknown", NullabilityState.NotNull, NullabilityState.NotNull, typeof(int) }; yield return new object[] { "PropertyNullableEnabled", NullabilityState.NotNull, NullabilityState.NotNull, typeof(int) }; } [Theory] [MemberData(nameof(GenericStructConstraintPropertiesTestData))] public void GenericStructConstraintPropertiesTest(string propertyName, NullabilityState readState, NullabilityState writeState, Type type) { PropertyInfo property = typeof(GenericTestConstrainedStruct<int>).GetProperty(propertyName, flags)!; NullabilityInfo nullability = nullabilityContext.Create(property); Assert.Equal(readState, nullability.ReadState); Assert.Equal(writeState, nullability.WriteState); Assert.Equal(type, nullability.Type); } [Fact] [SkipOnMono("Nullability attributes trimmed on Mono")] public void GenericListTest() { Type listNullable = typeof(List<string?>); MethodInfo addNullable = listNullable.GetMethod("Add")!; NullabilityInfo nullability = nullabilityContext.Create(addNullable.GetParameters()[0]); Assert.Equal(NullabilityState.Nullable, nullability.ReadState); Assert.Equal(NullabilityState.Nullable, nullability.WriteState); Assert.Equal(typeof(string), nullability.Type); Type listNotNull = typeof(List<string>); MethodInfo addNotNull = listNotNull.GetMethod("Add")!; nullability = nullabilityContext.Create(addNotNull.GetParameters()[0]); Assert.Equal(NullabilityState.Nullable, nullability.ReadState); Assert.Equal(typeof(string), nullability.Type); Type listOpen = typeof(List<>); MethodInfo addOpen = listOpen.GetMethod("Add")!; nullability = nullabilityContext.Create(addOpen.GetParameters()[0]); Assert.Equal(NullabilityState.Nullable, nullability.ReadState); } [Fact] [SkipOnMono("Nullability attributes trimmed on Mono")] public void GenericListAndDictionaryFieldTest() { Type typeNullable = typeof(GenericTest<string?>); FieldInfo listOfTNullable = typeNullable.GetField("FieldListOfT")!; NullabilityInfo listNullability = nullabilityContext.Create(listOfTNullable); Assert.Equal(NullabilityState.Nullable, listNullability.GenericTypeArguments[0].ReadState); Assert.Equal(typeof(string), listNullability.GenericTypeArguments[0].Type); FieldInfo dictStringToTNullable = typeNullable.GetField("FieldDictionaryStringToT")!; NullabilityInfo dictNullability = nullabilityContext.Create(dictStringToTNullable); Assert.Equal(NullabilityState.NotNull, dictNullability.GenericTypeArguments[0].ReadState); Assert.Equal(NullabilityState.Nullable, dictNullability.GenericTypeArguments[1].ReadState); Assert.Equal(typeof(string), dictNullability.GenericTypeArguments[1].Type); Type typeNonNull = typeof(GenericTest<string>); FieldInfo listOfTNotNull = typeNonNull.GetField("FieldListOfT")!; listNullability = nullabilityContext.Create(listOfTNotNull); Assert.Equal(NullabilityState.Nullable, listNullability.GenericTypeArguments[0].ReadState); Assert.Equal(typeof(string), listNullability.GenericTypeArguments[0].Type); FieldInfo dictStringToTNotNull = typeNonNull.GetField("FieldDictionaryStringToT")!; dictNullability = nullabilityContext.Create(dictStringToTNotNull); Assert.Equal(NullabilityState.NotNull, dictNullability.GenericTypeArguments[0].ReadState); Assert.Equal(NullabilityState.Nullable, dictNullability.GenericTypeArguments[1].ReadState); Assert.Equal(typeof(string), dictNullability.GenericTypeArguments[1].Type); Type typeOpen = typeof(GenericTest<>); FieldInfo listOfTOpen = typeOpen.GetField("FieldListOfT")!; listNullability = nullabilityContext.Create(listOfTOpen); Assert.Equal(NullabilityState.Nullable, listNullability.GenericTypeArguments[0].ReadState); // Assert.Equal(typeof(T), listNullability.TypeArguments[0].Type); FieldInfo dictStringToTOpen = typeOpen.GetField("FieldDictionaryStringToT")!; dictNullability = nullabilityContext.Create(dictStringToTOpen); Assert.Equal(NullabilityState.NotNull, dictNullability.GenericTypeArguments[0].ReadState); Assert.Equal(NullabilityState.Nullable, dictNullability.GenericTypeArguments[1].ReadState); } public static IEnumerable<object[]> MethodReturnParameterTestData() { yield return new object[] { "MethodReturnsUnknown", NullabilityState.Unknown, NullabilityState.Unknown }; yield return new object[] { "MethodReturnsNullNon", NullabilityState.Nullable, NullabilityState.NotNull }; yield return new object[] { "MethodReturnsNullNull", NullabilityState.Nullable, NullabilityState.Nullable }; yield return new object[] { "MethodReturnsNonNull", NullabilityState.NotNull, NullabilityState.Nullable }; yield return new object[] { "MethodReturnsNonNotNull", NullabilityState.NotNull, NullabilityState.NotNull }; yield return new object[] { "MethodReturnsNonMaybeNull", NullabilityState.NotNull, NullabilityState.Nullable }; yield return new object[] { "MethodReturnsNonNon", NullabilityState.NotNull, NullabilityState.NotNull }; } [Theory] [SkipOnMono("Nullability attributes trimmed on Mono")] [MemberData(nameof(MethodReturnParameterTestData))] public void MethodReturnParameterTest(string methodName, NullabilityState elementState, NullabilityState readState) { MethodInfo method = testType.GetMethod(methodName, flags)!; NullabilityInfo nullability = nullabilityContext.Create(method.ReturnParameter); Assert.Equal(readState, nullability.ReadState); //Assert.Equal(readState, nullability.WriteState); Assert.NotNull(nullability.ElementType); Assert.Equal(elementState, nullability.ElementType!.ReadState); Assert.Empty(nullability.GenericTypeArguments); } public static IEnumerable<object[]> MethodReturnsTupleTestData() { // public Tuple<string?, string>? MethodReturnsTupleNullNonNull() => null; yield return new object[] { "MethodReturnsTupleNullNonNull", NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.Nullable }; // public Tuple<string?, int> MethodReturnsTupleNullNonNot() => null! yield return new object[] { "MethodReturnsTupleNullNonNot", NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.NotNull }; // public (int?, string)? MethodReturnsValueTupleNullNonNull() => null; yield return new object[] { "MethodReturnsValueTupleNullNonNull", NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.Nullable }; // public (string?, string) MethodReturnsValueTupleNullNonNon() => (null, string.Empty); yield return new object[] { "MethodReturnsValueTupleNullNonNon", NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.NotNull }; } [Theory] [SkipOnMono("Nullability attributes trimmed on Mono")] [MemberData(nameof(MethodReturnsTupleTestData))] public void MethodReturnsTupleTest(string methodName, NullabilityState param1, NullabilityState param2, NullabilityState readState) { MethodInfo method = testType.GetMethod(methodName, flags)!; NullabilityInfo nullability = nullabilityContext.Create(method.ReturnParameter); Assert.Equal(readState, nullability.ReadState); Assert.Null(nullability.ElementType); Assert.Equal(param1, nullability.GenericTypeArguments[0].ReadState); Assert.Equal(param2, nullability.GenericTypeArguments[1].ReadState); } public static IEnumerable<object[]> MethodGenericReturnParameterTestData() { yield return new object[] { "MethodReturnsUnknown", NullabilityState.Unknown, NullabilityState.Unknown }; yield return new object[] { "MethodReturnsGeneric", NullabilityState.Nullable, NullabilityState.Unknown }; yield return new object[] { "MethodReturnsNullGeneric", NullabilityState.Nullable, NullabilityState.Unknown }; yield return new object[] { "MethodReturnsGenericNotNull", NullabilityState.NotNull, NullabilityState.Unknown }; yield return new object[] { "MethodReturnsGenericMaybeNull", NullabilityState.Nullable, NullabilityState.Unknown }; yield return new object[] { "MethodNonNullListNullGeneric", NullabilityState.NotNull, NullabilityState.Nullable }; yield return new object[] { "MethodNullListNonNullGeneric", NullabilityState.Nullable, NullabilityState.Nullable }; } [Theory] [SkipOnMono("Nullability attributes trimmed on Mono")] [MemberData(nameof(MethodGenericReturnParameterTestData))] public void MethodGenericReturnParameterTest(string methodName, NullabilityState readState, NullabilityState elementState) { MethodInfo method = typeof(GenericTest<TypeWithNotNullContext?>).GetMethod(methodName, flags)!; NullabilityInfo nullability = nullabilityContext.Create(method.ReturnParameter); Assert.Equal(readState, nullability.ReadState); if (nullability.GenericTypeArguments.Length > 0) { Assert.Equal(elementState, nullability.GenericTypeArguments[0].ReadState); } } public static IEnumerable<object[]> MethodParametersTestData() { yield return new object[] { "MethodParametersUnknown", NullabilityState.Unknown, NullabilityState.Unknown, NullabilityState.Unknown, NullabilityState.Unknown, NullabilityState.Unknown }; yield return new object[] { "MethodNullNonNullNonNon", NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.NotNull }; yield return new object[] { "MethodNonNullNonNullNotNull", NullabilityState.NotNull, NullabilityState.NotNull, NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.NotNull }; yield return new object[] { "MethodNullNonNullNullNon", NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.Nullable, NullabilityState.NotNull }; yield return new object[] { "MethodAllowNullNonNonNonNull", NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.NotNull, NullabilityState.NotNull, NullabilityState.Nullable }; } [Theory] [SkipOnMono("Nullability attributes trimmed on Mono")] [MemberData(nameof(MethodParametersTestData))] public void MethodParametersTest(string methodName, NullabilityState stringState, NullabilityState dictKey, NullabilityState dictValueElement, NullabilityState dictValue, NullabilityState dictionaryState) { ParameterInfo[] parameters = testType.GetMethod(methodName, flags)!.GetParameters(); NullabilityInfo stringNullability = nullabilityContext.Create(parameters[0]); NullabilityInfo dictionaryNullability = nullabilityContext.Create(parameters[1]); Assert.Equal(stringState, stringNullability.WriteState); Assert.Equal(dictionaryState, dictionaryNullability.ReadState); Assert.NotEmpty(dictionaryNullability.GenericTypeArguments); Assert.Equal(dictKey, dictionaryNullability.GenericTypeArguments[0].ReadState); Assert.Equal(dictValue, dictionaryNullability.GenericTypeArguments[1].ReadState); Assert.Equal(dictValueElement, dictionaryNullability.GenericTypeArguments[1].ElementType!.ReadState); Assert.Null(dictionaryNullability.ElementType); } public static IEnumerable<object[]> MethodGenericParametersTestData() { yield return new object[] { "MethodParametersUnknown", NullabilityState.Unknown, NullabilityState.Unknown, NullabilityState.Unknown, NullabilityState.Unknown }; yield return new object[] { "MethodArgsNullGenericNullDictValueGeneric", NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.Nullable }; yield return new object[] { "MethodArgsGenericDictValueNullGeneric", NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.NotNull }; } [Theory] [SkipOnMono("Nullability attributes trimmed on Mono")] [MemberData(nameof(MethodGenericParametersTestData))] public void MethodGenericParametersTest(string methodName, NullabilityState param1State, NullabilityState dictKey, NullabilityState dictValue, NullabilityState dictionaryState) { ParameterInfo[] parameters = typeof(GenericTest<TypeWithNotNullContext>).GetMethod(methodName, flags)!.GetParameters(); NullabilityInfo stringNullability = nullabilityContext.Create(parameters[0]); NullabilityInfo dictionaryNullability = nullabilityContext.Create(parameters[1]); Assert.Equal(param1State, stringNullability.WriteState); Assert.Equal(dictionaryState, dictionaryNullability.ReadState); Assert.NotEmpty(dictionaryNullability.GenericTypeArguments); Assert.Equal(dictKey, dictionaryNullability.GenericTypeArguments[0].ReadState); Assert.Equal(dictValue, dictionaryNullability.GenericTypeArguments[1].ReadState); } public static IEnumerable<object[]> StringTypeTestData() { yield return new object[] { "Format", NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.Nullable, new Type[] { typeof(string), typeof(object), typeof(object) } }; yield return new object[] { "ReplaceCore", NullabilityState.Unknown, NullabilityState.Unknown, NullabilityState.Unknown, new Type[] { typeof(string), typeof(string), typeof(CompareInfo), typeof(CompareOptions) } }; yield return new object[] { "Join", NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.NotNull, new Type[] { typeof(string), typeof(String?[]), typeof(int), typeof(int) } }; } [Theory] [SkipOnMono("Nullability attributes trimmed on Mono")] [MemberData(nameof(StringTypeTestData))] public void NullablePublicOnlyStringTypeTest(string methodName, NullabilityState param1State, NullabilityState param2State, NullabilityState param3State, Type[] types) { ParameterInfo[] parameters = stringType.GetMethod(methodName, flags, types)!.GetParameters(); NullabilityInfo param1 = nullabilityContext.Create(parameters[0]); NullabilityInfo param2 = nullabilityContext.Create(parameters[1]); NullabilityInfo param3 = nullabilityContext.Create(parameters[2]); Assert.Equal(param1State, param1.ReadState); Assert.Equal(param2State, param2.ReadState); Assert.Equal(param3State, param3.ReadState); if (param2.ElementType != null) { Assert.Equal(NullabilityState.Nullable, param2.ElementType.ReadState); } } [Fact] [SkipOnMono("Nullability attributes trimmed on Mono")] public void NullablePublicOnlyOtherTypesTest() { Type type = typeof(Type); FieldInfo privateNullableField = type.GetField("s_defaultBinder", flags)!; NullabilityInfo info = nullabilityContext.Create(privateNullableField); Assert.Equal(NullabilityState.Unknown, info.ReadState); Assert.Equal(NullabilityState.Unknown, info.WriteState); MethodInfo internalNotNullableMethod = type.GetMethod("GetRootElementType", flags)!; info = nullabilityContext.Create(internalNotNullableMethod.ReturnParameter); Assert.Equal(NullabilityState.NotNull, info.ReadState); Assert.Equal(NullabilityState.NotNull, info.WriteState); PropertyInfo publicNullableProperty = type.GetProperty("DeclaringType", flags)!; info = nullabilityContext.Create(publicNullableProperty); Assert.Equal(NullabilityState.Nullable, info.ReadState); Assert.Equal(NullabilityState.Unknown, info.WriteState); PropertyInfo publicGetPrivateSetNullableProperty = typeof(FileSystemEntry).GetProperty("Directory", flags)!; info = nullabilityContext.Create(publicGetPrivateSetNullableProperty); Assert.Equal(NullabilityState.NotNull, info.ReadState); Assert.Equal(NullabilityState.NotNull, info.WriteState); MethodInfo protectedNullableReturnMethod = type.GetMethod("GetPropertyImpl", flags)!; info = nullabilityContext.Create(protectedNullableReturnMethod.ReturnParameter); Assert.Equal(NullabilityState.Nullable, info.ReadState); Assert.Equal(NullabilityState.Nullable, info.WriteState); MethodInfo privateValueTypeReturnMethod = type.GetMethod("BinarySearch", flags)!; info = nullabilityContext.Create(privateValueTypeReturnMethod.ReturnParameter); Assert.Equal(NullabilityState.NotNull, info.ReadState); Assert.Equal(NullabilityState.NotNull, info.WriteState); Type regexType = typeof(Regex); FieldInfo protectedInternalNullableField = regexType.GetField("pattern", flags)!; info = nullabilityContext.Create(protectedInternalNullableField); Assert.Equal(NullabilityState.Nullable, info.ReadState); Assert.Equal(NullabilityState.Nullable, info.WriteState); privateNullableField = regexType.GetField("_runner", flags)!; info = nullabilityContext.Create(privateNullableField); Assert.Equal(NullabilityState.Unknown, info.ReadState); Assert.Equal(NullabilityState.Unknown, info.WriteState); ConstructorInfo privateConstructor = typeof(IndexOutOfRangeException) .GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, new[] { typeof(SerializationInfo), typeof(StreamingContext) })!; info = nullabilityContext.Create(privateConstructor.GetParameters()[0]); Assert.Equal(NullabilityState.Unknown, info.WriteState); } public static IEnumerable<object[]> DifferentContextTestData() { yield return new object[] { "PropertyDisabled", NullabilityState.Unknown, NullabilityState.Unknown, typeof(string) }; yield return new object[] { "PropertyDisabledAllowNull", NullabilityState.Unknown, NullabilityState.Nullable, typeof(string) }; yield return new object[] { "PropertyDisabledMaybeNull", NullabilityState.Nullable, NullabilityState.Unknown, typeof(string) }; yield return new object[] { "PropertyEnabledAllowNull", NullabilityState.NotNull, NullabilityState.Nullable, typeof(string) }; yield return new object[] { "PropertyEnabledNotNull", NullabilityState.NotNull, NullabilityState.Nullable, typeof(string) }; yield return new object[] { "PropertyEnabledMaybeNull", NullabilityState.Nullable, NullabilityState.NotNull, typeof(string) }; yield return new object[] { "PropertyEnabledDisallowNull", NullabilityState.Nullable, NullabilityState.NotNull, typeof(string) }; yield return new object[] { "PropertyEnabledNullable", NullabilityState.Nullable, NullabilityState.Nullable, typeof(string) }; yield return new object[] { "PropertyEnabledNonNullable", NullabilityState.NotNull, NullabilityState.NotNull, typeof(string) }; } [Theory] [MemberData(nameof(DifferentContextTestData))] public void NullabilityDifferentContextTest(string propertyName, NullabilityState readState, NullabilityState writeState, Type type) { Type noContext = typeof(TypeWithNoContext); PropertyInfo property = noContext.GetProperty(propertyName, flags)!; NullabilityInfo nullability = nullabilityContext.Create(property); Assert.Equal(readState, nullability.ReadState); Assert.Equal(writeState, nullability.WriteState); Assert.Equal(type, nullability.Type); Type nullableContext = typeof(TypeWithNullableContext); property = nullableContext.GetProperty(propertyName, flags)!; nullability = nullabilityContext.Create(property); Assert.Equal(readState, nullability.ReadState); Assert.Equal(writeState, nullability.WriteState); Assert.Equal(type, nullability.Type); } [Fact] public void AttributedParametersTest() { Type type = typeof(TypeWithNullableContext); // bool NotNullWhenParameter([DisallowNull] string? disallowNull, [NotNullWhen(true)] ref string? notNullWhen, Type? nullableType); ParameterInfo[] notNullWhenParameters = type.GetMethod("NotNullWhenParameter", flags)!.GetParameters(); NullabilityInfo disallowNull = nullabilityContext.Create(notNullWhenParameters[0]); NullabilityInfo notNullWhen = nullabilityContext.Create(notNullWhenParameters[1]); Assert.Equal(NullabilityState.Nullable, disallowNull.ReadState); Assert.Equal(NullabilityState.NotNull, disallowNull.WriteState); Assert.Equal(NullabilityState.Nullable, notNullWhen.ReadState); Assert.Equal(NullabilityState.Nullable, notNullWhen.WriteState); Assert.Equal(NullabilityState.Nullable, nullabilityContext.Create(notNullWhenParameters[1]).ReadState); // bool MaybeNullParameters([MaybeNull] string maybeNull, [MaybeNullWhen(false)] out string maybeNullWhen, Type? nullableType) ParameterInfo[] maybeNullParameters = type.GetMethod("MaybeNullParameters", flags)!.GetParameters(); NullabilityInfo maybeNull = nullabilityContext.Create(maybeNullParameters[0]); NullabilityInfo maybeNullWhen = nullabilityContext.Create(maybeNullParameters[1]); Assert.Equal(NullabilityState.Nullable, maybeNull.ReadState); Assert.Equal(NullabilityState.NotNull, maybeNull.WriteState); Assert.Equal(NullabilityState.Nullable, maybeNullWhen.ReadState); Assert.Equal(NullabilityState.NotNull, maybeNullWhen.WriteState); Assert.Equal(NullabilityState.Nullable, nullabilityContext.Create(maybeNullParameters[1]).ReadState); // string? AllowNullParameter([AllowNull] string allowNull, [NotNullIfNotNull("allowNull")] string? notNullIfNotNull) ParameterInfo[] allowNullParameter = type.GetMethod("AllowNullParameter", flags)!.GetParameters(); NullabilityInfo allowNull = nullabilityContext.Create(allowNullParameter[0]); NullabilityInfo notNullIfNotNull = nullabilityContext.Create(allowNullParameter[1]); Assert.Equal(NullabilityState.NotNull, allowNull.ReadState); Assert.Equal(NullabilityState.Nullable, allowNull.WriteState); Assert.Equal(NullabilityState.Nullable, notNullIfNotNull.ReadState); Assert.Equal(NullabilityState.Nullable, notNullIfNotNull.WriteState); Assert.Equal(NullabilityState.Nullable, nullabilityContext.Create(allowNullParameter[1]).ReadState); // [return: NotNullIfNotNull("nullable")] public string? NullableNotNullIfNotNullReturn(string? nullable, [NotNull] ref string? readNotNull) ParameterInfo[] nullableNotNullIfNotNullReturn = type.GetMethod("NullableNotNullIfNotNullReturn", flags)!.GetParameters(); NullabilityInfo returnNotNullIfNotNull = nullabilityContext.Create(type.GetMethod("NullableNotNullIfNotNullReturn", flags)!.ReturnParameter); NullabilityInfo readNotNull = nullabilityContext.Create(nullableNotNullIfNotNullReturn[1]); Assert.Equal(NullabilityState.Nullable, returnNotNullIfNotNull.ReadState); Assert.Equal(NullabilityState.Nullable, returnNotNullIfNotNull.WriteState); Assert.Equal(NullabilityState.NotNull, readNotNull.ReadState); Assert.Equal(NullabilityState.Nullable, readNotNull.WriteState); Assert.Equal(NullabilityState.Nullable, nullabilityContext.Create(nullableNotNullIfNotNullReturn[0]).ReadState); // public bool TryGetOutParameters(string id, [NotNullWhen(true)] out string? value, [MaybeNullWhen(false)] out string value2) ParameterInfo[] tryGetOutParameters = type.GetMethod("TryGetOutParameters", flags)!.GetParameters(); NullabilityInfo notNullWhenParam = nullabilityContext.Create(tryGetOutParameters[1]); NullabilityInfo maybeNullWhenParam = nullabilityContext.Create(tryGetOutParameters[2]); Assert.Equal(NullabilityState.Nullable, notNullWhenParam.ReadState); Assert.Equal(NullabilityState.Nullable, notNullWhenParam.WriteState); Assert.Equal(NullabilityState.Nullable, maybeNullWhenParam.ReadState); Assert.Equal(NullabilityState.NotNull, maybeNullWhenParam.WriteState); Assert.Equal(NullabilityState.NotNull, nullabilityContext.Create(tryGetOutParameters[0]).ReadState); } public static IEnumerable<object[]> NestedGenericsCorrectOrderData() { yield return new object[] { "MethodReturnsNonTupleNonTupleNullStringNullStringNullString", new[] { NullabilityState.NotNull, NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.Nullable, NullabilityState.Nullable }, new[] { typeof(Tuple<Tuple<string, string>, string>), typeof(Tuple<string, string>), typeof(string), typeof(string), typeof(string) } }; yield return new object[] { "MethodReturnsNonTupleNonTupleNullStringNullStringNonString", new[] { NullabilityState.NotNull, NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.Nullable, NullabilityState.NotNull }, new[] { typeof(Tuple<Tuple<string, string>, string>), typeof(Tuple<string, string>), typeof(string), typeof(string), typeof(string) } }; } [Theory] [MemberData(nameof(NestedGenericsCorrectOrderData))] [SkipOnMono("Nullability attributes trimmed on Mono")] public void NestedGenericsCorrectOrderTest(string methodName, NullabilityState[] nullStates, Type[] types) { NullabilityInfo parentInfo = nullabilityContext.Create(typeof(TypeWithNotNullContext).GetMethod(methodName)!.ReturnParameter); var dataIndex = 0; Examine(parentInfo); Assert.Equal(nullStates.Length, dataIndex); Assert.Equal(types.Length, dataIndex); void Examine(NullabilityInfo info) { Assert.Equal(types[dataIndex], info.Type); Assert.Equal(nullStates[dataIndex++], info.ReadState); for (var i = 0; i < info.GenericTypeArguments.Length; i++) { Examine(info.GenericTypeArguments[i]); } } } public static IEnumerable<object[]> NestedGenericsReturnParameterData() { // public IEnumerable<Tuple<(string name, object? value), int>?> MethodReturnsEnumerableNonTupleNonNonNullValueTupleNonNullNon() => null!; yield return new object[] { "MethodReturnsEnumerableNonTupleNonNonNullValueTupleNonNullNon", NullabilityState.NotNull, NullabilityState.NotNull, NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.Nullable }; // public IEnumerable<Tuple<(string? name, object value)?, int>?>? MethodReturnsEnumerableNullTupleNullNonNullValueTupleNullNonNull() => null!; yield return new object[] { "MethodReturnsEnumerableNullTupleNullNonNullValueTupleNullNonNull", NullabilityState.Nullable, NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.Nullable, NullabilityState.NotNull }; // public IEnumerable<Tuple<Tuple<string, object?>, int>?> MethodReturnsEnumerableNonTupleNonNonNullTupleNonNullNon() => null!; yield return new object[] { "MethodReturnsEnumerableNonTupleNonNonNullTupleNonNullNon", NullabilityState.NotNull, NullabilityState.NotNull, NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.Nullable }; // public IEnumerable<GenericStruct<Tuple<string, object?>?, int>?>? MethodReturnsEnumerableNullStructNullNonNonTupleNonNullNull() => null; yield return new object[] { "MethodReturnsEnumerableNullStructNullNonNullTupleNonNullNull", NullabilityState.Nullable, NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.Nullable }; // public IEnumerable<Tuple<GenericStruct<string, object?>?, int>?>? MethodReturnsEnumerableNullTupleNullNonNullStructNonNullNull() => null; yield return new object[] { "MethodReturnsEnumerableNullTupleNullNonNullStructNonNullNull", NullabilityState.Nullable, NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.Nullable }; // public IEnumerable<(GenericStruct<string, object?> str, int? count)> MethodReturnsEnumerableNonValueTupleNonNullNonTupleNonNullNon() => null!; yield return new object[] { "MethodReturnsEnumerableNonValueTupleNonNullNonStructNonNullNon", NullabilityState.NotNull, NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.NotNull, NullabilityState.Nullable }; } [Theory] [MemberData(nameof(NestedGenericsReturnParameterData))] [SkipOnMono("Nullability attributes trimmed on Mono")] public void NestedGenericsReturnParameterTest(string methodName, NullabilityState enumState, NullabilityState innerTupleState, NullabilityState intState, NullabilityState outerTupleState, NullabilityState stringState, NullabilityState objectState) { NullabilityInfo enumerabeNullability = nullabilityContext.Create(typeof(TypeWithNotNullContext).GetMethod(methodName, flags)!.ReturnParameter); Assert.Equal(enumState, enumerabeNullability.ReadState); NullabilityInfo tupleNullability = enumerabeNullability.GenericTypeArguments[0]; Assert.Equal(outerTupleState, tupleNullability.ReadState); Assert.Equal(innerTupleState, tupleNullability.GenericTypeArguments[0].ReadState); Assert.Equal(intState, tupleNullability.GenericTypeArguments[1].ReadState); NullabilityInfo valueTupleNullability = tupleNullability.GenericTypeArguments[0]; Assert.Equal(innerTupleState, valueTupleNullability.ReadState); Assert.Equal(stringState, valueTupleNullability.GenericTypeArguments[0].ReadState); Assert.Equal(objectState, valueTupleNullability.GenericTypeArguments[1].ReadState); } public static IEnumerable<object[]> RefReturnData() { yield return new object[] { "RefReturnUnknown", NullabilityState.Unknown, NullabilityState.Unknown, NullabilityState.Unknown, NullabilityState.Unknown }; // [return: MaybeNull] public ref string RefReturnMaybeNull([DisallowNull] ref string? id) yield return new object[] { "RefReturnMaybeNull", NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.NotNull }; // public ref string RefReturnNotNullable([MaybeNull] ref string id) yield return new object[] { "RefReturnNotNullable", NullabilityState.NotNull, NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.NotNull }; // [return: NotNull]public ref string? RefReturnNotNull([NotNull] ref string? id) yield return new object[] { "RefReturnNotNull", NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.Nullable }; // publiic ref string? RefReturnNullable([AllowNull] ref string id) yield return new object[] { "RefReturnNullable", NullabilityState.Nullable, NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.Nullable }; } [Theory] [MemberData(nameof(RefReturnData))] public void RefReturnTestTest(string methodName, NullabilityState retReadState, NullabilityState retWriteState, NullabilityState paramReadState, NullabilityState paramWriteState) { MethodInfo method = typeof(TypeWithNullableContext).GetMethod(methodName, flags)!; NullabilityInfo returnNullability = nullabilityContext.Create(method.ReturnParameter); NullabilityInfo paramNullability = nullabilityContext.Create(method.GetParameters()[0]); Assert.Equal(retReadState, returnNullability.ReadState); Assert.Equal(retWriteState, returnNullability.WriteState); Assert.Equal(paramReadState, paramNullability.ReadState); Assert.Equal(paramWriteState, paramNullability.WriteState); } public static IEnumerable<object[]> ValueTupleTestData() { // public (int, string) UnknownValueTuple; [0] yield return new object[] { "UnknownValueTuple", NullabilityState.NotNull, NullabilityState.Unknown, NullabilityState.NotNull }; // public (string?, object) NullNonNonValueTuple; [0, 2, 1] yield return new object[] { "Null_Non_Non_ValueTuple", NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.NotNull }; // public (string?, object)? Null_Non_Null_ValueTuple; [0, 2, 1] yield return new object[] { "Null_Non_Null_ValueTuple", NullabilityState.Nullable, NullabilityState.NotNull, NullabilityState.Nullable }; // public (int, int?)? Non_Null_Null_ValueTuple; [0] yield return new object[] { "Non_Null_Null_ValueTuple", NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.Nullable }; // public (int, string) Non_Non_Non_ValueTuple; [0, 1] yield return new object[] { "Non_Non_Non_ValueTuple", NullabilityState.NotNull, NullabilityState.NotNull, NullabilityState.NotNull }; // public (int, string?) Non_Null_Non_ValueTuple; [0, 2] yield return new object[] { "Non_Null_Non_ValueTuple", NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.NotNull }; } [Theory] [MemberData(nameof(ValueTupleTestData))] [SkipOnMono("Nullability attributes trimmed on Mono")] public void TestValueTupleGenericTypeParameters(string fieldName, NullabilityState param1, NullabilityState param2, NullabilityState fieldState) { var tupleInfo = nullabilityContext.Create(testType.GetField(fieldName)!); Assert.Equal(fieldState, tupleInfo.ReadState); Assert.Equal(param1, tupleInfo.GenericTypeArguments[0].ReadState); Assert.Equal(param2, tupleInfo.GenericTypeArguments[1].ReadState); } public static IEnumerable<object?[]> GenericInheritanceTestData() { yield return new object?[] { typeof(ListOfUnconstrained<string?>), NullabilityState.Nullable, null }; yield return new object?[] { typeof(ListUnconstrainedOfNullable<string>), NullabilityState.Nullable, null }; yield return new object?[] { typeof(ListUnconstrainedOfNullableOfObject<>), NullabilityState.NotNull, null }; yield return new object?[] { typeof(ListOfArrayOfNullableString), NullabilityState.NotNull, NullabilityState.Nullable }; yield return new object?[] { typeof(ListOfNotNull<ListOfNotNull<object>>), NullabilityState.NotNull, NullabilityState.NotNull }; yield return new object?[] { typeof(ListOfListOfObject<string?>), NullabilityState.NotNull, NullabilityState.NotNull }; yield return new object?[] { typeof(ListMultiGenericOfNotNull<object?, string, string?>), NullabilityState.NotNull, null }; } [Theory] [MemberData(nameof(GenericInheritanceTestData))] [SkipOnMono("Nullability attributes trimmed on Mono")] public void TestGenericInheritance(Type listType, NullabilityState parameterState, NullabilityState? subState) { var addParameterInfo = nullabilityContext.Create(listType.GetMethod("Add")!.GetParameters()[0]); Validate(addParameterInfo); var copyToParameterInfo = nullabilityContext.Create( listType.GetMethod("CopyTo", new[] { addParameterInfo.Type.MakeArrayType() })! .GetParameters()[0]); Assert.Equal(NullabilityState.NotNull, copyToParameterInfo.ReadState); Assert.Equal(NullabilityState.NotNull, copyToParameterInfo.WriteState); Assert.NotNull(copyToParameterInfo.ElementType); Validate(copyToParameterInfo.ElementType!); void Validate(NullabilityInfo info) { Assert.Equal(parameterState, info.ReadState); Assert.Equal(parameterState, info.WriteState); if (subState != null) { NullabilityInfo subInfo = info.ElementType ?? info.GenericTypeArguments[0]; Assert.Equal(subState, subInfo.ReadState); Assert.Equal(subState, subInfo.WriteState); Assert.True(info.GenericTypeArguments.Length <= 1); } else { Assert.Null(info.ElementType); Assert.Empty(info.GenericTypeArguments); } } } [Fact] [SkipOnMono("Nullability attributes trimmed on Mono")] public void TestDeeplyNestedGenericInheritance() { var copyToMethodInfo = nullabilityContext.Create( typeof(ListOfTupleOfDictionaryOfStringNullableBoolIntNullableObject).GetMethod("CopyTo", new[] { typeof((Dictionary<string, bool?>, int, object?)[]) })! .GetParameters()[0]); Validate(copyToMethodInfo, typeof((Dictionary<string, bool?>, int, object?)[]), NullabilityState.NotNull); Assert.NotNull(copyToMethodInfo.ElementType); var tupleInfo = copyToMethodInfo.ElementType!; Validate(tupleInfo, typeof((Dictionary<string, bool?>, int, object?)), NullabilityState.NotNull); var dictionaryInfo = tupleInfo.GenericTypeArguments[0]; Validate(dictionaryInfo, typeof(Dictionary<string, bool?>), NullabilityState.NotNull); var stringInfo = dictionaryInfo.GenericTypeArguments[0]; Validate(stringInfo, typeof(string), NullabilityState.NotNull); var nullableBoolInfo = dictionaryInfo.GenericTypeArguments[1]; Validate(nullableBoolInfo, typeof(bool?), NullabilityState.Nullable); var intInfo = tupleInfo.GenericTypeArguments[1]; Validate(intInfo, typeof(int), NullabilityState.NotNull); var objectInfo = tupleInfo.GenericTypeArguments[2]; Validate(objectInfo, typeof(object), NullabilityState.Nullable); void Validate(NullabilityInfo info, Type type, NullabilityState state) { Assert.Equal(type, info.Type); Assert.Equal(state, info.ReadState); Assert.Equal(state, info.WriteState); Assert.Equal(type.IsGenericType && type.GetGenericTypeDefinition() != typeof(Nullable<>) ? type.GetGenericArguments().Length : 0, info.GenericTypeArguments.Length); Assert.Equal(type.IsArray, info.ElementType is not null); } } [Fact] [SkipOnMono("Nullability attributes trimmed on Mono")] public void TestNestedGenericInheritanceWithMultipleParameters() { var item3Info = nullabilityContext.Create(typeof(DerivesFromTupleOfNestedGenerics).GetProperty("Item3")!); Assert.Equal(typeof(IDisposable[]), item3Info.Type); Assert.Equal(NullabilityState.Nullable, item3Info.ReadState); Assert.Equal(NullabilityState.Unknown, item3Info.WriteState); // read-only property Assert.Equal(NullabilityState.NotNull, item3Info.ElementType!.ReadState); Assert.Equal(NullabilityState.NotNull, item3Info.ElementType.WriteState); } } #pragma warning disable CS0649, CS0067, CS0414 public class TypeWithNullableContext { #nullable disable [AllowNull] public string PropertyDisabledAllowNull { get; set; } [MaybeNull] public string PropertyDisabledMaybeNull { get; set; } public string PropertyDisabled { get; set; } public ref string RefReturnUnknown(ref string id) { return ref id; } #nullable enable [AllowNull] public string PropertyEnabledAllowNull { get; set; } [NotNull] public string? PropertyEnabledNotNull { get; set; } = null!; [DisallowNull] public string? PropertyEnabledDisallowNull { get; set; } = null!; [MaybeNull] public string PropertyEnabledMaybeNull { get; set; } public string? PropertyEnabledNullable { get; set; } public string PropertyEnabledNonNullable { get; set; } = null!; bool NotNullWhenParameter([DisallowNull] string? disallowNull, [NotNullWhen(true)] ref string? notNullWhen, Type? nullableType) { return false; } public bool MaybeNullParameters([MaybeNull] string maybeNull, [MaybeNullWhen(false)] out string maybeNullWhen, Type? nullableType) { maybeNullWhen = null; return false; } public string? AllowNullParameter([AllowNull] string allowNull, [NotNullIfNotNull("allowNull")] string? notNullIfNotNull) { return null; } [return: NotNullIfNotNull("nullable")] public string? NullableNotNullIfNotNullReturn(string? nullable, [NotNull] ref string? readNotNull) { readNotNull = string.Empty; return null!; } public ref string? RefReturnNullable([AllowNull] ref string id) { return ref id!; } [return: MaybeNull] public ref string RefReturnMaybeNull([DisallowNull] ref string? id) { return ref id; } [return: NotNull] public ref string? RefReturnNotNull([NotNull] ref string? id) { id = string.Empty; return ref id!; } public ref string RefReturnNotNullable([MaybeNull] ref string id) { return ref id; } public bool TryGetOutParameters(string id, [NotNullWhen(true)] out string? value, [MaybeNullWhen(false)] out string value2) { value = null; value2 = null; return false; } public IEnumerable<Tuple<(string name, object? value), object>?> MethodReturnsEnumerableNonTupleNonNonNullValueTupleNonNullNon() => null!; } public class TypeWithNoContext { #nullable disable [AllowNull] public string PropertyDisabledAllowNull { get; set; } [MaybeNull] public string PropertyDisabledMaybeNull { get; set; } public string PropertyDisabled { get; set; } #nullable enable [AllowNull] public string PropertyEnabledAllowNull { get; set; } [NotNull] public string? PropertyEnabledNotNull { get; set; } = null!; [DisallowNull] public string? PropertyEnabledDisallowNull { get; set; } = null!; [MaybeNull] public string PropertyEnabledMaybeNull { get; set; } public string? PropertyEnabledNullable { get; set; } public string PropertyEnabledNonNullable { get; set; } = null!; #nullable disable } public class TypeWithNotNullContext { public string PropertyUnknown { get; set; } short PropertyValueTypeUnknown { get; set; } public string[] PropertyArrayUnknown { get; set; } private string[][] PropertyJaggedArrayUnknown { get; set; } protected Tuple<string, string, string> PropertyTupleUnknown { get; set; } protected internal IDictionary<Type, string[]> PropertyDictionaryUnknown { get; set; } public (int, string) UnknownValueTuple; internal TypeWithNotNullContext FieldUnknown; public int FieldValueTypeUnknown; public event EventHandler EventUnknown; public string[] MethodReturnsUnknown() => null!; public void MethodParametersUnknown(string s, IDictionary<Type, string[]> dict) { } #nullable enable public TypeWithNotNullContext? PropertyNullable { get; set; } public TypeWithNotNullContext? PropertyNullableReadOnly { get; } private NullabilityInfoContextTests PropertyNonNullable { get; set; } = null!; internal float PropertyValueType { get; set; } protected long? PropertyValueTypeNullable { get; set; } [DisallowNull] public int? PropertyValueTypeDisallowNull { get; set; } [NotNull] protected int? PropertyValueTypeNotNull { get; set; } [MaybeNull] public byte PropertyValueTypeMaybeNull { get; set; } [AllowNull] public byte PropertyValueTypeAllowNull { get; set; } [DisallowNull] public string? PropertyDisallowNull { get; set; } [AllowNull] public string PropertyAllowNull { get; set; } [NotNull] public string? PropertyNotNull { get; set; } [MaybeNull] public string PropertyMaybeNull { get; set; } // only DisallowNull matters [AllowNull, DisallowNull] public string PropertyAllowNull2 { get; set; } // only AllowNull matters [AllowNull, DisallowNull] public string? PropertyDisallowNull2 { get; set; } // only NotNull matters [NotNull, MaybeNull] public string? PropertyNotNull2 { get; set; } // only NotNull matters [NotNull, MaybeNull] public string PropertyMaybeNull2 { get; set; } [DisallowNull] public string? this[int i] { get => null; set { } } private protected string?[]?[]? PropertyJaggedArrayNullNullNull { get; set; } public static string?[]?[] PropertyJaggedArrayNullNullNon { get; set; } = null!; public string?[][]? PropertyJaggedArrayNullNonNull { get; set; } public static string[]?[]? PropertyJaggedArrayNonNullNull { get; set; } public string?[][] PropertyJaggedArrayNullNonNon { get; set; } = null!; private static string[][]? PropertyJaggedArrayNonNonNull { get; set; } public string?[]? PropertyArrayNullNull { get; set; } static string?[] PropertyArrayNullNon { get; set; } = null!; public string[]? PropertyArrayNonNull { get; } = null; public string[] PropertyArrayNonNon { get; set; } = null!; public Tuple<string?, string?, string?>? PropertyTupleNullNullNullNull { get; set; } public Tuple<string, string?, string> PropertyTupleNonNullNonNon { get; set; } = null!; internal Tuple<string?, string, string?>? PropertyTupleNullNonNullNull { get; set; } public Tuple<string, string?, string>? PropertyTupleNonNullNonNull { get; set; } protected Tuple<string, string, string> PropertyTupleNonNonNonNon { get; set; } = null!; public IDictionary<Type?, string?[]?> PropertyDictionaryNullNullNullNon { get; set; } = null!; public IDictionary<Type, string?[]>? PropertyDictionaryNonNullNonNull { get; set; } IDictionary<Type?, string[]>? PropertyDictionaryNullNonNonNull { get; set; } public IDictionary<Type, string?[]> PropertyDictionaryNonNullNonNon { get; set; } = null!; private IDictionary<Type, string[]>? PropertyDictionaryNonNonNonNull { get; set; } public IDictionary<Type, string[]> PropertyDictionaryNonNonNonNon { get; set; } = null!; public (string?, object) Null_Non_Non_ValueTuple; public (string?, object)? Null_Non_Null_ValueTuple; public (int, int?)? Non_Null_Null_ValueTuple; public (int, string) Non_Non_Non_ValueTuple; public (int, string?) Non_Null_Non_ValueTuple; private const string? FieldNullable = null; protected static NullabilityInfoContextTests FieldNonNullable = null!; public static double FieldValueTypeNotNull; public readonly int? FieldValueTypeNullable; [DisallowNull] public string? FieldDisallowNull; [AllowNull] public string FieldAllowNull; [NotNull] string? FieldNotNull = null; [MaybeNull] public string FieldMaybeNull; [AllowNull, DisallowNull] public string FieldAllowNull2; [AllowNull, DisallowNull] public string? FieldDisallowNull2; [NotNull, MaybeNull] internal string? FieldNotNull2; [NotNull, MaybeNull] public string FieldMaybeNull2; public event EventHandler? EventNullable; public event EventHandler EventNotNull = null!; public string?[] MethodReturnsNullNon() => null!; public string?[]? MethodReturnsNullNull() => null; public string[]? MethodReturnsNonNull() => null; [return: NotNull, MaybeNull] public string[]? MethodReturnsNonNotNull() => null!; // only NotNull is applicable [return: MaybeNull] public string[] MethodReturnsNonMaybeNull() => null; public string[] MethodReturnsNonNon() => null!; public Tuple<string?, string>? MethodReturnsTupleNullNonNull() => null; public Tuple<string?, int> MethodReturnsTupleNullNonNot() => null!; public (int?, string)? MethodReturnsValueTupleNullNonNull() => null; public (string?, string) MethodReturnsValueTupleNullNonNon() => (null, string.Empty); public IEnumerable<Tuple<(string name, object? value), int>?> MethodReturnsEnumerableNonTupleNonNonNullValueTupleNonNullNon() => null!; public IEnumerable<Tuple<(string? name, object value)?, int>?>? MethodReturnsEnumerableNullTupleNullNonNullValueTupleNullNonNull() => null!; public IEnumerable<Tuple<Tuple<string, object?>, int>?> MethodReturnsEnumerableNonTupleNonNonNullTupleNonNullNon() => null!; public IEnumerable<GenericStruct<Tuple<string, object?>?, int>?>? MethodReturnsEnumerableNullStructNullNonNullTupleNonNullNull() => null; public IEnumerable<Tuple<GenericStruct<string, object?>?, int>?>? MethodReturnsEnumerableNullTupleNullNonNullStructNonNullNull() => null; public IEnumerable<(GenericStruct<string, object?> str, int? count)> MethodReturnsEnumerableNonValueTupleNonNullNonStructNonNullNon() => null!; public Tuple<Tuple<string?, string?>, string?> MethodReturnsNonTupleNonTupleNullStringNullStringNullString() => null!; public Tuple<Tuple<string?, string?>, string> MethodReturnsNonTupleNonTupleNullStringNullStringNonString() => null!; public void MethodNullNonNullNonNon(string? s, IDictionary<Type, string?[]> dict) { } public void MethodNonNullNonNullNotNull(string s, [NotNull] IDictionary<Type, string[]?>? dict) { dict = new Dictionary<Type, string[]?>(); } public void MethodNullNonNullNullNon(string? s, IDictionary<Type, string?[]?> dict) { } public void MethodAllowNullNonNonNonNull([AllowNull] string s, IDictionary<Type, string[]>? dict) { } } public struct GenericStruct<T, Y> { } internal class GenericTest<T> { #nullable disable public T PropertyUnknown { get; set; } protected T[] PropertyArrayUnknown { get; set; } public Tuple<T, string, TypeWithNotNullContext> PropertyTupleUnknown { get; set; } private IDictionary<Type, T[]> PropertyDictionaryUnknown { get; set; } public T FieldUnknown; public T MethodReturnsUnknown() => default!; public void MethodParametersUnknown(T s, IDictionary<Type, T> dict) { } #nullable enable public T PropertyNonNullable { get; set; } = default!; public T? PropertyNullable { get; set; } [DisallowNull] public T PropertyDisallowNull { get; set; } = default!; [NotNull] public T PropertyNotNull { get; set; } = default!; [MaybeNull] public T PropertyMaybeNull { get; set; } [AllowNull] public T PropertyAllowNull { get; set; } internal T?[]? PropertyArrayNullNull { get; set; } public T?[] PropertyArrayNullNon { get; set; } = null!; T[]? PropertyArrayNonNull { get; set; } public T[] PropertyArrayNonNon { get; set; } = null!; public Tuple<T?, string?, string?>? PropertyTupleNullNullNullNull { get; set; } public Tuple<T, T?, string> PropertyTupleNonNullNonNon { get; set; } = null!; Tuple<string?, T, T?>? PropertyTupleNullNonNullNull { get; set; } public Tuple<T, int?, string>? PropertyTupleNonNullNonNull { get; set; } public Tuple<int, string, T> PropertyTupleNonNonNonNon { get; set; } = null!; private IDictionary<T?, string?[]?> PropertyDictionaryNullNullNullNon { get; set; } = null!; static IDictionary<Type, T?[]>? PropertyDictionaryNonNullNonNull { get; set; } public static IDictionary<T?, T[]>? PropertyDictionaryNullNonNonNull { get; set; } public IDictionary<Type, T?[]> PropertyDictionaryNonNullNonNon { get; set; } = null!; protected IDictionary<T, T[]>? PropertyDictionaryNonNonNonNull { get; set; } public IDictionary<T, int[]> PropertyDictionaryNonNonNonNon { get; set; } = null!; static T? FieldNullable = default; public T FieldNonNullable = default!; [DisallowNull] public T? FieldDisallowNull; [AllowNull] protected T FieldAllowNull; [NotNull] public T? FieldNotNull = default; [MaybeNull] protected internal T FieldMaybeNull = default!; public List<T> FieldListOfT = default!; public Dictionary<string, T> FieldDictionaryStringToT = default!; public T MethodReturnsGeneric() => default!; public T? MethodReturnsNullGeneric() => default; [return: NotNull] public T MethodReturnsGenericNotNull() => default!; [return: MaybeNull] public T MethodReturnsGenericMaybeNull() => default; public List<T?> MethodNonNullListNullGeneric() => null!; public List<T>? MethodNullListNonNullGeneric() => null; public void MethodArgsNullGenericNullDictValueGeneric(T? s, IDictionary<Type, T>? dict) { } public void MethodArgsGenericDictValueNullGeneric(T s, IDictionary<string, T?> dict) { } } internal class GenericTestConstrainedNotNull<T> where T : notnull { #nullable disable public T FieldUnknown; public T PropertyUnknown { get; set; } #nullable enable public T FieldNullableEnabled = default!; public T? FieldNullable; public T PropertyNullableEnabled { get; set; } = default!; public T? PropertyNullable { get; set; } = default!; } internal class GenericTestConstrainedStruct<T> where T : struct { #nullable disable public T FieldUnknown; public T PropertyUnknown { get; set; } #nullable enable public T FieldNullableEnabled; public T? FieldNullable; public T PropertyNullableEnabled { get; set; } public T? PropertyNullable { get; set; } } public class ListOfUnconstrained<T> : List<T> { } public class ListUnconstrainedOfNullable<T> : ListOfUnconstrained<T> where T : class? { } public class ListUnconstrainedOfNullableOfObject<T> : ListUnconstrainedOfNullable<object> { } public class ListOfArrayOfNullableString : List<string?[]> { } public class ListOfNotNull<T> : List<T> where T : notnull { } public class ListOfListOfObject<T> : List<List<object>> { } public class ListMultiGenericOfNotNull<T, U, V> : List<U> where T : class? where U : class where V : class? { } public class ListOfTupleOfDictionaryOfStringNullableBoolIntNullableObject : List<(Dictionary<string, bool?>, int, object?)> { } public class DerivesFromTupleOfNestedGenerics : Tuple<List<string[]>, Dictionary<object[], List<object>>, IDisposable[]?> { public DerivesFromTupleOfNestedGenerics(List<string[]> item1, Dictionary<object[], List<object>> item2, IDisposable[]? item3) : base(item1, item2, item3) { } } }
-1
dotnet/runtime
66,474
Update repo CMake configuration to target /W4 by default
Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
AaronRobinsonMSFT
2022-03-10T20:20:31Z
2022-03-11T04:59:21Z
ba5207b0f4054fe8963fc3e87c2bd32907516961
5ce2b9f860f7a84c3059650bb67817d59d8f4953
Update repo CMake configuration to target /W4 by default. Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
./src/tests/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b39417/b39417.ilproj
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).il" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).il" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,474
Update repo CMake configuration to target /W4 by default
Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
AaronRobinsonMSFT
2022-03-10T20:20:31Z
2022-03-11T04:59:21Z
ba5207b0f4054fe8963fc3e87c2bd32907516961
5ce2b9f860f7a84c3059650bb67817d59d8f4953
Update repo CMake configuration to target /W4 by default. Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
./src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaIdEntityConstraint.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Xml.Schema { using System.Collections; using System.ComponentModel; using System.Xml.Serialization; public class XmlSchemaIdentityConstraint : XmlSchemaAnnotated { private string? _name; private XmlSchemaXPath? _selector; private readonly XmlSchemaObjectCollection _fields = new XmlSchemaObjectCollection(); private XmlQualifiedName _qualifiedName = XmlQualifiedName.Empty; private CompiledIdentityConstraint? _compiledConstraint; [XmlAttribute("name")] public string? Name { get { return _name; } set { _name = value; } } [XmlElement("selector", typeof(XmlSchemaXPath))] public XmlSchemaXPath? Selector { get { return _selector; } set { _selector = value; } } [XmlElement("field", typeof(XmlSchemaXPath))] public XmlSchemaObjectCollection Fields { get { return _fields; } } [XmlIgnore] public XmlQualifiedName QualifiedName { get { return _qualifiedName; } } internal void SetQualifiedName(XmlQualifiedName value) { _qualifiedName = value; } [XmlIgnore] internal CompiledIdentityConstraint? CompiledConstraint { get { return _compiledConstraint; } set { _compiledConstraint = value; } } [XmlIgnore] internal override string? NameAttribute { get { return Name; } set { Name = value; } } } public class XmlSchemaXPath : XmlSchemaAnnotated { private string? _xpath; [XmlAttribute("xpath"), DefaultValue("")] public string? XPath { get { return _xpath; } set { _xpath = value; } } } public class XmlSchemaUnique : XmlSchemaIdentityConstraint { } public class XmlSchemaKey : XmlSchemaIdentityConstraint { } public class XmlSchemaKeyref : XmlSchemaIdentityConstraint { private XmlQualifiedName _refer = XmlQualifiedName.Empty; [XmlAttribute("refer")] public XmlQualifiedName Refer { get { return _refer; } set { _refer = (value == null ? XmlQualifiedName.Empty : value); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Xml.Schema { using System.Collections; using System.ComponentModel; using System.Xml.Serialization; public class XmlSchemaIdentityConstraint : XmlSchemaAnnotated { private string? _name; private XmlSchemaXPath? _selector; private readonly XmlSchemaObjectCollection _fields = new XmlSchemaObjectCollection(); private XmlQualifiedName _qualifiedName = XmlQualifiedName.Empty; private CompiledIdentityConstraint? _compiledConstraint; [XmlAttribute("name")] public string? Name { get { return _name; } set { _name = value; } } [XmlElement("selector", typeof(XmlSchemaXPath))] public XmlSchemaXPath? Selector { get { return _selector; } set { _selector = value; } } [XmlElement("field", typeof(XmlSchemaXPath))] public XmlSchemaObjectCollection Fields { get { return _fields; } } [XmlIgnore] public XmlQualifiedName QualifiedName { get { return _qualifiedName; } } internal void SetQualifiedName(XmlQualifiedName value) { _qualifiedName = value; } [XmlIgnore] internal CompiledIdentityConstraint? CompiledConstraint { get { return _compiledConstraint; } set { _compiledConstraint = value; } } [XmlIgnore] internal override string? NameAttribute { get { return Name; } set { Name = value; } } } public class XmlSchemaXPath : XmlSchemaAnnotated { private string? _xpath; [XmlAttribute("xpath"), DefaultValue("")] public string? XPath { get { return _xpath; } set { _xpath = value; } } } public class XmlSchemaUnique : XmlSchemaIdentityConstraint { } public class XmlSchemaKey : XmlSchemaIdentityConstraint { } public class XmlSchemaKeyref : XmlSchemaIdentityConstraint { private XmlQualifiedName _refer = XmlQualifiedName.Empty; [XmlAttribute("refer")] public XmlQualifiedName Refer { get { return _refer; } set { _refer = (value == null ? XmlQualifiedName.Empty : value); } } } }
-1
dotnet/runtime
66,474
Update repo CMake configuration to target /W4 by default
Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
AaronRobinsonMSFT
2022-03-10T20:20:31Z
2022-03-11T04:59:21Z
ba5207b0f4054fe8963fc3e87c2bd32907516961
5ce2b9f860f7a84c3059650bb67817d59d8f4953
Update repo CMake configuration to target /W4 by default. Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
./src/libraries/Common/src/Interop/Windows/Advapi32/Interop.RegFlushKey.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #if REGISTRY_ASSEMBLY using Microsoft.Win32.SafeHandles; #else using Internal.Win32.SafeHandles; #endif using System.Runtime.InteropServices; internal static partial class Interop { internal static partial class Advapi32 { [LibraryImport(Libraries.Advapi32)] internal static partial int RegFlushKey(SafeRegistryHandle hKey); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #if REGISTRY_ASSEMBLY using Microsoft.Win32.SafeHandles; #else using Internal.Win32.SafeHandles; #endif using System.Runtime.InteropServices; internal static partial class Interop { internal static partial class Advapi32 { [LibraryImport(Libraries.Advapi32)] internal static partial int RegFlushKey(SafeRegistryHandle hKey); } }
-1
dotnet/runtime
66,474
Update repo CMake configuration to target /W4 by default
Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
AaronRobinsonMSFT
2022-03-10T20:20:31Z
2022-03-11T04:59:21Z
ba5207b0f4054fe8963fc3e87c2bd32907516961
5ce2b9f860f7a84c3059650bb67817d59d8f4953
Update repo CMake configuration to target /W4 by default. Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
./src/libraries/System.Data.Common/src/System/Data/CommandBehavior.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Data { [Flags] public enum CommandBehavior { Default = 0, // with data, multiple results, may affect database SingleResult = 1, // with data, force single result, may affect database SchemaOnly = 2, // column info, no data, no effect on database KeyInfo = 4, // column info + primary key information (if available) SingleRow = 8, // data, hint single row and single result, may affect database - doesn't apply to child(chapter) results SequentialAccess = 0x10, CloseConnection = 0x20, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Data { [Flags] public enum CommandBehavior { Default = 0, // with data, multiple results, may affect database SingleResult = 1, // with data, force single result, may affect database SchemaOnly = 2, // column info, no data, no effect on database KeyInfo = 4, // column info + primary key information (if available) SingleRow = 8, // data, hint single row and single result, may affect database - doesn't apply to child(chapter) results SequentialAccess = 0x10, CloseConnection = 0x20, } }
-1
dotnet/runtime
66,474
Update repo CMake configuration to target /W4 by default
Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
AaronRobinsonMSFT
2022-03-10T20:20:31Z
2022-03-11T04:59:21Z
ba5207b0f4054fe8963fc3e87c2bd32907516961
5ce2b9f860f7a84c3059650bb67817d59d8f4953
Update repo CMake configuration to target /W4 by default. Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
./src/coreclr/pal/src/libunwind/src/ppc/siglongjmp.S
/* libunwind - a platform-independent unwind library This file is part of libunwind. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ .globl _UI_siglongjmp_cont _UI_siglongjmp_cont: #ifdef __linux__ /* We do not need executable stack. */ .section .note.GNU-stack,"",@progbits #endif
/* libunwind - a platform-independent unwind library This file is part of libunwind. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ .globl _UI_siglongjmp_cont _UI_siglongjmp_cont: #ifdef __linux__ /* We do not need executable stack. */ .section .note.GNU-stack,"",@progbits #endif
-1
dotnet/runtime
66,474
Update repo CMake configuration to target /W4 by default
Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
AaronRobinsonMSFT
2022-03-10T20:20:31Z
2022-03-11T04:59:21Z
ba5207b0f4054fe8963fc3e87c2bd32907516961
5ce2b9f860f7a84c3059650bb67817d59d8f4953
Update repo CMake configuration to target /W4 by default. Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
./src/tests/JIT/jit64/gc/misc/struct1_4.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="struct1_4.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="struct1_4.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,474
Update repo CMake configuration to target /W4 by default
Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
AaronRobinsonMSFT
2022-03-10T20:20:31Z
2022-03-11T04:59:21Z
ba5207b0f4054fe8963fc3e87c2bd32907516961
5ce2b9f860f7a84c3059650bb67817d59d8f4953
Update repo CMake configuration to target /W4 by default. Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
./src/libraries/System.Drawing.Primitives/ref/System.Drawing.Primitives.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // ------------------------------------------------------------------------------ // Changes to this file must follow the https://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.Drawing { [System.ComponentModel.EditorAttribute("System.Drawing.Design.ColorEditor, System.Drawing.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] [System.ComponentModel.TypeConverterAttribute("System.Drawing.ColorConverter, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] public readonly partial struct Color : System.IEquatable<System.Drawing.Color> { private readonly object _dummy; private readonly int _dummyPrimitive; public static readonly System.Drawing.Color Empty; public byte A { get { throw null; } } public static System.Drawing.Color AliceBlue { get { throw null; } } public static System.Drawing.Color AntiqueWhite { get { throw null; } } public static System.Drawing.Color Aqua { get { throw null; } } public static System.Drawing.Color Aquamarine { get { throw null; } } public static System.Drawing.Color Azure { get { throw null; } } public byte B { get { throw null; } } public static System.Drawing.Color Beige { get { throw null; } } public static System.Drawing.Color Bisque { get { throw null; } } public static System.Drawing.Color Black { get { throw null; } } public static System.Drawing.Color BlanchedAlmond { get { throw null; } } public static System.Drawing.Color Blue { get { throw null; } } public static System.Drawing.Color BlueViolet { get { throw null; } } public static System.Drawing.Color Brown { get { throw null; } } public static System.Drawing.Color BurlyWood { get { throw null; } } public static System.Drawing.Color CadetBlue { get { throw null; } } public static System.Drawing.Color Chartreuse { get { throw null; } } public static System.Drawing.Color Chocolate { get { throw null; } } public static System.Drawing.Color Coral { get { throw null; } } public static System.Drawing.Color CornflowerBlue { get { throw null; } } public static System.Drawing.Color Cornsilk { get { throw null; } } public static System.Drawing.Color Crimson { get { throw null; } } public static System.Drawing.Color Cyan { get { throw null; } } public static System.Drawing.Color DarkBlue { get { throw null; } } public static System.Drawing.Color DarkCyan { get { throw null; } } public static System.Drawing.Color DarkGoldenrod { get { throw null; } } public static System.Drawing.Color DarkGray { get { throw null; } } public static System.Drawing.Color DarkGreen { get { throw null; } } public static System.Drawing.Color DarkKhaki { get { throw null; } } public static System.Drawing.Color DarkMagenta { get { throw null; } } public static System.Drawing.Color DarkOliveGreen { get { throw null; } } public static System.Drawing.Color DarkOrange { get { throw null; } } public static System.Drawing.Color DarkOrchid { get { throw null; } } public static System.Drawing.Color DarkRed { get { throw null; } } public static System.Drawing.Color DarkSalmon { get { throw null; } } public static System.Drawing.Color DarkSeaGreen { get { throw null; } } public static System.Drawing.Color DarkSlateBlue { get { throw null; } } public static System.Drawing.Color DarkSlateGray { get { throw null; } } public static System.Drawing.Color DarkTurquoise { get { throw null; } } public static System.Drawing.Color DarkViolet { get { throw null; } } public static System.Drawing.Color DeepPink { get { throw null; } } public static System.Drawing.Color DeepSkyBlue { get { throw null; } } public static System.Drawing.Color DimGray { get { throw null; } } public static System.Drawing.Color DodgerBlue { get { throw null; } } public static System.Drawing.Color Firebrick { get { throw null; } } public static System.Drawing.Color FloralWhite { get { throw null; } } public static System.Drawing.Color ForestGreen { get { throw null; } } public static System.Drawing.Color Fuchsia { get { throw null; } } public byte G { get { throw null; } } public static System.Drawing.Color Gainsboro { get { throw null; } } public static System.Drawing.Color GhostWhite { get { throw null; } } public static System.Drawing.Color Gold { get { throw null; } } public static System.Drawing.Color Goldenrod { get { throw null; } } public static System.Drawing.Color Gray { get { throw null; } } public static System.Drawing.Color Green { get { throw null; } } public static System.Drawing.Color GreenYellow { get { throw null; } } public static System.Drawing.Color Honeydew { get { throw null; } } public static System.Drawing.Color HotPink { get { throw null; } } public static System.Drawing.Color IndianRed { get { throw null; } } public static System.Drawing.Color Indigo { get { throw null; } } public bool IsEmpty { get { throw null; } } public bool IsKnownColor { get { throw null; } } public bool IsNamedColor { get { throw null; } } public bool IsSystemColor { get { throw null; } } public static System.Drawing.Color Ivory { get { throw null; } } public static System.Drawing.Color Khaki { get { throw null; } } public static System.Drawing.Color Lavender { get { throw null; } } public static System.Drawing.Color LavenderBlush { get { throw null; } } public static System.Drawing.Color LawnGreen { get { throw null; } } public static System.Drawing.Color LemonChiffon { get { throw null; } } public static System.Drawing.Color LightBlue { get { throw null; } } public static System.Drawing.Color LightCoral { get { throw null; } } public static System.Drawing.Color LightCyan { get { throw null; } } public static System.Drawing.Color LightGoldenrodYellow { get { throw null; } } public static System.Drawing.Color LightGray { get { throw null; } } public static System.Drawing.Color LightGreen { get { throw null; } } public static System.Drawing.Color LightPink { get { throw null; } } public static System.Drawing.Color LightSalmon { get { throw null; } } public static System.Drawing.Color LightSeaGreen { get { throw null; } } public static System.Drawing.Color LightSkyBlue { get { throw null; } } public static System.Drawing.Color LightSlateGray { get { throw null; } } public static System.Drawing.Color LightSteelBlue { get { throw null; } } public static System.Drawing.Color LightYellow { get { throw null; } } public static System.Drawing.Color Lime { get { throw null; } } public static System.Drawing.Color LimeGreen { get { throw null; } } public static System.Drawing.Color Linen { get { throw null; } } public static System.Drawing.Color Magenta { get { throw null; } } public static System.Drawing.Color Maroon { get { throw null; } } public static System.Drawing.Color MediumAquamarine { get { throw null; } } public static System.Drawing.Color MediumBlue { get { throw null; } } public static System.Drawing.Color MediumOrchid { get { throw null; } } public static System.Drawing.Color MediumPurple { get { throw null; } } public static System.Drawing.Color MediumSeaGreen { get { throw null; } } public static System.Drawing.Color MediumSlateBlue { get { throw null; } } public static System.Drawing.Color MediumSpringGreen { get { throw null; } } public static System.Drawing.Color MediumTurquoise { get { throw null; } } public static System.Drawing.Color MediumVioletRed { get { throw null; } } public static System.Drawing.Color MidnightBlue { get { throw null; } } public static System.Drawing.Color MintCream { get { throw null; } } public static System.Drawing.Color MistyRose { get { throw null; } } public static System.Drawing.Color Moccasin { get { throw null; } } public string Name { get { throw null; } } public static System.Drawing.Color NavajoWhite { get { throw null; } } public static System.Drawing.Color Navy { get { throw null; } } public static System.Drawing.Color OldLace { get { throw null; } } public static System.Drawing.Color Olive { get { throw null; } } public static System.Drawing.Color OliveDrab { get { throw null; } } public static System.Drawing.Color Orange { get { throw null; } } public static System.Drawing.Color OrangeRed { get { throw null; } } public static System.Drawing.Color Orchid { get { throw null; } } public static System.Drawing.Color PaleGoldenrod { get { throw null; } } public static System.Drawing.Color PaleGreen { get { throw null; } } public static System.Drawing.Color PaleTurquoise { get { throw null; } } public static System.Drawing.Color PaleVioletRed { get { throw null; } } public static System.Drawing.Color PapayaWhip { get { throw null; } } public static System.Drawing.Color PeachPuff { get { throw null; } } public static System.Drawing.Color Peru { get { throw null; } } public static System.Drawing.Color Pink { get { throw null; } } public static System.Drawing.Color Plum { get { throw null; } } public static System.Drawing.Color PowderBlue { get { throw null; } } public static System.Drawing.Color Purple { get { throw null; } } public byte R { get { throw null; } } public static System.Drawing.Color RebeccaPurple { get { throw null; } } public static System.Drawing.Color Red { get { throw null; } } public static System.Drawing.Color RosyBrown { get { throw null; } } public static System.Drawing.Color RoyalBlue { get { throw null; } } public static System.Drawing.Color SaddleBrown { get { throw null; } } public static System.Drawing.Color Salmon { get { throw null; } } public static System.Drawing.Color SandyBrown { get { throw null; } } public static System.Drawing.Color SeaGreen { get { throw null; } } public static System.Drawing.Color SeaShell { get { throw null; } } public static System.Drawing.Color Sienna { get { throw null; } } public static System.Drawing.Color Silver { get { throw null; } } public static System.Drawing.Color SkyBlue { get { throw null; } } public static System.Drawing.Color SlateBlue { get { throw null; } } public static System.Drawing.Color SlateGray { get { throw null; } } public static System.Drawing.Color Snow { get { throw null; } } public static System.Drawing.Color SpringGreen { get { throw null; } } public static System.Drawing.Color SteelBlue { get { throw null; } } public static System.Drawing.Color Tan { get { throw null; } } public static System.Drawing.Color Teal { get { throw null; } } public static System.Drawing.Color Thistle { get { throw null; } } public static System.Drawing.Color Tomato { get { throw null; } } public static System.Drawing.Color Transparent { get { throw null; } } public static System.Drawing.Color Turquoise { get { throw null; } } public static System.Drawing.Color Violet { get { throw null; } } public static System.Drawing.Color Wheat { get { throw null; } } public static System.Drawing.Color White { get { throw null; } } public static System.Drawing.Color WhiteSmoke { get { throw null; } } public static System.Drawing.Color Yellow { get { throw null; } } public static System.Drawing.Color YellowGreen { get { throw null; } } public bool Equals(System.Drawing.Color other) { throw null; } public override bool Equals([System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] object? obj) { throw null; } public static System.Drawing.Color FromArgb(int argb) { throw null; } public static System.Drawing.Color FromArgb(int alpha, System.Drawing.Color baseColor) { throw null; } public static System.Drawing.Color FromArgb(int red, int green, int blue) { throw null; } public static System.Drawing.Color FromArgb(int alpha, int red, int green, int blue) { throw null; } public static System.Drawing.Color FromKnownColor(System.Drawing.KnownColor color) { throw null; } public static System.Drawing.Color FromName(string name) { throw null; } public float GetBrightness() { throw null; } public override int GetHashCode() { throw null; } public float GetHue() { throw null; } public float GetSaturation() { throw null; } public static bool operator ==(System.Drawing.Color left, System.Drawing.Color right) { throw null; } public static bool operator !=(System.Drawing.Color left, System.Drawing.Color right) { throw null; } public int ToArgb() { throw null; } public System.Drawing.KnownColor ToKnownColor() { throw null; } public override string ToString() { throw null; } } public static partial class ColorTranslator { public static System.Drawing.Color FromHtml(string htmlColor) { throw null; } public static System.Drawing.Color FromOle(int oleColor) { throw null; } public static System.Drawing.Color FromWin32(int win32Color) { throw null; } public static string ToHtml(System.Drawing.Color c) { throw null; } public static int ToOle(System.Drawing.Color c) { throw null; } public static int ToWin32(System.Drawing.Color c) { throw null; } } public enum KnownColor { ActiveBorder = 1, ActiveCaption = 2, ActiveCaptionText = 3, AppWorkspace = 4, Control = 5, ControlDark = 6, ControlDarkDark = 7, ControlLight = 8, ControlLightLight = 9, ControlText = 10, Desktop = 11, GrayText = 12, Highlight = 13, HighlightText = 14, HotTrack = 15, InactiveBorder = 16, InactiveCaption = 17, InactiveCaptionText = 18, Info = 19, InfoText = 20, Menu = 21, MenuText = 22, ScrollBar = 23, Window = 24, WindowFrame = 25, WindowText = 26, Transparent = 27, AliceBlue = 28, AntiqueWhite = 29, Aqua = 30, Aquamarine = 31, Azure = 32, Beige = 33, Bisque = 34, Black = 35, BlanchedAlmond = 36, Blue = 37, BlueViolet = 38, Brown = 39, BurlyWood = 40, CadetBlue = 41, Chartreuse = 42, Chocolate = 43, Coral = 44, CornflowerBlue = 45, Cornsilk = 46, Crimson = 47, Cyan = 48, DarkBlue = 49, DarkCyan = 50, DarkGoldenrod = 51, DarkGray = 52, DarkGreen = 53, DarkKhaki = 54, DarkMagenta = 55, DarkOliveGreen = 56, DarkOrange = 57, DarkOrchid = 58, DarkRed = 59, DarkSalmon = 60, DarkSeaGreen = 61, DarkSlateBlue = 62, DarkSlateGray = 63, DarkTurquoise = 64, DarkViolet = 65, DeepPink = 66, DeepSkyBlue = 67, DimGray = 68, DodgerBlue = 69, Firebrick = 70, FloralWhite = 71, ForestGreen = 72, Fuchsia = 73, Gainsboro = 74, GhostWhite = 75, Gold = 76, Goldenrod = 77, Gray = 78, Green = 79, GreenYellow = 80, Honeydew = 81, HotPink = 82, IndianRed = 83, Indigo = 84, Ivory = 85, Khaki = 86, Lavender = 87, LavenderBlush = 88, LawnGreen = 89, LemonChiffon = 90, LightBlue = 91, LightCoral = 92, LightCyan = 93, LightGoldenrodYellow = 94, LightGray = 95, LightGreen = 96, LightPink = 97, LightSalmon = 98, LightSeaGreen = 99, LightSkyBlue = 100, LightSlateGray = 101, LightSteelBlue = 102, LightYellow = 103, Lime = 104, LimeGreen = 105, Linen = 106, Magenta = 107, Maroon = 108, MediumAquamarine = 109, MediumBlue = 110, MediumOrchid = 111, MediumPurple = 112, MediumSeaGreen = 113, MediumSlateBlue = 114, MediumSpringGreen = 115, MediumTurquoise = 116, MediumVioletRed = 117, MidnightBlue = 118, MintCream = 119, MistyRose = 120, Moccasin = 121, NavajoWhite = 122, Navy = 123, OldLace = 124, Olive = 125, OliveDrab = 126, Orange = 127, OrangeRed = 128, Orchid = 129, PaleGoldenrod = 130, PaleGreen = 131, PaleTurquoise = 132, PaleVioletRed = 133, PapayaWhip = 134, PeachPuff = 135, Peru = 136, Pink = 137, Plum = 138, PowderBlue = 139, Purple = 140, Red = 141, RosyBrown = 142, RoyalBlue = 143, SaddleBrown = 144, Salmon = 145, SandyBrown = 146, SeaGreen = 147, SeaShell = 148, Sienna = 149, Silver = 150, SkyBlue = 151, SlateBlue = 152, SlateGray = 153, Snow = 154, SpringGreen = 155, SteelBlue = 156, Tan = 157, Teal = 158, Thistle = 159, Tomato = 160, Turquoise = 161, Violet = 162, Wheat = 163, White = 164, WhiteSmoke = 165, Yellow = 166, YellowGreen = 167, ButtonFace = 168, ButtonHighlight = 169, ButtonShadow = 170, GradientActiveCaption = 171, GradientInactiveCaption = 172, MenuBar = 173, MenuHighlight = 174, RebeccaPurple = 175, } [System.ComponentModel.TypeConverterAttribute("System.Drawing.PointConverter, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] public partial struct Point : System.IEquatable<System.Drawing.Point> { private int _dummyPrimitive; public static readonly System.Drawing.Point Empty; public Point(System.Drawing.Size sz) { throw null; } public Point(int dw) { throw null; } public Point(int x, int y) { throw null; } [System.ComponentModel.BrowsableAttribute(false)] public readonly bool IsEmpty { get { throw null; } } public int X { readonly get { throw null; } set { } } public int Y { readonly get { throw null; } set { } } public static System.Drawing.Point Add(System.Drawing.Point pt, System.Drawing.Size sz) { throw null; } public static System.Drawing.Point Ceiling(System.Drawing.PointF value) { throw null; } public readonly bool Equals(System.Drawing.Point other) { throw null; } public override readonly bool Equals([System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] object? obj) { throw null; } public override readonly int GetHashCode() { throw null; } public void Offset(System.Drawing.Point p) { } public void Offset(int dx, int dy) { } public static System.Drawing.Point operator +(System.Drawing.Point pt, System.Drawing.Size sz) { throw null; } public static bool operator ==(System.Drawing.Point left, System.Drawing.Point right) { throw null; } public static explicit operator System.Drawing.Size (System.Drawing.Point p) { throw null; } public static implicit operator System.Drawing.PointF (System.Drawing.Point p) { throw null; } public static bool operator !=(System.Drawing.Point left, System.Drawing.Point right) { throw null; } public static System.Drawing.Point operator -(System.Drawing.Point pt, System.Drawing.Size sz) { throw null; } public static System.Drawing.Point Round(System.Drawing.PointF value) { throw null; } public static System.Drawing.Point Subtract(System.Drawing.Point pt, System.Drawing.Size sz) { throw null; } public override readonly string ToString() { throw null; } public static System.Drawing.Point Truncate(System.Drawing.PointF value) { throw null; } } public partial struct PointF : System.IEquatable<System.Drawing.PointF> { private int _dummyPrimitive; public static readonly System.Drawing.PointF Empty; public PointF(float x, float y) { throw null; } public PointF(System.Numerics.Vector2 vector) { throw null; } [System.ComponentModel.BrowsableAttribute(false)] public readonly bool IsEmpty { get { throw null; } } public float X { readonly get { throw null; } set { } } public float Y { readonly get { throw null; } set { } } public static System.Drawing.PointF Add(System.Drawing.PointF pt, System.Drawing.Size sz) { throw null; } public static System.Drawing.PointF Add(System.Drawing.PointF pt, System.Drawing.SizeF sz) { throw null; } public readonly bool Equals(System.Drawing.PointF other) { throw null; } public override readonly bool Equals([System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] object? obj) { throw null; } public override readonly int GetHashCode() { throw null; } public static explicit operator System.Numerics.Vector2(System.Drawing.PointF point) { throw null; } public static explicit operator System.Drawing.PointF(System.Numerics.Vector2 vector) { throw null; } public static System.Drawing.PointF operator +(System.Drawing.PointF pt, System.Drawing.Size sz) { throw null; } public static System.Drawing.PointF operator +(System.Drawing.PointF pt, System.Drawing.SizeF sz) { throw null; } public static bool operator ==(System.Drawing.PointF left, System.Drawing.PointF right) { throw null; } public static bool operator !=(System.Drawing.PointF left, System.Drawing.PointF right) { throw null; } public static System.Drawing.PointF operator -(System.Drawing.PointF pt, System.Drawing.Size sz) { throw null; } public static System.Drawing.PointF operator -(System.Drawing.PointF pt, System.Drawing.SizeF sz) { throw null; } public static System.Drawing.PointF Subtract(System.Drawing.PointF pt, System.Drawing.Size sz) { throw null; } public static System.Drawing.PointF Subtract(System.Drawing.PointF pt, System.Drawing.SizeF sz) { throw null; } public override readonly string ToString() { throw null; } public System.Numerics.Vector2 ToVector2() { throw null; } } [System.ComponentModel.TypeConverterAttribute("System.Drawing.RectangleConverter, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] public partial struct Rectangle : System.IEquatable<System.Drawing.Rectangle> { private int _dummyPrimitive; public static readonly System.Drawing.Rectangle Empty; public Rectangle(System.Drawing.Point location, System.Drawing.Size size) { throw null; } public Rectangle(int x, int y, int width, int height) { throw null; } [System.ComponentModel.BrowsableAttribute(false)] public readonly int Bottom { get { throw null; } } public int Height { readonly get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] public readonly bool IsEmpty { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] public readonly int Left { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] public System.Drawing.Point Location { readonly get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] public readonly int Right { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] public System.Drawing.Size Size { readonly get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] public readonly int Top { get { throw null; } } public int Width { readonly get { throw null; } set { } } public int X { readonly get { throw null; } set { } } public int Y { readonly get { throw null; } set { } } public static System.Drawing.Rectangle Ceiling(System.Drawing.RectangleF value) { throw null; } public readonly bool Contains(System.Drawing.Point pt) { throw null; } public readonly bool Contains(System.Drawing.Rectangle rect) { throw null; } public readonly bool Contains(int x, int y) { throw null; } public readonly bool Equals(System.Drawing.Rectangle other) { throw null; } public override readonly bool Equals([System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] object? obj) { throw null; } public static System.Drawing.Rectangle FromLTRB(int left, int top, int right, int bottom) { throw null; } public override readonly int GetHashCode() { throw null; } public static System.Drawing.Rectangle Inflate(System.Drawing.Rectangle rect, int x, int y) { throw null; } public void Inflate(System.Drawing.Size size) { } public void Inflate(int width, int height) { } public void Intersect(System.Drawing.Rectangle rect) { } public static System.Drawing.Rectangle Intersect(System.Drawing.Rectangle a, System.Drawing.Rectangle b) { throw null; } public readonly bool IntersectsWith(System.Drawing.Rectangle rect) { throw null; } public void Offset(System.Drawing.Point pos) { } public void Offset(int x, int y) { } public static bool operator ==(System.Drawing.Rectangle left, System.Drawing.Rectangle right) { throw null; } public static bool operator !=(System.Drawing.Rectangle left, System.Drawing.Rectangle right) { throw null; } public static System.Drawing.Rectangle Round(System.Drawing.RectangleF value) { throw null; } public override readonly string ToString() { throw null; } public static System.Drawing.Rectangle Truncate(System.Drawing.RectangleF value) { throw null; } public static System.Drawing.Rectangle Union(System.Drawing.Rectangle a, System.Drawing.Rectangle b) { throw null; } } public partial struct RectangleF : System.IEquatable<System.Drawing.RectangleF> { private int _dummyPrimitive; public static readonly System.Drawing.RectangleF Empty; public RectangleF(System.Drawing.PointF location, System.Drawing.SizeF size) { throw null; } public RectangleF(float x, float y, float width, float height) { throw null; } public RectangleF(System.Numerics.Vector4 vector) { throw null; } [System.ComponentModel.BrowsableAttribute(false)] public readonly float Bottom { get { throw null; } } public float Height { readonly get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] public readonly bool IsEmpty { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] public readonly float Left { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] public System.Drawing.PointF Location { readonly get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] public readonly float Right { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] public System.Drawing.SizeF Size { readonly get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] public readonly float Top { get { throw null; } } public float Width { readonly get { throw null; } set { } } public float X { readonly get { throw null; } set { } } public float Y { readonly get { throw null; } set { } } public readonly bool Contains(System.Drawing.PointF pt) { throw null; } public readonly bool Contains(System.Drawing.RectangleF rect) { throw null; } public readonly bool Contains(float x, float y) { throw null; } public readonly bool Equals(System.Drawing.RectangleF other) { throw null; } public override readonly bool Equals([System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] object? obj) { throw null; } public static System.Drawing.RectangleF FromLTRB(float left, float top, float right, float bottom) { throw null; } public override readonly int GetHashCode() { throw null; } public static System.Drawing.RectangleF Inflate(System.Drawing.RectangleF rect, float x, float y) { throw null; } public void Inflate(System.Drawing.SizeF size) { } public void Inflate(float x, float y) { } public void Intersect(System.Drawing.RectangleF rect) { } public static System.Drawing.RectangleF Intersect(System.Drawing.RectangleF a, System.Drawing.RectangleF b) { throw null; } public readonly bool IntersectsWith(System.Drawing.RectangleF rect) { throw null; } public void Offset(System.Drawing.PointF pos) { } public void Offset(float x, float y) { } public static explicit operator System.Numerics.Vector4(System.Drawing.RectangleF rectangle) { throw null; } public static explicit operator System.Drawing.RectangleF(System.Numerics.Vector4 vector) { throw null; } public static bool operator ==(System.Drawing.RectangleF left, System.Drawing.RectangleF right) { throw null; } public static implicit operator System.Drawing.RectangleF (System.Drawing.Rectangle r) { throw null; } public static bool operator !=(System.Drawing.RectangleF left, System.Drawing.RectangleF right) { throw null; } public override readonly string ToString() { throw null; } public System.Numerics.Vector4 ToVector4() { throw null; } public static System.Drawing.RectangleF Union(System.Drawing.RectangleF a, System.Drawing.RectangleF b) { throw null; } } [System.ComponentModel.TypeConverterAttribute("System.Drawing.SizeConverter, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] public partial struct Size : System.IEquatable<System.Drawing.Size> { private int _dummyPrimitive; public static readonly System.Drawing.Size Empty; public Size(System.Drawing.Point pt) { throw null; } public Size(int width, int height) { throw null; } public int Height { readonly get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] public readonly bool IsEmpty { get { throw null; } } public int Width { readonly get { throw null; } set { } } public static System.Drawing.Size Add(System.Drawing.Size sz1, System.Drawing.Size sz2) { throw null; } public static System.Drawing.Size Ceiling(System.Drawing.SizeF value) { throw null; } public readonly bool Equals(System.Drawing.Size other) { throw null; } public override readonly bool Equals([System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] object? obj) { throw null; } public override readonly int GetHashCode() { throw null; } public static System.Drawing.Size operator +(System.Drawing.Size sz1, System.Drawing.Size sz2) { throw null; } public static System.Drawing.Size operator /(System.Drawing.Size left, int right) { throw null; } public static System.Drawing.SizeF operator /(System.Drawing.Size left, float right) { throw null; } public static bool operator ==(System.Drawing.Size sz1, System.Drawing.Size sz2) { throw null; } public static explicit operator System.Drawing.Point (System.Drawing.Size size) { throw null; } public static implicit operator System.Drawing.SizeF (System.Drawing.Size p) { throw null; } public static bool operator !=(System.Drawing.Size sz1, System.Drawing.Size sz2) { throw null; } public static System.Drawing.Size operator *(System.Drawing.Size left, int right) { throw null; } public static System.Drawing.SizeF operator *(System.Drawing.Size left, float right) { throw null; } public static System.Drawing.Size operator *(int left, System.Drawing.Size right) { throw null; } public static System.Drawing.SizeF operator *(float left, System.Drawing.Size right) { throw null; } public static System.Drawing.Size operator -(System.Drawing.Size sz1, System.Drawing.Size sz2) { throw null; } public static System.Drawing.Size Round(System.Drawing.SizeF value) { throw null; } public static System.Drawing.Size Subtract(System.Drawing.Size sz1, System.Drawing.Size sz2) { throw null; } public override readonly string ToString() { throw null; } public static System.Drawing.Size Truncate(System.Drawing.SizeF value) { throw null; } } [System.ComponentModel.TypeConverterAttribute("System.Drawing.SizeFConverter, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] public partial struct SizeF : System.IEquatable<System.Drawing.SizeF> { private int _dummyPrimitive; public static readonly System.Drawing.SizeF Empty; public SizeF(System.Drawing.PointF pt) { throw null; } public SizeF(System.Drawing.SizeF size) { throw null; } public SizeF(float width, float height) { throw null; } public SizeF(System.Numerics.Vector2 vector) { throw null; } public float Height { readonly get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] public readonly bool IsEmpty { get { throw null; } } public float Width { readonly get { throw null; } set { } } public static System.Drawing.SizeF Add(System.Drawing.SizeF sz1, System.Drawing.SizeF sz2) { throw null; } public readonly bool Equals(System.Drawing.SizeF other) { throw null; } public override readonly bool Equals([System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] object? obj) { throw null; } public override readonly int GetHashCode() { throw null; } public static explicit operator System.Numerics.Vector2(System.Drawing.SizeF size) { throw null; } public static explicit operator System.Drawing.SizeF(System.Numerics.Vector2 vector) { throw null; } public static System.Drawing.SizeF operator +(System.Drawing.SizeF sz1, System.Drawing.SizeF sz2) { throw null; } public static System.Drawing.SizeF operator /(System.Drawing.SizeF left, float right) { throw null; } public static bool operator ==(System.Drawing.SizeF sz1, System.Drawing.SizeF sz2) { throw null; } public static explicit operator System.Drawing.PointF (System.Drawing.SizeF size) { throw null; } public static bool operator !=(System.Drawing.SizeF sz1, System.Drawing.SizeF sz2) { throw null; } public static System.Drawing.SizeF operator *(System.Drawing.SizeF left, float right) { throw null; } public static System.Drawing.SizeF operator *(float left, System.Drawing.SizeF right) { throw null; } public static System.Drawing.SizeF operator -(System.Drawing.SizeF sz1, System.Drawing.SizeF sz2) { throw null; } public static System.Drawing.SizeF Subtract(System.Drawing.SizeF sz1, System.Drawing.SizeF sz2) { throw null; } public readonly System.Drawing.PointF ToPointF() { throw null; } public readonly System.Drawing.Size ToSize() { throw null; } public override readonly string ToString() { throw null; } public System.Numerics.Vector2 ToVector2() { throw null; } } public static partial class SystemColors { public static System.Drawing.Color ActiveBorder { get { throw null; } } public static System.Drawing.Color ActiveCaption { get { throw null; } } public static System.Drawing.Color ActiveCaptionText { get { throw null; } } public static System.Drawing.Color AppWorkspace { get { throw null; } } public static System.Drawing.Color ButtonFace { get { throw null; } } public static System.Drawing.Color ButtonHighlight { get { throw null; } } public static System.Drawing.Color ButtonShadow { get { throw null; } } public static System.Drawing.Color Control { get { throw null; } } public static System.Drawing.Color ControlDark { get { throw null; } } public static System.Drawing.Color ControlDarkDark { get { throw null; } } public static System.Drawing.Color ControlLight { get { throw null; } } public static System.Drawing.Color ControlLightLight { get { throw null; } } public static System.Drawing.Color ControlText { get { throw null; } } public static System.Drawing.Color Desktop { get { throw null; } } public static System.Drawing.Color GradientActiveCaption { get { throw null; } } public static System.Drawing.Color GradientInactiveCaption { get { throw null; } } public static System.Drawing.Color GrayText { get { throw null; } } public static System.Drawing.Color Highlight { get { throw null; } } public static System.Drawing.Color HighlightText { get { throw null; } } public static System.Drawing.Color HotTrack { get { throw null; } } public static System.Drawing.Color InactiveBorder { get { throw null; } } public static System.Drawing.Color InactiveCaption { get { throw null; } } public static System.Drawing.Color InactiveCaptionText { get { throw null; } } public static System.Drawing.Color Info { get { throw null; } } public static System.Drawing.Color InfoText { get { throw null; } } public static System.Drawing.Color Menu { get { throw null; } } public static System.Drawing.Color MenuBar { get { throw null; } } public static System.Drawing.Color MenuHighlight { get { throw null; } } public static System.Drawing.Color MenuText { get { throw null; } } public static System.Drawing.Color ScrollBar { get { throw null; } } public static System.Drawing.Color Window { get { throw null; } } public static System.Drawing.Color WindowFrame { get { throw null; } } public static System.Drawing.Color WindowText { get { throw null; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // ------------------------------------------------------------------------------ // Changes to this file must follow the https://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.Drawing { [System.ComponentModel.EditorAttribute("System.Drawing.Design.ColorEditor, System.Drawing.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] [System.ComponentModel.TypeConverterAttribute("System.Drawing.ColorConverter, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] public readonly partial struct Color : System.IEquatable<System.Drawing.Color> { private readonly object _dummy; private readonly int _dummyPrimitive; public static readonly System.Drawing.Color Empty; public byte A { get { throw null; } } public static System.Drawing.Color AliceBlue { get { throw null; } } public static System.Drawing.Color AntiqueWhite { get { throw null; } } public static System.Drawing.Color Aqua { get { throw null; } } public static System.Drawing.Color Aquamarine { get { throw null; } } public static System.Drawing.Color Azure { get { throw null; } } public byte B { get { throw null; } } public static System.Drawing.Color Beige { get { throw null; } } public static System.Drawing.Color Bisque { get { throw null; } } public static System.Drawing.Color Black { get { throw null; } } public static System.Drawing.Color BlanchedAlmond { get { throw null; } } public static System.Drawing.Color Blue { get { throw null; } } public static System.Drawing.Color BlueViolet { get { throw null; } } public static System.Drawing.Color Brown { get { throw null; } } public static System.Drawing.Color BurlyWood { get { throw null; } } public static System.Drawing.Color CadetBlue { get { throw null; } } public static System.Drawing.Color Chartreuse { get { throw null; } } public static System.Drawing.Color Chocolate { get { throw null; } } public static System.Drawing.Color Coral { get { throw null; } } public static System.Drawing.Color CornflowerBlue { get { throw null; } } public static System.Drawing.Color Cornsilk { get { throw null; } } public static System.Drawing.Color Crimson { get { throw null; } } public static System.Drawing.Color Cyan { get { throw null; } } public static System.Drawing.Color DarkBlue { get { throw null; } } public static System.Drawing.Color DarkCyan { get { throw null; } } public static System.Drawing.Color DarkGoldenrod { get { throw null; } } public static System.Drawing.Color DarkGray { get { throw null; } } public static System.Drawing.Color DarkGreen { get { throw null; } } public static System.Drawing.Color DarkKhaki { get { throw null; } } public static System.Drawing.Color DarkMagenta { get { throw null; } } public static System.Drawing.Color DarkOliveGreen { get { throw null; } } public static System.Drawing.Color DarkOrange { get { throw null; } } public static System.Drawing.Color DarkOrchid { get { throw null; } } public static System.Drawing.Color DarkRed { get { throw null; } } public static System.Drawing.Color DarkSalmon { get { throw null; } } public static System.Drawing.Color DarkSeaGreen { get { throw null; } } public static System.Drawing.Color DarkSlateBlue { get { throw null; } } public static System.Drawing.Color DarkSlateGray { get { throw null; } } public static System.Drawing.Color DarkTurquoise { get { throw null; } } public static System.Drawing.Color DarkViolet { get { throw null; } } public static System.Drawing.Color DeepPink { get { throw null; } } public static System.Drawing.Color DeepSkyBlue { get { throw null; } } public static System.Drawing.Color DimGray { get { throw null; } } public static System.Drawing.Color DodgerBlue { get { throw null; } } public static System.Drawing.Color Firebrick { get { throw null; } } public static System.Drawing.Color FloralWhite { get { throw null; } } public static System.Drawing.Color ForestGreen { get { throw null; } } public static System.Drawing.Color Fuchsia { get { throw null; } } public byte G { get { throw null; } } public static System.Drawing.Color Gainsboro { get { throw null; } } public static System.Drawing.Color GhostWhite { get { throw null; } } public static System.Drawing.Color Gold { get { throw null; } } public static System.Drawing.Color Goldenrod { get { throw null; } } public static System.Drawing.Color Gray { get { throw null; } } public static System.Drawing.Color Green { get { throw null; } } public static System.Drawing.Color GreenYellow { get { throw null; } } public static System.Drawing.Color Honeydew { get { throw null; } } public static System.Drawing.Color HotPink { get { throw null; } } public static System.Drawing.Color IndianRed { get { throw null; } } public static System.Drawing.Color Indigo { get { throw null; } } public bool IsEmpty { get { throw null; } } public bool IsKnownColor { get { throw null; } } public bool IsNamedColor { get { throw null; } } public bool IsSystemColor { get { throw null; } } public static System.Drawing.Color Ivory { get { throw null; } } public static System.Drawing.Color Khaki { get { throw null; } } public static System.Drawing.Color Lavender { get { throw null; } } public static System.Drawing.Color LavenderBlush { get { throw null; } } public static System.Drawing.Color LawnGreen { get { throw null; } } public static System.Drawing.Color LemonChiffon { get { throw null; } } public static System.Drawing.Color LightBlue { get { throw null; } } public static System.Drawing.Color LightCoral { get { throw null; } } public static System.Drawing.Color LightCyan { get { throw null; } } public static System.Drawing.Color LightGoldenrodYellow { get { throw null; } } public static System.Drawing.Color LightGray { get { throw null; } } public static System.Drawing.Color LightGreen { get { throw null; } } public static System.Drawing.Color LightPink { get { throw null; } } public static System.Drawing.Color LightSalmon { get { throw null; } } public static System.Drawing.Color LightSeaGreen { get { throw null; } } public static System.Drawing.Color LightSkyBlue { get { throw null; } } public static System.Drawing.Color LightSlateGray { get { throw null; } } public static System.Drawing.Color LightSteelBlue { get { throw null; } } public static System.Drawing.Color LightYellow { get { throw null; } } public static System.Drawing.Color Lime { get { throw null; } } public static System.Drawing.Color LimeGreen { get { throw null; } } public static System.Drawing.Color Linen { get { throw null; } } public static System.Drawing.Color Magenta { get { throw null; } } public static System.Drawing.Color Maroon { get { throw null; } } public static System.Drawing.Color MediumAquamarine { get { throw null; } } public static System.Drawing.Color MediumBlue { get { throw null; } } public static System.Drawing.Color MediumOrchid { get { throw null; } } public static System.Drawing.Color MediumPurple { get { throw null; } } public static System.Drawing.Color MediumSeaGreen { get { throw null; } } public static System.Drawing.Color MediumSlateBlue { get { throw null; } } public static System.Drawing.Color MediumSpringGreen { get { throw null; } } public static System.Drawing.Color MediumTurquoise { get { throw null; } } public static System.Drawing.Color MediumVioletRed { get { throw null; } } public static System.Drawing.Color MidnightBlue { get { throw null; } } public static System.Drawing.Color MintCream { get { throw null; } } public static System.Drawing.Color MistyRose { get { throw null; } } public static System.Drawing.Color Moccasin { get { throw null; } } public string Name { get { throw null; } } public static System.Drawing.Color NavajoWhite { get { throw null; } } public static System.Drawing.Color Navy { get { throw null; } } public static System.Drawing.Color OldLace { get { throw null; } } public static System.Drawing.Color Olive { get { throw null; } } public static System.Drawing.Color OliveDrab { get { throw null; } } public static System.Drawing.Color Orange { get { throw null; } } public static System.Drawing.Color OrangeRed { get { throw null; } } public static System.Drawing.Color Orchid { get { throw null; } } public static System.Drawing.Color PaleGoldenrod { get { throw null; } } public static System.Drawing.Color PaleGreen { get { throw null; } } public static System.Drawing.Color PaleTurquoise { get { throw null; } } public static System.Drawing.Color PaleVioletRed { get { throw null; } } public static System.Drawing.Color PapayaWhip { get { throw null; } } public static System.Drawing.Color PeachPuff { get { throw null; } } public static System.Drawing.Color Peru { get { throw null; } } public static System.Drawing.Color Pink { get { throw null; } } public static System.Drawing.Color Plum { get { throw null; } } public static System.Drawing.Color PowderBlue { get { throw null; } } public static System.Drawing.Color Purple { get { throw null; } } public byte R { get { throw null; } } public static System.Drawing.Color RebeccaPurple { get { throw null; } } public static System.Drawing.Color Red { get { throw null; } } public static System.Drawing.Color RosyBrown { get { throw null; } } public static System.Drawing.Color RoyalBlue { get { throw null; } } public static System.Drawing.Color SaddleBrown { get { throw null; } } public static System.Drawing.Color Salmon { get { throw null; } } public static System.Drawing.Color SandyBrown { get { throw null; } } public static System.Drawing.Color SeaGreen { get { throw null; } } public static System.Drawing.Color SeaShell { get { throw null; } } public static System.Drawing.Color Sienna { get { throw null; } } public static System.Drawing.Color Silver { get { throw null; } } public static System.Drawing.Color SkyBlue { get { throw null; } } public static System.Drawing.Color SlateBlue { get { throw null; } } public static System.Drawing.Color SlateGray { get { throw null; } } public static System.Drawing.Color Snow { get { throw null; } } public static System.Drawing.Color SpringGreen { get { throw null; } } public static System.Drawing.Color SteelBlue { get { throw null; } } public static System.Drawing.Color Tan { get { throw null; } } public static System.Drawing.Color Teal { get { throw null; } } public static System.Drawing.Color Thistle { get { throw null; } } public static System.Drawing.Color Tomato { get { throw null; } } public static System.Drawing.Color Transparent { get { throw null; } } public static System.Drawing.Color Turquoise { get { throw null; } } public static System.Drawing.Color Violet { get { throw null; } } public static System.Drawing.Color Wheat { get { throw null; } } public static System.Drawing.Color White { get { throw null; } } public static System.Drawing.Color WhiteSmoke { get { throw null; } } public static System.Drawing.Color Yellow { get { throw null; } } public static System.Drawing.Color YellowGreen { get { throw null; } } public bool Equals(System.Drawing.Color other) { throw null; } public override bool Equals([System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] object? obj) { throw null; } public static System.Drawing.Color FromArgb(int argb) { throw null; } public static System.Drawing.Color FromArgb(int alpha, System.Drawing.Color baseColor) { throw null; } public static System.Drawing.Color FromArgb(int red, int green, int blue) { throw null; } public static System.Drawing.Color FromArgb(int alpha, int red, int green, int blue) { throw null; } public static System.Drawing.Color FromKnownColor(System.Drawing.KnownColor color) { throw null; } public static System.Drawing.Color FromName(string name) { throw null; } public float GetBrightness() { throw null; } public override int GetHashCode() { throw null; } public float GetHue() { throw null; } public float GetSaturation() { throw null; } public static bool operator ==(System.Drawing.Color left, System.Drawing.Color right) { throw null; } public static bool operator !=(System.Drawing.Color left, System.Drawing.Color right) { throw null; } public int ToArgb() { throw null; } public System.Drawing.KnownColor ToKnownColor() { throw null; } public override string ToString() { throw null; } } public static partial class ColorTranslator { public static System.Drawing.Color FromHtml(string htmlColor) { throw null; } public static System.Drawing.Color FromOle(int oleColor) { throw null; } public static System.Drawing.Color FromWin32(int win32Color) { throw null; } public static string ToHtml(System.Drawing.Color c) { throw null; } public static int ToOle(System.Drawing.Color c) { throw null; } public static int ToWin32(System.Drawing.Color c) { throw null; } } public enum KnownColor { ActiveBorder = 1, ActiveCaption = 2, ActiveCaptionText = 3, AppWorkspace = 4, Control = 5, ControlDark = 6, ControlDarkDark = 7, ControlLight = 8, ControlLightLight = 9, ControlText = 10, Desktop = 11, GrayText = 12, Highlight = 13, HighlightText = 14, HotTrack = 15, InactiveBorder = 16, InactiveCaption = 17, InactiveCaptionText = 18, Info = 19, InfoText = 20, Menu = 21, MenuText = 22, ScrollBar = 23, Window = 24, WindowFrame = 25, WindowText = 26, Transparent = 27, AliceBlue = 28, AntiqueWhite = 29, Aqua = 30, Aquamarine = 31, Azure = 32, Beige = 33, Bisque = 34, Black = 35, BlanchedAlmond = 36, Blue = 37, BlueViolet = 38, Brown = 39, BurlyWood = 40, CadetBlue = 41, Chartreuse = 42, Chocolate = 43, Coral = 44, CornflowerBlue = 45, Cornsilk = 46, Crimson = 47, Cyan = 48, DarkBlue = 49, DarkCyan = 50, DarkGoldenrod = 51, DarkGray = 52, DarkGreen = 53, DarkKhaki = 54, DarkMagenta = 55, DarkOliveGreen = 56, DarkOrange = 57, DarkOrchid = 58, DarkRed = 59, DarkSalmon = 60, DarkSeaGreen = 61, DarkSlateBlue = 62, DarkSlateGray = 63, DarkTurquoise = 64, DarkViolet = 65, DeepPink = 66, DeepSkyBlue = 67, DimGray = 68, DodgerBlue = 69, Firebrick = 70, FloralWhite = 71, ForestGreen = 72, Fuchsia = 73, Gainsboro = 74, GhostWhite = 75, Gold = 76, Goldenrod = 77, Gray = 78, Green = 79, GreenYellow = 80, Honeydew = 81, HotPink = 82, IndianRed = 83, Indigo = 84, Ivory = 85, Khaki = 86, Lavender = 87, LavenderBlush = 88, LawnGreen = 89, LemonChiffon = 90, LightBlue = 91, LightCoral = 92, LightCyan = 93, LightGoldenrodYellow = 94, LightGray = 95, LightGreen = 96, LightPink = 97, LightSalmon = 98, LightSeaGreen = 99, LightSkyBlue = 100, LightSlateGray = 101, LightSteelBlue = 102, LightYellow = 103, Lime = 104, LimeGreen = 105, Linen = 106, Magenta = 107, Maroon = 108, MediumAquamarine = 109, MediumBlue = 110, MediumOrchid = 111, MediumPurple = 112, MediumSeaGreen = 113, MediumSlateBlue = 114, MediumSpringGreen = 115, MediumTurquoise = 116, MediumVioletRed = 117, MidnightBlue = 118, MintCream = 119, MistyRose = 120, Moccasin = 121, NavajoWhite = 122, Navy = 123, OldLace = 124, Olive = 125, OliveDrab = 126, Orange = 127, OrangeRed = 128, Orchid = 129, PaleGoldenrod = 130, PaleGreen = 131, PaleTurquoise = 132, PaleVioletRed = 133, PapayaWhip = 134, PeachPuff = 135, Peru = 136, Pink = 137, Plum = 138, PowderBlue = 139, Purple = 140, Red = 141, RosyBrown = 142, RoyalBlue = 143, SaddleBrown = 144, Salmon = 145, SandyBrown = 146, SeaGreen = 147, SeaShell = 148, Sienna = 149, Silver = 150, SkyBlue = 151, SlateBlue = 152, SlateGray = 153, Snow = 154, SpringGreen = 155, SteelBlue = 156, Tan = 157, Teal = 158, Thistle = 159, Tomato = 160, Turquoise = 161, Violet = 162, Wheat = 163, White = 164, WhiteSmoke = 165, Yellow = 166, YellowGreen = 167, ButtonFace = 168, ButtonHighlight = 169, ButtonShadow = 170, GradientActiveCaption = 171, GradientInactiveCaption = 172, MenuBar = 173, MenuHighlight = 174, RebeccaPurple = 175, } [System.ComponentModel.TypeConverterAttribute("System.Drawing.PointConverter, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] public partial struct Point : System.IEquatable<System.Drawing.Point> { private int _dummyPrimitive; public static readonly System.Drawing.Point Empty; public Point(System.Drawing.Size sz) { throw null; } public Point(int dw) { throw null; } public Point(int x, int y) { throw null; } [System.ComponentModel.BrowsableAttribute(false)] public readonly bool IsEmpty { get { throw null; } } public int X { readonly get { throw null; } set { } } public int Y { readonly get { throw null; } set { } } public static System.Drawing.Point Add(System.Drawing.Point pt, System.Drawing.Size sz) { throw null; } public static System.Drawing.Point Ceiling(System.Drawing.PointF value) { throw null; } public readonly bool Equals(System.Drawing.Point other) { throw null; } public override readonly bool Equals([System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] object? obj) { throw null; } public override readonly int GetHashCode() { throw null; } public void Offset(System.Drawing.Point p) { } public void Offset(int dx, int dy) { } public static System.Drawing.Point operator +(System.Drawing.Point pt, System.Drawing.Size sz) { throw null; } public static bool operator ==(System.Drawing.Point left, System.Drawing.Point right) { throw null; } public static explicit operator System.Drawing.Size (System.Drawing.Point p) { throw null; } public static implicit operator System.Drawing.PointF (System.Drawing.Point p) { throw null; } public static bool operator !=(System.Drawing.Point left, System.Drawing.Point right) { throw null; } public static System.Drawing.Point operator -(System.Drawing.Point pt, System.Drawing.Size sz) { throw null; } public static System.Drawing.Point Round(System.Drawing.PointF value) { throw null; } public static System.Drawing.Point Subtract(System.Drawing.Point pt, System.Drawing.Size sz) { throw null; } public override readonly string ToString() { throw null; } public static System.Drawing.Point Truncate(System.Drawing.PointF value) { throw null; } } public partial struct PointF : System.IEquatable<System.Drawing.PointF> { private int _dummyPrimitive; public static readonly System.Drawing.PointF Empty; public PointF(float x, float y) { throw null; } public PointF(System.Numerics.Vector2 vector) { throw null; } [System.ComponentModel.BrowsableAttribute(false)] public readonly bool IsEmpty { get { throw null; } } public float X { readonly get { throw null; } set { } } public float Y { readonly get { throw null; } set { } } public static System.Drawing.PointF Add(System.Drawing.PointF pt, System.Drawing.Size sz) { throw null; } public static System.Drawing.PointF Add(System.Drawing.PointF pt, System.Drawing.SizeF sz) { throw null; } public readonly bool Equals(System.Drawing.PointF other) { throw null; } public override readonly bool Equals([System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] object? obj) { throw null; } public override readonly int GetHashCode() { throw null; } public static explicit operator System.Numerics.Vector2(System.Drawing.PointF point) { throw null; } public static explicit operator System.Drawing.PointF(System.Numerics.Vector2 vector) { throw null; } public static System.Drawing.PointF operator +(System.Drawing.PointF pt, System.Drawing.Size sz) { throw null; } public static System.Drawing.PointF operator +(System.Drawing.PointF pt, System.Drawing.SizeF sz) { throw null; } public static bool operator ==(System.Drawing.PointF left, System.Drawing.PointF right) { throw null; } public static bool operator !=(System.Drawing.PointF left, System.Drawing.PointF right) { throw null; } public static System.Drawing.PointF operator -(System.Drawing.PointF pt, System.Drawing.Size sz) { throw null; } public static System.Drawing.PointF operator -(System.Drawing.PointF pt, System.Drawing.SizeF sz) { throw null; } public static System.Drawing.PointF Subtract(System.Drawing.PointF pt, System.Drawing.Size sz) { throw null; } public static System.Drawing.PointF Subtract(System.Drawing.PointF pt, System.Drawing.SizeF sz) { throw null; } public override readonly string ToString() { throw null; } public System.Numerics.Vector2 ToVector2() { throw null; } } [System.ComponentModel.TypeConverterAttribute("System.Drawing.RectangleConverter, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] public partial struct Rectangle : System.IEquatable<System.Drawing.Rectangle> { private int _dummyPrimitive; public static readonly System.Drawing.Rectangle Empty; public Rectangle(System.Drawing.Point location, System.Drawing.Size size) { throw null; } public Rectangle(int x, int y, int width, int height) { throw null; } [System.ComponentModel.BrowsableAttribute(false)] public readonly int Bottom { get { throw null; } } public int Height { readonly get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] public readonly bool IsEmpty { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] public readonly int Left { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] public System.Drawing.Point Location { readonly get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] public readonly int Right { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] public System.Drawing.Size Size { readonly get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] public readonly int Top { get { throw null; } } public int Width { readonly get { throw null; } set { } } public int X { readonly get { throw null; } set { } } public int Y { readonly get { throw null; } set { } } public static System.Drawing.Rectangle Ceiling(System.Drawing.RectangleF value) { throw null; } public readonly bool Contains(System.Drawing.Point pt) { throw null; } public readonly bool Contains(System.Drawing.Rectangle rect) { throw null; } public readonly bool Contains(int x, int y) { throw null; } public readonly bool Equals(System.Drawing.Rectangle other) { throw null; } public override readonly bool Equals([System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] object? obj) { throw null; } public static System.Drawing.Rectangle FromLTRB(int left, int top, int right, int bottom) { throw null; } public override readonly int GetHashCode() { throw null; } public static System.Drawing.Rectangle Inflate(System.Drawing.Rectangle rect, int x, int y) { throw null; } public void Inflate(System.Drawing.Size size) { } public void Inflate(int width, int height) { } public void Intersect(System.Drawing.Rectangle rect) { } public static System.Drawing.Rectangle Intersect(System.Drawing.Rectangle a, System.Drawing.Rectangle b) { throw null; } public readonly bool IntersectsWith(System.Drawing.Rectangle rect) { throw null; } public void Offset(System.Drawing.Point pos) { } public void Offset(int x, int y) { } public static bool operator ==(System.Drawing.Rectangle left, System.Drawing.Rectangle right) { throw null; } public static bool operator !=(System.Drawing.Rectangle left, System.Drawing.Rectangle right) { throw null; } public static System.Drawing.Rectangle Round(System.Drawing.RectangleF value) { throw null; } public override readonly string ToString() { throw null; } public static System.Drawing.Rectangle Truncate(System.Drawing.RectangleF value) { throw null; } public static System.Drawing.Rectangle Union(System.Drawing.Rectangle a, System.Drawing.Rectangle b) { throw null; } } public partial struct RectangleF : System.IEquatable<System.Drawing.RectangleF> { private int _dummyPrimitive; public static readonly System.Drawing.RectangleF Empty; public RectangleF(System.Drawing.PointF location, System.Drawing.SizeF size) { throw null; } public RectangleF(float x, float y, float width, float height) { throw null; } public RectangleF(System.Numerics.Vector4 vector) { throw null; } [System.ComponentModel.BrowsableAttribute(false)] public readonly float Bottom { get { throw null; } } public float Height { readonly get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] public readonly bool IsEmpty { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] public readonly float Left { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] public System.Drawing.PointF Location { readonly get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] public readonly float Right { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] public System.Drawing.SizeF Size { readonly get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] public readonly float Top { get { throw null; } } public float Width { readonly get { throw null; } set { } } public float X { readonly get { throw null; } set { } } public float Y { readonly get { throw null; } set { } } public readonly bool Contains(System.Drawing.PointF pt) { throw null; } public readonly bool Contains(System.Drawing.RectangleF rect) { throw null; } public readonly bool Contains(float x, float y) { throw null; } public readonly bool Equals(System.Drawing.RectangleF other) { throw null; } public override readonly bool Equals([System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] object? obj) { throw null; } public static System.Drawing.RectangleF FromLTRB(float left, float top, float right, float bottom) { throw null; } public override readonly int GetHashCode() { throw null; } public static System.Drawing.RectangleF Inflate(System.Drawing.RectangleF rect, float x, float y) { throw null; } public void Inflate(System.Drawing.SizeF size) { } public void Inflate(float x, float y) { } public void Intersect(System.Drawing.RectangleF rect) { } public static System.Drawing.RectangleF Intersect(System.Drawing.RectangleF a, System.Drawing.RectangleF b) { throw null; } public readonly bool IntersectsWith(System.Drawing.RectangleF rect) { throw null; } public void Offset(System.Drawing.PointF pos) { } public void Offset(float x, float y) { } public static explicit operator System.Numerics.Vector4(System.Drawing.RectangleF rectangle) { throw null; } public static explicit operator System.Drawing.RectangleF(System.Numerics.Vector4 vector) { throw null; } public static bool operator ==(System.Drawing.RectangleF left, System.Drawing.RectangleF right) { throw null; } public static implicit operator System.Drawing.RectangleF (System.Drawing.Rectangle r) { throw null; } public static bool operator !=(System.Drawing.RectangleF left, System.Drawing.RectangleF right) { throw null; } public override readonly string ToString() { throw null; } public System.Numerics.Vector4 ToVector4() { throw null; } public static System.Drawing.RectangleF Union(System.Drawing.RectangleF a, System.Drawing.RectangleF b) { throw null; } } [System.ComponentModel.TypeConverterAttribute("System.Drawing.SizeConverter, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] public partial struct Size : System.IEquatable<System.Drawing.Size> { private int _dummyPrimitive; public static readonly System.Drawing.Size Empty; public Size(System.Drawing.Point pt) { throw null; } public Size(int width, int height) { throw null; } public int Height { readonly get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] public readonly bool IsEmpty { get { throw null; } } public int Width { readonly get { throw null; } set { } } public static System.Drawing.Size Add(System.Drawing.Size sz1, System.Drawing.Size sz2) { throw null; } public static System.Drawing.Size Ceiling(System.Drawing.SizeF value) { throw null; } public readonly bool Equals(System.Drawing.Size other) { throw null; } public override readonly bool Equals([System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] object? obj) { throw null; } public override readonly int GetHashCode() { throw null; } public static System.Drawing.Size operator +(System.Drawing.Size sz1, System.Drawing.Size sz2) { throw null; } public static System.Drawing.Size operator /(System.Drawing.Size left, int right) { throw null; } public static System.Drawing.SizeF operator /(System.Drawing.Size left, float right) { throw null; } public static bool operator ==(System.Drawing.Size sz1, System.Drawing.Size sz2) { throw null; } public static explicit operator System.Drawing.Point (System.Drawing.Size size) { throw null; } public static implicit operator System.Drawing.SizeF (System.Drawing.Size p) { throw null; } public static bool operator !=(System.Drawing.Size sz1, System.Drawing.Size sz2) { throw null; } public static System.Drawing.Size operator *(System.Drawing.Size left, int right) { throw null; } public static System.Drawing.SizeF operator *(System.Drawing.Size left, float right) { throw null; } public static System.Drawing.Size operator *(int left, System.Drawing.Size right) { throw null; } public static System.Drawing.SizeF operator *(float left, System.Drawing.Size right) { throw null; } public static System.Drawing.Size operator -(System.Drawing.Size sz1, System.Drawing.Size sz2) { throw null; } public static System.Drawing.Size Round(System.Drawing.SizeF value) { throw null; } public static System.Drawing.Size Subtract(System.Drawing.Size sz1, System.Drawing.Size sz2) { throw null; } public override readonly string ToString() { throw null; } public static System.Drawing.Size Truncate(System.Drawing.SizeF value) { throw null; } } [System.ComponentModel.TypeConverterAttribute("System.Drawing.SizeFConverter, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] public partial struct SizeF : System.IEquatable<System.Drawing.SizeF> { private int _dummyPrimitive; public static readonly System.Drawing.SizeF Empty; public SizeF(System.Drawing.PointF pt) { throw null; } public SizeF(System.Drawing.SizeF size) { throw null; } public SizeF(float width, float height) { throw null; } public SizeF(System.Numerics.Vector2 vector) { throw null; } public float Height { readonly get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] public readonly bool IsEmpty { get { throw null; } } public float Width { readonly get { throw null; } set { } } public static System.Drawing.SizeF Add(System.Drawing.SizeF sz1, System.Drawing.SizeF sz2) { throw null; } public readonly bool Equals(System.Drawing.SizeF other) { throw null; } public override readonly bool Equals([System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] object? obj) { throw null; } public override readonly int GetHashCode() { throw null; } public static explicit operator System.Numerics.Vector2(System.Drawing.SizeF size) { throw null; } public static explicit operator System.Drawing.SizeF(System.Numerics.Vector2 vector) { throw null; } public static System.Drawing.SizeF operator +(System.Drawing.SizeF sz1, System.Drawing.SizeF sz2) { throw null; } public static System.Drawing.SizeF operator /(System.Drawing.SizeF left, float right) { throw null; } public static bool operator ==(System.Drawing.SizeF sz1, System.Drawing.SizeF sz2) { throw null; } public static explicit operator System.Drawing.PointF (System.Drawing.SizeF size) { throw null; } public static bool operator !=(System.Drawing.SizeF sz1, System.Drawing.SizeF sz2) { throw null; } public static System.Drawing.SizeF operator *(System.Drawing.SizeF left, float right) { throw null; } public static System.Drawing.SizeF operator *(float left, System.Drawing.SizeF right) { throw null; } public static System.Drawing.SizeF operator -(System.Drawing.SizeF sz1, System.Drawing.SizeF sz2) { throw null; } public static System.Drawing.SizeF Subtract(System.Drawing.SizeF sz1, System.Drawing.SizeF sz2) { throw null; } public readonly System.Drawing.PointF ToPointF() { throw null; } public readonly System.Drawing.Size ToSize() { throw null; } public override readonly string ToString() { throw null; } public System.Numerics.Vector2 ToVector2() { throw null; } } public static partial class SystemColors { public static System.Drawing.Color ActiveBorder { get { throw null; } } public static System.Drawing.Color ActiveCaption { get { throw null; } } public static System.Drawing.Color ActiveCaptionText { get { throw null; } } public static System.Drawing.Color AppWorkspace { get { throw null; } } public static System.Drawing.Color ButtonFace { get { throw null; } } public static System.Drawing.Color ButtonHighlight { get { throw null; } } public static System.Drawing.Color ButtonShadow { get { throw null; } } public static System.Drawing.Color Control { get { throw null; } } public static System.Drawing.Color ControlDark { get { throw null; } } public static System.Drawing.Color ControlDarkDark { get { throw null; } } public static System.Drawing.Color ControlLight { get { throw null; } } public static System.Drawing.Color ControlLightLight { get { throw null; } } public static System.Drawing.Color ControlText { get { throw null; } } public static System.Drawing.Color Desktop { get { throw null; } } public static System.Drawing.Color GradientActiveCaption { get { throw null; } } public static System.Drawing.Color GradientInactiveCaption { get { throw null; } } public static System.Drawing.Color GrayText { get { throw null; } } public static System.Drawing.Color Highlight { get { throw null; } } public static System.Drawing.Color HighlightText { get { throw null; } } public static System.Drawing.Color HotTrack { get { throw null; } } public static System.Drawing.Color InactiveBorder { get { throw null; } } public static System.Drawing.Color InactiveCaption { get { throw null; } } public static System.Drawing.Color InactiveCaptionText { get { throw null; } } public static System.Drawing.Color Info { get { throw null; } } public static System.Drawing.Color InfoText { get { throw null; } } public static System.Drawing.Color Menu { get { throw null; } } public static System.Drawing.Color MenuBar { get { throw null; } } public static System.Drawing.Color MenuHighlight { get { throw null; } } public static System.Drawing.Color MenuText { get { throw null; } } public static System.Drawing.Color ScrollBar { get { throw null; } } public static System.Drawing.Color Window { get { throw null; } } public static System.Drawing.Color WindowFrame { get { throw null; } } public static System.Drawing.Color WindowText { get { throw null; } } } }
-1
dotnet/runtime
66,474
Update repo CMake configuration to target /W4 by default
Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
AaronRobinsonMSFT
2022-03-10T20:20:31Z
2022-03-11T04:59:21Z
ba5207b0f4054fe8963fc3e87c2bd32907516961
5ce2b9f860f7a84c3059650bb67817d59d8f4953
Update repo CMake configuration to target /W4 by default. Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
./src/tests/CoreMangLib/system/enum/EnumIConvertibleToUint64.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="enumiconvertibletouint64.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="$(TestSourceDir)Common/CoreCLRTestLibrary/CoreCLRTestLibrary.csproj" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="enumiconvertibletouint64.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="$(TestSourceDir)Common/CoreCLRTestLibrary/CoreCLRTestLibrary.csproj" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,474
Update repo CMake configuration to target /W4 by default
Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
AaronRobinsonMSFT
2022-03-10T20:20:31Z
2022-03-11T04:59:21Z
ba5207b0f4054fe8963fc3e87c2bd32907516961
5ce2b9f860f7a84c3059650bb67817d59d8f4953
Update repo CMake configuration to target /W4 by default. Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
./src/tests/Interop/PInvoke/Generics/GenericsNative.Vector64U.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include <stdio.h> #include <stdint.h> #include <xplatform.h> #include <platformdefines.h> #if defined(TARGET_XARCH) #include <mmintrin.h> typedef __m64 Vector64U; #elif defined(TARGET_ARMARCH) #if defined(_MSC_VER) #if defined(TARGET_ARM64) #include <arm64_neon.h> #else #include <arm_neon.h> #endif #elif defined(TARGET_ARM64) #include <arm_neon.h> #else typedef struct { uint32_t e00; uint32_t e01; } uint32x2_t; #endif typedef uint32x2_t Vector64U; #else #error Unsupported target architecture #endif static Vector64U Vector64UValue = { }; extern "C" DLL_EXPORT Vector64U STDMETHODCALLTYPE GetVector64U(uint32_t e00, uint32_t e01) { union { uint32_t value[2]; Vector64U result; }; value[0] = e00; value[1] = e01; return result; } extern "C" DLL_EXPORT void STDMETHODCALLTYPE GetVector64UOut(uint32_t e00, uint32_t e01, Vector64U* pValue) { *pValue = GetVector64U(e00, e01); #if defined(_MSC_VER) && defined(TARGET_X86) _mm_empty(); #endif // _MSC_VER && TARGET_X86 } extern "C" DLL_EXPORT const Vector64U* STDMETHODCALLTYPE GetVector64UPtr(uint32_t e00, uint32_t e01) { GetVector64UOut(e00, e01, &Vector64UValue); return &Vector64UValue; } extern "C" DLL_EXPORT Vector64U STDMETHODCALLTYPE AddVector64U(Vector64U lhs, Vector64U rhs) { throw "P/Invoke for Vector64<uint> should be unsupported."; } extern "C" DLL_EXPORT Vector64U STDMETHODCALLTYPE AddVector64Us(const Vector64U* pValues, uint32_t count) { throw "P/Invoke for Vector64<uint> should be unsupported."; }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include <stdio.h> #include <stdint.h> #include <xplatform.h> #include <platformdefines.h> #if defined(TARGET_XARCH) #include <mmintrin.h> typedef __m64 Vector64U; #elif defined(TARGET_ARMARCH) #if defined(_MSC_VER) #if defined(TARGET_ARM64) #include <arm64_neon.h> #else #include <arm_neon.h> #endif #elif defined(TARGET_ARM64) #include <arm_neon.h> #else typedef struct { uint32_t e00; uint32_t e01; } uint32x2_t; #endif typedef uint32x2_t Vector64U; #else #error Unsupported target architecture #endif static Vector64U Vector64UValue = { }; extern "C" DLL_EXPORT Vector64U STDMETHODCALLTYPE GetVector64U(uint32_t e00, uint32_t e01) { union { uint32_t value[2]; Vector64U result; }; value[0] = e00; value[1] = e01; return result; } extern "C" DLL_EXPORT void STDMETHODCALLTYPE GetVector64UOut(uint32_t e00, uint32_t e01, Vector64U* pValue) { *pValue = GetVector64U(e00, e01); #if defined(_MSC_VER) && defined(TARGET_X86) _mm_empty(); #endif // _MSC_VER && TARGET_X86 } extern "C" DLL_EXPORT const Vector64U* STDMETHODCALLTYPE GetVector64UPtr(uint32_t e00, uint32_t e01) { GetVector64UOut(e00, e01, &Vector64UValue); return &Vector64UValue; } extern "C" DLL_EXPORT Vector64U STDMETHODCALLTYPE AddVector64U(Vector64U lhs, Vector64U rhs) { throw "P/Invoke for Vector64<uint> should be unsupported."; } extern "C" DLL_EXPORT Vector64U STDMETHODCALLTYPE AddVector64Us(const Vector64U* pValues, uint32_t count) { throw "P/Invoke for Vector64<uint> should be unsupported."; }
-1
dotnet/runtime
66,474
Update repo CMake configuration to target /W4 by default
Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
AaronRobinsonMSFT
2022-03-10T20:20:31Z
2022-03-11T04:59:21Z
ba5207b0f4054fe8963fc3e87c2bd32907516961
5ce2b9f860f7a84c3059650bb67817d59d8f4953
Update repo CMake configuration to target /W4 by default. Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
./src/coreclr/tools/aot/ILLink.Shared/ILLink.LinkAttributes.xsd
<?xml version="1.0" encoding="utf-8"?> <xsd:schema attributeFormDefault="unqualified" elementFormDefault="unqualified" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:complexType name="membertype"> <xsd:choice maxOccurs="unbounded" minOccurs="0"> <xsd:element name="attribute" type="attribute" /> </xsd:choice> <xsd:attribute name="feature" /> <xsd:attribute name="featurevalue" type="xsd:boolean" /> <xsd:attribute name="featuredefault" type="xsd:boolean" /> <xsd:attribute name="name" /> <xsd:attribute name="signature" /> </xsd:complexType> <xsd:complexType name="method"> <xsd:complexContent> <xsd:extension base="membertype"> <xsd:choice maxOccurs="unbounded" minOccurs="0"> <xsd:choice maxOccurs="unbounded" minOccurs="0"> <xsd:element name="parameter"> <xsd:complexType> <xsd:choice maxOccurs="unbounded" minOccurs="0"> <xsd:element name="attribute" type="attribute" /> </xsd:choice> <xsd:attribute name="name" use="required" /> </xsd:complexType> </xsd:element> </xsd:choice> <xsd:choice maxOccurs="1" minOccurs="0"> <xsd:element name="return"> <xsd:complexType> <xsd:choice maxOccurs="unbounded" minOccurs="0"> <xsd:element name="attribute" type="attribute" /> </xsd:choice> </xsd:complexType> </xsd:element> </xsd:choice> </xsd:choice> </xsd:extension> </xsd:complexContent> </xsd:complexType> <xsd:complexType name="argument" mixed="true"> <xsd:choice minOccurs="0" maxOccurs="1"> <xsd:element name="argument"> <xsd:complexType> <xsd:simpleContent> <xsd:extension base="xsd:string"> <xsd:attribute name="type" /> </xsd:extension> </xsd:simpleContent> </xsd:complexType> </xsd:element> </xsd:choice> <xsd:attribute name="type" /> </xsd:complexType> <xsd:complexType name="attribute"> <xsd:choice maxOccurs="unbounded" minOccurs="0"> <xsd:element name="argument" type="argument" /> <xsd:element name="property"> <xsd:complexType mixed="true"> <xsd:attribute name="name" use="required" /> </xsd:complexType> </xsd:element> </xsd:choice> <xsd:attribute name="internal" /> <xsd:attribute name="fullname" /> <xsd:attribute name="assembly" /> </xsd:complexType> <xsd:complexType name="assembly"> <xsd:choice maxOccurs="unbounded" minOccurs="0"> <xsd:element name="attribute" type="attribute" /> <xsd:element name="type" type="type" /> </xsd:choice> <xsd:attribute name="fullname" use="required" /> <xsd:attribute name="feature" /> <xsd:attribute name="featurevalue" type="xsd:boolean" /> <xsd:attribute name="featuredefault" type="xsd:boolean" /> </xsd:complexType> <xsd:complexType name ="nestedtype"> <xsd:choice minOccurs="0" maxOccurs="unbounded"> <xsd:element name="event" type="membertype" /> <xsd:element name="method" type="method" /> <xsd:element name="field" type="membertype" /> <xsd:element name="property" type="membertype" /> <xsd:element name="attribute" type="attribute" /> <xsd:element name="type" type="nestedtype" /> </xsd:choice> <xsd:attribute name="name" use="required"/> <xsd:attribute name="feature" /> <xsd:attribute name="featurevalue" type="xsd:boolean" /> <xsd:attribute name="featuredefault" type="xsd:boolean" /> </xsd:complexType> <xsd:complexType name="type"> <xsd:choice maxOccurs="unbounded" minOccurs="0"> <xsd:element name="attribute" type="attribute" /> <xsd:element name="event" type="membertype" /> <xsd:element name="method" type="method" /> <xsd:element name="field" type="membertype" /> <xsd:element name="property" type="membertype" /> <xsd:element name="type" type="nestedtype"/> </xsd:choice> <xsd:attribute name="feature" /> <xsd:attribute name="featurevalue" type="xsd:boolean" /> <xsd:attribute name="featuredefault" type="xsd:boolean" /> <xsd:attribute name="fullname" use="required"/> </xsd:complexType> <xsd:element name="linker"> <xsd:complexType> <xsd:choice maxOccurs="unbounded" minOccurs="0"> <xsd:element name="assembly" type="assembly" /> <xsd:element name="type" type="type" /> </xsd:choice> </xsd:complexType> </xsd:element> </xsd:schema>
<?xml version="1.0" encoding="utf-8"?> <xsd:schema attributeFormDefault="unqualified" elementFormDefault="unqualified" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:complexType name="membertype"> <xsd:choice maxOccurs="unbounded" minOccurs="0"> <xsd:element name="attribute" type="attribute" /> </xsd:choice> <xsd:attribute name="feature" /> <xsd:attribute name="featurevalue" type="xsd:boolean" /> <xsd:attribute name="featuredefault" type="xsd:boolean" /> <xsd:attribute name="name" /> <xsd:attribute name="signature" /> </xsd:complexType> <xsd:complexType name="method"> <xsd:complexContent> <xsd:extension base="membertype"> <xsd:choice maxOccurs="unbounded" minOccurs="0"> <xsd:choice maxOccurs="unbounded" minOccurs="0"> <xsd:element name="parameter"> <xsd:complexType> <xsd:choice maxOccurs="unbounded" minOccurs="0"> <xsd:element name="attribute" type="attribute" /> </xsd:choice> <xsd:attribute name="name" use="required" /> </xsd:complexType> </xsd:element> </xsd:choice> <xsd:choice maxOccurs="1" minOccurs="0"> <xsd:element name="return"> <xsd:complexType> <xsd:choice maxOccurs="unbounded" minOccurs="0"> <xsd:element name="attribute" type="attribute" /> </xsd:choice> </xsd:complexType> </xsd:element> </xsd:choice> </xsd:choice> </xsd:extension> </xsd:complexContent> </xsd:complexType> <xsd:complexType name="argument" mixed="true"> <xsd:choice minOccurs="0" maxOccurs="1"> <xsd:element name="argument"> <xsd:complexType> <xsd:simpleContent> <xsd:extension base="xsd:string"> <xsd:attribute name="type" /> </xsd:extension> </xsd:simpleContent> </xsd:complexType> </xsd:element> </xsd:choice> <xsd:attribute name="type" /> </xsd:complexType> <xsd:complexType name="attribute"> <xsd:choice maxOccurs="unbounded" minOccurs="0"> <xsd:element name="argument" type="argument" /> <xsd:element name="property"> <xsd:complexType mixed="true"> <xsd:attribute name="name" use="required" /> </xsd:complexType> </xsd:element> </xsd:choice> <xsd:attribute name="internal" /> <xsd:attribute name="fullname" /> <xsd:attribute name="assembly" /> </xsd:complexType> <xsd:complexType name="assembly"> <xsd:choice maxOccurs="unbounded" minOccurs="0"> <xsd:element name="attribute" type="attribute" /> <xsd:element name="type" type="type" /> </xsd:choice> <xsd:attribute name="fullname" use="required" /> <xsd:attribute name="feature" /> <xsd:attribute name="featurevalue" type="xsd:boolean" /> <xsd:attribute name="featuredefault" type="xsd:boolean" /> </xsd:complexType> <xsd:complexType name ="nestedtype"> <xsd:choice minOccurs="0" maxOccurs="unbounded"> <xsd:element name="event" type="membertype" /> <xsd:element name="method" type="method" /> <xsd:element name="field" type="membertype" /> <xsd:element name="property" type="membertype" /> <xsd:element name="attribute" type="attribute" /> <xsd:element name="type" type="nestedtype" /> </xsd:choice> <xsd:attribute name="name" use="required"/> <xsd:attribute name="feature" /> <xsd:attribute name="featurevalue" type="xsd:boolean" /> <xsd:attribute name="featuredefault" type="xsd:boolean" /> </xsd:complexType> <xsd:complexType name="type"> <xsd:choice maxOccurs="unbounded" minOccurs="0"> <xsd:element name="attribute" type="attribute" /> <xsd:element name="event" type="membertype" /> <xsd:element name="method" type="method" /> <xsd:element name="field" type="membertype" /> <xsd:element name="property" type="membertype" /> <xsd:element name="type" type="nestedtype"/> </xsd:choice> <xsd:attribute name="feature" /> <xsd:attribute name="featurevalue" type="xsd:boolean" /> <xsd:attribute name="featuredefault" type="xsd:boolean" /> <xsd:attribute name="fullname" use="required"/> </xsd:complexType> <xsd:element name="linker"> <xsd:complexType> <xsd:choice maxOccurs="unbounded" minOccurs="0"> <xsd:element name="assembly" type="assembly" /> <xsd:element name="type" type="type" /> </xsd:choice> </xsd:complexType> </xsd:element> </xsd:schema>
-1
dotnet/runtime
66,474
Update repo CMake configuration to target /W4 by default
Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
AaronRobinsonMSFT
2022-03-10T20:20:31Z
2022-03-11T04:59:21Z
ba5207b0f4054fe8963fc3e87c2bd32907516961
5ce2b9f860f7a84c3059650bb67817d59d8f4953
Update repo CMake configuration to target /W4 by default. Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
./src/tests/JIT/Regression/CLR-x86-JIT/v2.1/DDB/B168384/LdfldaHack.ilproj
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="LdfldaHack.il" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="LdfldaHack.il" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,474
Update repo CMake configuration to target /W4 by default
Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
AaronRobinsonMSFT
2022-03-10T20:20:31Z
2022-03-11T04:59:21Z
ba5207b0f4054fe8963fc3e87c2bd32907516961
5ce2b9f860f7a84c3059650bb67817d59d8f4953
Update repo CMake configuration to target /W4 by default. Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
./src/tests/JIT/HardwareIntrinsics/X86/Shared/ScalarUnOpTest.template
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void {Method}{RetBaseType}() { var test = new ScalarUnaryOpTest__{Method}{RetBaseType}(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.ReadUnaligned test.RunBasicScenario_UnsafeRead(); // Validates calling via reflection works, using Unsafe.ReadUnaligned test.RunReflectionScenario_UnsafeRead(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.ReadUnaligned test.RunLclVarScenario_UnsafeRead(); // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ScalarUnaryOpTest__{Method}{RetBaseType} { private struct TestStruct { public {Op1BaseType} _fld; public static TestStruct Create() { var testStruct = new TestStruct(); testStruct._fld = {NextValueOp1}; return testStruct; } public void RunStructFldScenario(ScalarUnaryOpTest__{Method}{RetBaseType} testClass) { var result = {Isa}.{Method}(_fld); testClass.ValidateResult(_fld, result); } } private static {Op1BaseType} _data; private static {Op1BaseType} _clsVar; private {Op1BaseType} _fld; static ScalarUnaryOpTest__{Method}{RetBaseType}() { _clsVar = {NextValueOp1}; } public ScalarUnaryOpTest__{Method}{RetBaseType}() { Succeeded = true; _fld = {NextValueOp1}; _data = {NextValueOp1}; } public bool IsSupported => {Isa}.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = {Isa}.{Method}( Unsafe.ReadUnaligned<{Op1BaseType}>(ref Unsafe.As<{Op1BaseType}, byte>(ref _data)) ); ValidateResult(_data, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof({Isa}).GetMethod(nameof({Isa}.{Method}), new Type[] { typeof({Op1BaseType}) }) .Invoke(null, new object[] { Unsafe.ReadUnaligned<{Op1BaseType}>(ref Unsafe.As<{Op1BaseType}, byte>(ref _data)) }); ValidateResult(_data, ({RetBaseType})result); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = {Isa}.{Method}( _clsVar ); ValidateResult(_clsVar, result); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var data = Unsafe.ReadUnaligned<{Op1BaseType}>(ref Unsafe.As<{Op1BaseType}, byte>(ref _data)); var result = {Isa}.{Method}(data); ValidateResult(data, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ScalarUnaryOpTest__{Method}{RetBaseType}(); var result = {Isa}.{Method}(test._fld); ValidateResult(test._fld, result); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = {Isa}.{Method}(_fld); ValidateResult(_fld, result); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = {Isa}.{Method}(test._fld); ValidateResult(test._fld, result); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult({Op1BaseType} data, {RetBaseType} result, [CallerMemberName] string method = "") { var isUnexpectedResult = false; {ValidateResult} if (isUnexpectedResult) { TestLibrary.TestFramework.LogInformation($"{nameof({Isa})}.{nameof({Isa}.{Method})}<{RetBaseType}>({Op1BaseType}): {Method} failed:"); TestLibrary.TestFramework.LogInformation($" data: {data}"); TestLibrary.TestFramework.LogInformation($" result: {result}"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void {Method}{RetBaseType}() { var test = new ScalarUnaryOpTest__{Method}{RetBaseType}(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.ReadUnaligned test.RunBasicScenario_UnsafeRead(); // Validates calling via reflection works, using Unsafe.ReadUnaligned test.RunReflectionScenario_UnsafeRead(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.ReadUnaligned test.RunLclVarScenario_UnsafeRead(); // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ScalarUnaryOpTest__{Method}{RetBaseType} { private struct TestStruct { public {Op1BaseType} _fld; public static TestStruct Create() { var testStruct = new TestStruct(); testStruct._fld = {NextValueOp1}; return testStruct; } public void RunStructFldScenario(ScalarUnaryOpTest__{Method}{RetBaseType} testClass) { var result = {Isa}.{Method}(_fld); testClass.ValidateResult(_fld, result); } } private static {Op1BaseType} _data; private static {Op1BaseType} _clsVar; private {Op1BaseType} _fld; static ScalarUnaryOpTest__{Method}{RetBaseType}() { _clsVar = {NextValueOp1}; } public ScalarUnaryOpTest__{Method}{RetBaseType}() { Succeeded = true; _fld = {NextValueOp1}; _data = {NextValueOp1}; } public bool IsSupported => {Isa}.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = {Isa}.{Method}( Unsafe.ReadUnaligned<{Op1BaseType}>(ref Unsafe.As<{Op1BaseType}, byte>(ref _data)) ); ValidateResult(_data, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof({Isa}).GetMethod(nameof({Isa}.{Method}), new Type[] { typeof({Op1BaseType}) }) .Invoke(null, new object[] { Unsafe.ReadUnaligned<{Op1BaseType}>(ref Unsafe.As<{Op1BaseType}, byte>(ref _data)) }); ValidateResult(_data, ({RetBaseType})result); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = {Isa}.{Method}( _clsVar ); ValidateResult(_clsVar, result); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var data = Unsafe.ReadUnaligned<{Op1BaseType}>(ref Unsafe.As<{Op1BaseType}, byte>(ref _data)); var result = {Isa}.{Method}(data); ValidateResult(data, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ScalarUnaryOpTest__{Method}{RetBaseType}(); var result = {Isa}.{Method}(test._fld); ValidateResult(test._fld, result); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = {Isa}.{Method}(_fld); ValidateResult(_fld, result); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = {Isa}.{Method}(test._fld); ValidateResult(test._fld, result); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult({Op1BaseType} data, {RetBaseType} result, [CallerMemberName] string method = "") { var isUnexpectedResult = false; {ValidateResult} if (isUnexpectedResult) { TestLibrary.TestFramework.LogInformation($"{nameof({Isa})}.{nameof({Isa}.{Method})}<{RetBaseType}>({Op1BaseType}): {Method} failed:"); TestLibrary.TestFramework.LogInformation($" data: {data}"); TestLibrary.TestFramework.LogInformation($" result: {result}"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,474
Update repo CMake configuration to target /W4 by default
Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
AaronRobinsonMSFT
2022-03-10T20:20:31Z
2022-03-11T04:59:21Z
ba5207b0f4054fe8963fc3e87c2bd32907516961
5ce2b9f860f7a84c3059650bb67817d59d8f4953
Update repo CMake configuration to target /W4 by default. Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
./src/tests/Loader/AssemblyDependencyResolver/AssemblyDependencyResolverTests/NativeDependencyTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.IO; using System.Runtime.InteropServices; using System.Runtime.Loader; using TestLibrary; using Xunit; namespace AssemblyDependencyResolverTests { class NativeDependencyTests : TestBase { string _componentDirectory; string _componentAssemblyPath; protected override void Initialize() { HostPolicyMock.Initialize(TestBasePath, CoreRoot); _componentDirectory = Path.Combine(TestBasePath, $"TestComponent_{Guid.NewGuid().ToString().Substring(0, 8)}"); Directory.CreateDirectory(_componentDirectory); _componentAssemblyPath = CreateMockFile("TestComponent.dll"); } protected override void Cleanup() { if (Directory.Exists(_componentDirectory)) { Directory.Delete(_componentDirectory, recursive: true); } } public void TestSimpleNameAndNoPrefixAndNoSuffix() { ValidateNativeLibraryResolutions("{0}", "{0}", OS.Windows | OS.OSX | OS.Linux); } public void TestSimpleNameAndNoPrefixAndSuffix() { ValidateNativeLibraryResolutions("{0}.dll", "{0}", OS.Windows); ValidateNativeLibraryResolutions("{0}.dylib", "{0}", OS.OSX); ValidateNativeLibraryResolutions("{0}.so", "{0}", OS.Linux); } public void TestSimpleNameAndLibPrefixAndNoSuffix() { ValidateNativeLibraryResolutions("lib{0}", "{0}", OS.OSX | OS.Linux); } public void TestRelativeNameAndLibPrefixAndNoSuffix() { // The lib prefix is not added if the lookup is a relative path. ValidateNativeLibraryWithRelativeLookupResolutions("lib{0}", "{0}", 0); } public void TestSimpleNameAndLibPrefixAndSuffix() { ValidateNativeLibraryResolutions("lib{0}.dll", "{0}", 0); ValidateNativeLibraryResolutions("lib{0}.dylib", "{0}", OS.OSX); ValidateNativeLibraryResolutions("lib{0}.so", "{0}", OS.Linux); } public void TestNameWithSuffixAndNoPrefixAndNoSuffix() { ValidateNativeLibraryResolutions("{0}", "{0}.dll", 0); ValidateNativeLibraryResolutions("{0}", "{0}.dylib", 0); ValidateNativeLibraryResolutions("{0}", "{0}.so", 0); } public void TestNameWithSuffixAndNoPrefixAndSuffix() { ValidateNativeLibraryResolutions("{0}.dll", "{0}.dll", OS.Windows | OS.OSX | OS.Linux); ValidateNativeLibraryResolutions("{0}.dylib", "{0}.dylib", OS.Windows | OS.OSX | OS.Linux); ValidateNativeLibraryResolutions("{0}.so", "{0}.so", OS.Windows | OS.OSX | OS.Linux); } public void TestNameWithSuffixAndNoPrefixAndDoubleSuffix() { // Unixes add the suffix even if one is already present. ValidateNativeLibraryResolutions("{0}.dll.dll", "{0}.dll", 0); ValidateNativeLibraryResolutions("{0}.dylib.dylib", "{0}.dylib", OS.OSX); ValidateNativeLibraryResolutions("{0}.so.so", "{0}.so", OS.Linux); } public void TestNameWithSuffixAndPrefixAndNoSuffix() { ValidateNativeLibraryResolutions("lib{0}", "{0}.dll", 0); ValidateNativeLibraryResolutions("lib{0}", "{0}.dylib", 0); ValidateNativeLibraryResolutions("lib{0}", "{0}.so", 0); } public void TestNameWithSuffixAndPrefixAndSuffix() { ValidateNativeLibraryResolutions("lib{0}.dll", "{0}.dll", OS.OSX | OS.Linux); ValidateNativeLibraryResolutions("lib{0}.dylib", "{0}.dylib", OS.OSX | OS.Linux); ValidateNativeLibraryResolutions("lib{0}.so", "{0}.so", OS.OSX | OS.Linux); } public void TestRelativeNameWithSuffixAndPrefixAndSuffix() { // The lib prefix is not added if the lookup is a relative path ValidateNativeLibraryWithRelativeLookupResolutions("lib{0}.dll", "{0}.dll", 0); ValidateNativeLibraryWithRelativeLookupResolutions("lib{0}.dylib", "{0}.dylib", 0); ValidateNativeLibraryWithRelativeLookupResolutions("lib{0}.so", "{0}.so", 0); } public void TestNameWithPrefixAndNoPrefixAndNoSuffix() { ValidateNativeLibraryResolutions("{0}", "lib{0}", 0); } public void TestNameWithPrefixAndPrefixAndNoSuffix() { ValidateNativeLibraryResolutions("lib{0}", "lib{0}", OS.Windows | OS.OSX | OS.Linux); } public void TestNameWithPrefixAndNoPrefixAndSuffix() { ValidateNativeLibraryResolutions("{0}.dll", "lib{0}", 0); ValidateNativeLibraryResolutions("{0}.dylib", "lib{0}", 0); ValidateNativeLibraryResolutions("{0}.so", "lib{0}", 0); } public void TestNameWithPrefixAndPrefixAndSuffix() { ValidateNativeLibraryResolutions("lib{0}.dll", "lib{0}", OS.Windows); ValidateNativeLibraryResolutions("lib{0}.dylib", "lib{0}", OS.OSX); ValidateNativeLibraryResolutions("lib{0}.so", "lib{0}", OS.Linux); } public void TestWindowsAddsSuffixEvenWithOnePresent() { ValidateNativeLibraryResolutions("{0}.ext.dll", "{0}.ext", OS.Windows); } public void TestWindowsDoesntAddSuffixWhenExectubaleIsPresent() { ValidateNativeLibraryResolutions("{0}.dll.dll", "{0}.dll", 0); ValidateNativeLibraryResolutions("{0}.dll.exe", "{0}.dll", 0); ValidateNativeLibraryResolutions("{0}.exe.dll", "{0}.exe", 0); ValidateNativeLibraryResolutions("{0}.exe.exe", "{0}.exe", 0); } private void TestLookupWithSuffixPrefersUnmodifiedSuffixOnUnixes() { ValidateNativeLibraryResolutionsWithTwoFiles("{0}.dylib", "lib{0}.dylib", "{0}.dylib", OS.OSX); ValidateNativeLibraryResolutionsWithTwoFiles("{0}.so", "lib{0}.so", "{0}.so", OS.Linux); ValidateNativeLibraryResolutionsWithTwoFiles("{0}.dylib", "{0}.dylib.dylib", "{0}.dylib", OS.OSX); ValidateNativeLibraryResolutionsWithTwoFiles("{0}.so", "{0}.so.so", "{0}.so", OS.Linux); } private void TestLookupWithoutSuffixPrefersWithSuffixOnUnixes() { ValidateNativeLibraryResolutionsWithTwoFiles("{0}.dylib", "lib{0}.dylib", "{0}", OS.OSX); ValidateNativeLibraryResolutionsWithTwoFiles("{0}.so", "lib{0}.so", "{0}", OS.Linux); ValidateNativeLibraryResolutionsWithTwoFiles("{0}.dylib", "{0}", "{0}", OS.OSX); ValidateNativeLibraryResolutionsWithTwoFiles("{0}.so", "{0}", "{0}", OS.Linux); ValidateNativeLibraryResolutionsWithTwoFiles("{0}.dylib", "lib{0}", "{0}", OS.OSX); ValidateNativeLibraryResolutionsWithTwoFiles("{0}.so", "lib{0}", "{0}", OS.Linux); } public void TestFullPathLookupWithMatchingFileName() { ValidateFullPathNativeLibraryResolutions("{0}", "{0}", OS.Windows | OS.OSX | OS.Linux); ValidateFullPathNativeLibraryResolutions("{0}.dll", "{0}.dll", OS.Windows | OS.OSX | OS.Linux); ValidateFullPathNativeLibraryResolutions("{0}.dylib", "{0}.dylib", OS.Windows | OS.OSX | OS.Linux); ValidateFullPathNativeLibraryResolutions("{0}.so", "{0}.so", OS.Windows | OS.OSX | OS.Linux); ValidateFullPathNativeLibraryResolutions("lib{0}", "lib{0}", OS.Windows | OS.OSX | OS.Linux); ValidateFullPathNativeLibraryResolutions("lib{0}.dll", "lib{0}.dll", OS.Windows | OS.OSX | OS.Linux); ValidateFullPathNativeLibraryResolutions("lib{0}.dylib", "lib{0}.dylib", OS.Windows | OS.OSX | OS.Linux); ValidateFullPathNativeLibraryResolutions("lib{0}.so", "lib{0}.so", OS.Windows | OS.OSX | OS.Linux); } public void TestFullPathLookupWithDifferentFileName() { ValidateFullPathNativeLibraryResolutions("lib{0}", "{0}", 0); ValidateFullPathNativeLibraryResolutions("{0}.dll", "{0}", 0); ValidateFullPathNativeLibraryResolutions("{0}.dylib", "{0}", 0); ValidateFullPathNativeLibraryResolutions("{0}.so", "{0}", 0); ValidateFullPathNativeLibraryResolutions("lib{0}.dll", "{0}", 0); ValidateFullPathNativeLibraryResolutions("lib{0}.dylib", "{0}", 0); ValidateFullPathNativeLibraryResolutions("lib{0}.so", "{0}", 0); ValidateFullPathNativeLibraryResolutions("lib{0}.dll", "{0}.dll", 0); ValidateFullPathNativeLibraryResolutions("lib{0}.dylib", "{0}.dylib", 0); ValidateFullPathNativeLibraryResolutions("lib{0}.so", "{0}.so", 0); } [Flags] private enum OS { Windows = 0x1, OSX = 0x2, Linux = 0x4 } private void ValidateNativeLibraryResolutions( string fileNamePattern, string lookupNamePattern, OS resolvesOnOSes) { string newDirectory = Guid.NewGuid().ToString().Substring(0, 8); string nativeLibraryPath = CreateMockFile(Path.Combine(newDirectory, string.Format(fileNamePattern, "NativeLibrary"))); ValidateNativeLibraryResolutions( Path.GetDirectoryName(nativeLibraryPath), nativeLibraryPath, string.Format(lookupNamePattern, "NativeLibrary"), resolvesOnOSes); } private void ValidateNativeLibraryWithRelativeLookupResolutions( string fileNamePattern, string lookupNamePattern, OS resolvesOnOSes) { string newDirectory = Guid.NewGuid().ToString().Substring(0, 8); string nativeLibraryPath = CreateMockFile(Path.Combine(newDirectory, string.Format(fileNamePattern, "NativeLibrary"))); ValidateNativeLibraryResolutions( Path.GetDirectoryName(Path.GetDirectoryName(nativeLibraryPath)), nativeLibraryPath, Path.Combine(newDirectory, string.Format(lookupNamePattern, "NativeLibrary")), resolvesOnOSes); } private void ValidateFullPathNativeLibraryResolutions( string fileNamePattern, string lookupNamePattern, OS resolvesOnOSes) { string newDirectory = Guid.NewGuid().ToString().Substring(0, 8); string nativeLibraryPath = CreateMockFile(Path.Combine(newDirectory, string.Format(fileNamePattern, "NativeLibrary"))); ValidateNativeLibraryResolutions( Path.GetDirectoryName(nativeLibraryPath), nativeLibraryPath, Path.Combine(Path.GetDirectoryName(nativeLibraryPath), string.Format(lookupNamePattern, "NativeLibrary")), resolvesOnOSes); } private void ValidateNativeLibraryResolutionsWithTwoFiles( string fileNameToResolvePattern, string otherFileNamePattern, string lookupNamePattern, OS resolvesOnOSes) { string newDirectory = Guid.NewGuid().ToString().Substring(0, 8); string nativeLibraryPath = CreateMockFile(Path.Combine(newDirectory, string.Format(fileNameToResolvePattern, "NativeLibrary"))); CreateMockFile(Path.Combine(newDirectory, string.Format(otherFileNamePattern, "NativeLibrary"))); ValidateNativeLibraryResolutions( Path.GetDirectoryName(nativeLibraryPath), nativeLibraryPath, string.Format(lookupNamePattern, "NativeLibrary"), resolvesOnOSes); } private void ValidateNativeLibraryResolutions( string nativeLibraryPaths, string expectedResolvedFilePath, string lookupName, OS resolvesOnOSes) { using (HostPolicyMock.Mock_corehost_resolve_component_dependencies( 0, "", $"{nativeLibraryPaths}", "")) { AssemblyDependencyResolver resolver = new AssemblyDependencyResolver( Path.Combine(TestBasePath, _componentAssemblyPath)); string result = resolver.ResolveUnmanagedDllToPath(lookupName); if (OperatingSystem.IsWindows()) { if (resolvesOnOSes.HasFlag(OS.Windows)) { Assert.Equal(expectedResolvedFilePath, result); } else { Assert.Null(result); } } else if (OperatingSystem.IsMacOS()) { if (resolvesOnOSes.HasFlag(OS.OSX)) { Assert.Equal(expectedResolvedFilePath, result); } else { Assert.Null(result); } } else { if (resolvesOnOSes.HasFlag(OS.Linux)) { Assert.Equal(expectedResolvedFilePath, result); } else { Assert.Null(result); } } } } private string CreateMockFile(string relativePath) { string fullPath = Path.Combine(_componentDirectory, relativePath); if (!File.Exists(fullPath)) { string directory = Path.GetDirectoryName(fullPath); if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } File.WriteAllText(fullPath, "Mock file"); } return fullPath; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.IO; using System.Runtime.InteropServices; using System.Runtime.Loader; using TestLibrary; using Xunit; namespace AssemblyDependencyResolverTests { class NativeDependencyTests : TestBase { string _componentDirectory; string _componentAssemblyPath; protected override void Initialize() { HostPolicyMock.Initialize(TestBasePath, CoreRoot); _componentDirectory = Path.Combine(TestBasePath, $"TestComponent_{Guid.NewGuid().ToString().Substring(0, 8)}"); Directory.CreateDirectory(_componentDirectory); _componentAssemblyPath = CreateMockFile("TestComponent.dll"); } protected override void Cleanup() { if (Directory.Exists(_componentDirectory)) { Directory.Delete(_componentDirectory, recursive: true); } } public void TestSimpleNameAndNoPrefixAndNoSuffix() { ValidateNativeLibraryResolutions("{0}", "{0}", OS.Windows | OS.OSX | OS.Linux); } public void TestSimpleNameAndNoPrefixAndSuffix() { ValidateNativeLibraryResolutions("{0}.dll", "{0}", OS.Windows); ValidateNativeLibraryResolutions("{0}.dylib", "{0}", OS.OSX); ValidateNativeLibraryResolutions("{0}.so", "{0}", OS.Linux); } public void TestSimpleNameAndLibPrefixAndNoSuffix() { ValidateNativeLibraryResolutions("lib{0}", "{0}", OS.OSX | OS.Linux); } public void TestRelativeNameAndLibPrefixAndNoSuffix() { // The lib prefix is not added if the lookup is a relative path. ValidateNativeLibraryWithRelativeLookupResolutions("lib{0}", "{0}", 0); } public void TestSimpleNameAndLibPrefixAndSuffix() { ValidateNativeLibraryResolutions("lib{0}.dll", "{0}", 0); ValidateNativeLibraryResolutions("lib{0}.dylib", "{0}", OS.OSX); ValidateNativeLibraryResolutions("lib{0}.so", "{0}", OS.Linux); } public void TestNameWithSuffixAndNoPrefixAndNoSuffix() { ValidateNativeLibraryResolutions("{0}", "{0}.dll", 0); ValidateNativeLibraryResolutions("{0}", "{0}.dylib", 0); ValidateNativeLibraryResolutions("{0}", "{0}.so", 0); } public void TestNameWithSuffixAndNoPrefixAndSuffix() { ValidateNativeLibraryResolutions("{0}.dll", "{0}.dll", OS.Windows | OS.OSX | OS.Linux); ValidateNativeLibraryResolutions("{0}.dylib", "{0}.dylib", OS.Windows | OS.OSX | OS.Linux); ValidateNativeLibraryResolutions("{0}.so", "{0}.so", OS.Windows | OS.OSX | OS.Linux); } public void TestNameWithSuffixAndNoPrefixAndDoubleSuffix() { // Unixes add the suffix even if one is already present. ValidateNativeLibraryResolutions("{0}.dll.dll", "{0}.dll", 0); ValidateNativeLibraryResolutions("{0}.dylib.dylib", "{0}.dylib", OS.OSX); ValidateNativeLibraryResolutions("{0}.so.so", "{0}.so", OS.Linux); } public void TestNameWithSuffixAndPrefixAndNoSuffix() { ValidateNativeLibraryResolutions("lib{0}", "{0}.dll", 0); ValidateNativeLibraryResolutions("lib{0}", "{0}.dylib", 0); ValidateNativeLibraryResolutions("lib{0}", "{0}.so", 0); } public void TestNameWithSuffixAndPrefixAndSuffix() { ValidateNativeLibraryResolutions("lib{0}.dll", "{0}.dll", OS.OSX | OS.Linux); ValidateNativeLibraryResolutions("lib{0}.dylib", "{0}.dylib", OS.OSX | OS.Linux); ValidateNativeLibraryResolutions("lib{0}.so", "{0}.so", OS.OSX | OS.Linux); } public void TestRelativeNameWithSuffixAndPrefixAndSuffix() { // The lib prefix is not added if the lookup is a relative path ValidateNativeLibraryWithRelativeLookupResolutions("lib{0}.dll", "{0}.dll", 0); ValidateNativeLibraryWithRelativeLookupResolutions("lib{0}.dylib", "{0}.dylib", 0); ValidateNativeLibraryWithRelativeLookupResolutions("lib{0}.so", "{0}.so", 0); } public void TestNameWithPrefixAndNoPrefixAndNoSuffix() { ValidateNativeLibraryResolutions("{0}", "lib{0}", 0); } public void TestNameWithPrefixAndPrefixAndNoSuffix() { ValidateNativeLibraryResolutions("lib{0}", "lib{0}", OS.Windows | OS.OSX | OS.Linux); } public void TestNameWithPrefixAndNoPrefixAndSuffix() { ValidateNativeLibraryResolutions("{0}.dll", "lib{0}", 0); ValidateNativeLibraryResolutions("{0}.dylib", "lib{0}", 0); ValidateNativeLibraryResolutions("{0}.so", "lib{0}", 0); } public void TestNameWithPrefixAndPrefixAndSuffix() { ValidateNativeLibraryResolutions("lib{0}.dll", "lib{0}", OS.Windows); ValidateNativeLibraryResolutions("lib{0}.dylib", "lib{0}", OS.OSX); ValidateNativeLibraryResolutions("lib{0}.so", "lib{0}", OS.Linux); } public void TestWindowsAddsSuffixEvenWithOnePresent() { ValidateNativeLibraryResolutions("{0}.ext.dll", "{0}.ext", OS.Windows); } public void TestWindowsDoesntAddSuffixWhenExectubaleIsPresent() { ValidateNativeLibraryResolutions("{0}.dll.dll", "{0}.dll", 0); ValidateNativeLibraryResolutions("{0}.dll.exe", "{0}.dll", 0); ValidateNativeLibraryResolutions("{0}.exe.dll", "{0}.exe", 0); ValidateNativeLibraryResolutions("{0}.exe.exe", "{0}.exe", 0); } private void TestLookupWithSuffixPrefersUnmodifiedSuffixOnUnixes() { ValidateNativeLibraryResolutionsWithTwoFiles("{0}.dylib", "lib{0}.dylib", "{0}.dylib", OS.OSX); ValidateNativeLibraryResolutionsWithTwoFiles("{0}.so", "lib{0}.so", "{0}.so", OS.Linux); ValidateNativeLibraryResolutionsWithTwoFiles("{0}.dylib", "{0}.dylib.dylib", "{0}.dylib", OS.OSX); ValidateNativeLibraryResolutionsWithTwoFiles("{0}.so", "{0}.so.so", "{0}.so", OS.Linux); } private void TestLookupWithoutSuffixPrefersWithSuffixOnUnixes() { ValidateNativeLibraryResolutionsWithTwoFiles("{0}.dylib", "lib{0}.dylib", "{0}", OS.OSX); ValidateNativeLibraryResolutionsWithTwoFiles("{0}.so", "lib{0}.so", "{0}", OS.Linux); ValidateNativeLibraryResolutionsWithTwoFiles("{0}.dylib", "{0}", "{0}", OS.OSX); ValidateNativeLibraryResolutionsWithTwoFiles("{0}.so", "{0}", "{0}", OS.Linux); ValidateNativeLibraryResolutionsWithTwoFiles("{0}.dylib", "lib{0}", "{0}", OS.OSX); ValidateNativeLibraryResolutionsWithTwoFiles("{0}.so", "lib{0}", "{0}", OS.Linux); } public void TestFullPathLookupWithMatchingFileName() { ValidateFullPathNativeLibraryResolutions("{0}", "{0}", OS.Windows | OS.OSX | OS.Linux); ValidateFullPathNativeLibraryResolutions("{0}.dll", "{0}.dll", OS.Windows | OS.OSX | OS.Linux); ValidateFullPathNativeLibraryResolutions("{0}.dylib", "{0}.dylib", OS.Windows | OS.OSX | OS.Linux); ValidateFullPathNativeLibraryResolutions("{0}.so", "{0}.so", OS.Windows | OS.OSX | OS.Linux); ValidateFullPathNativeLibraryResolutions("lib{0}", "lib{0}", OS.Windows | OS.OSX | OS.Linux); ValidateFullPathNativeLibraryResolutions("lib{0}.dll", "lib{0}.dll", OS.Windows | OS.OSX | OS.Linux); ValidateFullPathNativeLibraryResolutions("lib{0}.dylib", "lib{0}.dylib", OS.Windows | OS.OSX | OS.Linux); ValidateFullPathNativeLibraryResolutions("lib{0}.so", "lib{0}.so", OS.Windows | OS.OSX | OS.Linux); } public void TestFullPathLookupWithDifferentFileName() { ValidateFullPathNativeLibraryResolutions("lib{0}", "{0}", 0); ValidateFullPathNativeLibraryResolutions("{0}.dll", "{0}", 0); ValidateFullPathNativeLibraryResolutions("{0}.dylib", "{0}", 0); ValidateFullPathNativeLibraryResolutions("{0}.so", "{0}", 0); ValidateFullPathNativeLibraryResolutions("lib{0}.dll", "{0}", 0); ValidateFullPathNativeLibraryResolutions("lib{0}.dylib", "{0}", 0); ValidateFullPathNativeLibraryResolutions("lib{0}.so", "{0}", 0); ValidateFullPathNativeLibraryResolutions("lib{0}.dll", "{0}.dll", 0); ValidateFullPathNativeLibraryResolutions("lib{0}.dylib", "{0}.dylib", 0); ValidateFullPathNativeLibraryResolutions("lib{0}.so", "{0}.so", 0); } [Flags] private enum OS { Windows = 0x1, OSX = 0x2, Linux = 0x4 } private void ValidateNativeLibraryResolutions( string fileNamePattern, string lookupNamePattern, OS resolvesOnOSes) { string newDirectory = Guid.NewGuid().ToString().Substring(0, 8); string nativeLibraryPath = CreateMockFile(Path.Combine(newDirectory, string.Format(fileNamePattern, "NativeLibrary"))); ValidateNativeLibraryResolutions( Path.GetDirectoryName(nativeLibraryPath), nativeLibraryPath, string.Format(lookupNamePattern, "NativeLibrary"), resolvesOnOSes); } private void ValidateNativeLibraryWithRelativeLookupResolutions( string fileNamePattern, string lookupNamePattern, OS resolvesOnOSes) { string newDirectory = Guid.NewGuid().ToString().Substring(0, 8); string nativeLibraryPath = CreateMockFile(Path.Combine(newDirectory, string.Format(fileNamePattern, "NativeLibrary"))); ValidateNativeLibraryResolutions( Path.GetDirectoryName(Path.GetDirectoryName(nativeLibraryPath)), nativeLibraryPath, Path.Combine(newDirectory, string.Format(lookupNamePattern, "NativeLibrary")), resolvesOnOSes); } private void ValidateFullPathNativeLibraryResolutions( string fileNamePattern, string lookupNamePattern, OS resolvesOnOSes) { string newDirectory = Guid.NewGuid().ToString().Substring(0, 8); string nativeLibraryPath = CreateMockFile(Path.Combine(newDirectory, string.Format(fileNamePattern, "NativeLibrary"))); ValidateNativeLibraryResolutions( Path.GetDirectoryName(nativeLibraryPath), nativeLibraryPath, Path.Combine(Path.GetDirectoryName(nativeLibraryPath), string.Format(lookupNamePattern, "NativeLibrary")), resolvesOnOSes); } private void ValidateNativeLibraryResolutionsWithTwoFiles( string fileNameToResolvePattern, string otherFileNamePattern, string lookupNamePattern, OS resolvesOnOSes) { string newDirectory = Guid.NewGuid().ToString().Substring(0, 8); string nativeLibraryPath = CreateMockFile(Path.Combine(newDirectory, string.Format(fileNameToResolvePattern, "NativeLibrary"))); CreateMockFile(Path.Combine(newDirectory, string.Format(otherFileNamePattern, "NativeLibrary"))); ValidateNativeLibraryResolutions( Path.GetDirectoryName(nativeLibraryPath), nativeLibraryPath, string.Format(lookupNamePattern, "NativeLibrary"), resolvesOnOSes); } private void ValidateNativeLibraryResolutions( string nativeLibraryPaths, string expectedResolvedFilePath, string lookupName, OS resolvesOnOSes) { using (HostPolicyMock.Mock_corehost_resolve_component_dependencies( 0, "", $"{nativeLibraryPaths}", "")) { AssemblyDependencyResolver resolver = new AssemblyDependencyResolver( Path.Combine(TestBasePath, _componentAssemblyPath)); string result = resolver.ResolveUnmanagedDllToPath(lookupName); if (OperatingSystem.IsWindows()) { if (resolvesOnOSes.HasFlag(OS.Windows)) { Assert.Equal(expectedResolvedFilePath, result); } else { Assert.Null(result); } } else if (OperatingSystem.IsMacOS()) { if (resolvesOnOSes.HasFlag(OS.OSX)) { Assert.Equal(expectedResolvedFilePath, result); } else { Assert.Null(result); } } else { if (resolvesOnOSes.HasFlag(OS.Linux)) { Assert.Equal(expectedResolvedFilePath, result); } else { Assert.Null(result); } } } } private string CreateMockFile(string relativePath) { string fullPath = Path.Combine(_componentDirectory, relativePath); if (!File.Exists(fullPath)) { string directory = Path.GetDirectoryName(fullPath); if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } File.WriteAllText(fullPath, "Mock file"); } return fullPath; } } }
-1
dotnet/runtime
66,474
Update repo CMake configuration to target /W4 by default
Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
AaronRobinsonMSFT
2022-03-10T20:20:31Z
2022-03-11T04:59:21Z
ba5207b0f4054fe8963fc3e87c2bd32907516961
5ce2b9f860f7a84c3059650bb67817d59d8f4953
Update repo CMake configuration to target /W4 by default. Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
./src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/ConstantExpression.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Dynamic.Utils; namespace System.Linq.Expressions { /// <summary> /// Represents an expression that has a constant value. /// </summary> [DebuggerTypeProxy(typeof(ConstantExpressionProxy))] public class ConstantExpression : Expression { internal ConstantExpression(object? value) { Value = value; } /// <summary> /// Gets the static type of the expression that this <see cref="Expression"/> represents. /// </summary> /// <returns>The <see cref="System.Type"/> that represents the static type of the expression.</returns> public override Type Type { get { if (Value == null) { return typeof(object); } return Value.GetType(); } } /// <summary> /// Returns the node type of this Expression. Extension nodes should return /// ExpressionType.Extension when overriding this method. /// </summary> /// <returns>The <see cref="ExpressionType"/> of the expression.</returns> public sealed override ExpressionType NodeType => ExpressionType.Constant; /// <summary> /// Gets the value of the constant expression. /// </summary> public object? Value { get; } /// <summary> /// Dispatches to the specific visit method for this node type. /// </summary> protected internal override Expression Accept(ExpressionVisitor visitor) { return visitor.VisitConstant(this); } } internal sealed class TypedConstantExpression : ConstantExpression { internal TypedConstantExpression(object? value, Type type) : base(value) { Type = type; } public sealed override Type Type { get; } } public partial class Expression { /// <summary> /// Creates a <see cref="ConstantExpression"/> that has the <see cref="ConstantExpression.Value"/> property set to the specified value. . /// </summary> /// <param name="value">An <see cref="object"/> to set the <see cref="ConstantExpression.Value"/> property equal to.</param> /// <returns> /// A <see cref="ConstantExpression"/> that has the <see cref="NodeType"/> property equal to /// <see cref="ExpressionType.Constant"/> and the <see cref="ConstantExpression.Value"/> property set to the specified value. /// </returns> public static ConstantExpression Constant(object? value) { return new ConstantExpression(value); } /// <summary> /// Creates a <see cref="ConstantExpression"/> that has the <see cref="ConstantExpression.Value"/> /// and <see cref="ConstantExpression.Type"/> properties set to the specified values. . /// </summary> /// <param name="value">An <see cref="object"/> to set the <see cref="ConstantExpression.Value"/> property equal to.</param> /// <param name="type">A <see cref="Type"/> to set the <see cref="Type"/> property equal to.</param> /// <returns> /// A <see cref="ConstantExpression"/> that has the <see cref="NodeType"/> property equal to /// <see cref="ExpressionType.Constant"/> and the <see cref="ConstantExpression.Value"/> and /// <see cref="Type"/> properties set to the specified values. /// </returns> public static ConstantExpression Constant(object? value, Type type) { ContractUtils.RequiresNotNull(type, nameof(type)); TypeUtils.ValidateType(type, nameof(type)); if (value == null) { if (type == typeof(object)) { return new ConstantExpression(null); } if (!type.IsValueType || type.IsNullableType()) { return new TypedConstantExpression(null, type); } } else { Type valueType = value.GetType(); if (type == valueType) { return new ConstantExpression(value); } if (type.IsAssignableFrom(valueType)) { return new TypedConstantExpression(value, type); } } throw Error.ArgumentTypesMustMatch(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Dynamic.Utils; namespace System.Linq.Expressions { /// <summary> /// Represents an expression that has a constant value. /// </summary> [DebuggerTypeProxy(typeof(ConstantExpressionProxy))] public class ConstantExpression : Expression { internal ConstantExpression(object? value) { Value = value; } /// <summary> /// Gets the static type of the expression that this <see cref="Expression"/> represents. /// </summary> /// <returns>The <see cref="System.Type"/> that represents the static type of the expression.</returns> public override Type Type { get { if (Value == null) { return typeof(object); } return Value.GetType(); } } /// <summary> /// Returns the node type of this Expression. Extension nodes should return /// ExpressionType.Extension when overriding this method. /// </summary> /// <returns>The <see cref="ExpressionType"/> of the expression.</returns> public sealed override ExpressionType NodeType => ExpressionType.Constant; /// <summary> /// Gets the value of the constant expression. /// </summary> public object? Value { get; } /// <summary> /// Dispatches to the specific visit method for this node type. /// </summary> protected internal override Expression Accept(ExpressionVisitor visitor) { return visitor.VisitConstant(this); } } internal sealed class TypedConstantExpression : ConstantExpression { internal TypedConstantExpression(object? value, Type type) : base(value) { Type = type; } public sealed override Type Type { get; } } public partial class Expression { /// <summary> /// Creates a <see cref="ConstantExpression"/> that has the <see cref="ConstantExpression.Value"/> property set to the specified value. . /// </summary> /// <param name="value">An <see cref="object"/> to set the <see cref="ConstantExpression.Value"/> property equal to.</param> /// <returns> /// A <see cref="ConstantExpression"/> that has the <see cref="NodeType"/> property equal to /// <see cref="ExpressionType.Constant"/> and the <see cref="ConstantExpression.Value"/> property set to the specified value. /// </returns> public static ConstantExpression Constant(object? value) { return new ConstantExpression(value); } /// <summary> /// Creates a <see cref="ConstantExpression"/> that has the <see cref="ConstantExpression.Value"/> /// and <see cref="ConstantExpression.Type"/> properties set to the specified values. . /// </summary> /// <param name="value">An <see cref="object"/> to set the <see cref="ConstantExpression.Value"/> property equal to.</param> /// <param name="type">A <see cref="Type"/> to set the <see cref="Type"/> property equal to.</param> /// <returns> /// A <see cref="ConstantExpression"/> that has the <see cref="NodeType"/> property equal to /// <see cref="ExpressionType.Constant"/> and the <see cref="ConstantExpression.Value"/> and /// <see cref="Type"/> properties set to the specified values. /// </returns> public static ConstantExpression Constant(object? value, Type type) { ContractUtils.RequiresNotNull(type, nameof(type)); TypeUtils.ValidateType(type, nameof(type)); if (value == null) { if (type == typeof(object)) { return new ConstantExpression(null); } if (!type.IsValueType || type.IsNullableType()) { return new TypedConstantExpression(null, type); } } else { Type valueType = value.GetType(); if (type == valueType) { return new ConstantExpression(value); } if (type.IsAssignableFrom(valueType)) { return new TypedConstantExpression(value, type); } } throw Error.ArgumentTypesMustMatch(); } } }
-1
dotnet/runtime
66,474
Update repo CMake configuration to target /W4 by default
Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
AaronRobinsonMSFT
2022-03-10T20:20:31Z
2022-03-11T04:59:21Z
ba5207b0f4054fe8963fc3e87c2bd32907516961
5ce2b9f860f7a84c3059650bb67817d59d8f4953
Update repo CMake configuration to target /W4 by default. Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
./src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonNode/JsonNodeOperatorTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; namespace System.Text.Json.Nodes.Tests { public static class OperatorTests { private const string ExpectedPrimitiveJson = @"{" + @"""MyInt16"":1," + @"""MyInt32"":2," + @"""MyInt64"":3," + @"""MyUInt16"":4," + @"""MyUInt32"":5," + @"""MyUInt64"":6," + @"""MyByte"":7," + @"""MySByte"":8," + @"""MyChar"":""a""," + @"""MyString"":""Hello""," + @"""MyBooleanTrue"":true," + @"""MyBooleanFalse"":false," + @"""MySingle"":1.1," + @"""MyDouble"":2.2," + @"""MyDecimal"":3.3," + @"""MyDateTime"":""2019-01-30T12:01:02Z""," + @"""MyDateTimeOffset"":""2019-01-30T12:01:02+01:00""," + @"""MyGuid"":""1b33498a-7b7d-4dda-9c13-f6aa4ab449a6""" + // note lowercase @"}"; [Fact] public static void ImplicitOperators_FromProperties() { var jObject = new JsonObject(); jObject["MyInt16"] = (short)1; jObject["MyInt32"] = 2; jObject["MyInt64"] = (long)3; jObject["MyUInt16"] = (ushort)4; jObject["MyUInt32"] = (uint)5; jObject["MyUInt64"] = (ulong)6; jObject["MyByte"] = (byte)7; jObject["MySByte"] = (sbyte)8; jObject["MyChar"] = 'a'; jObject["MyString"] = "Hello"; jObject["MyBooleanTrue"] = true; jObject["MyBooleanFalse"] = false; jObject["MySingle"] = 1.1f; jObject["MyDouble"] = 2.2d; jObject["MyDecimal"] = 3.3m; jObject["MyDateTime"] = new DateTime(2019, 1, 30, 12, 1, 2, DateTimeKind.Utc); jObject["MyDateTimeOffset"] = new DateTimeOffset(2019, 1, 30, 12, 1, 2, new TimeSpan(1, 0, 0)); jObject["MyGuid"] = new Guid("1B33498A-7B7D-4DDA-9C13-F6AA4AB449A6"); string expected = ExpectedPrimitiveJson; string json = jObject.ToJsonString(); // Adjust for non-Core frameworks which do not have round-trippable floating point strings. json = json.Replace("1.10000002", "1.1").Replace("2.2000000000000002", "2.2"); Assert.Equal(expected, json); } [Fact] public static void ExplicitOperators_FromProperties() { JsonObject jObject = JsonNode.Parse(ExpectedPrimitiveJson).AsObject(); Assert.Equal(1, (short)jObject["MyInt16"]); Assert.Equal(2, (int)jObject["MyInt32"]); Assert.Equal(3, (long)jObject["MyInt64"]); Assert.Equal(4, (ushort)jObject["MyUInt16"]); Assert.Equal<uint>(5, (uint)jObject["MyUInt32"]); Assert.Equal<ulong>(6, (ulong)jObject["MyUInt64"]); Assert.Equal(7, (byte)jObject["MyByte"]); Assert.Equal(8, (sbyte)jObject["MySByte"]); Assert.Equal('a', (char)jObject["MyChar"]); Assert.Equal("Hello", (string)jObject["MyString"]); Assert.True((bool)jObject["MyBooleanTrue"]); Assert.False((bool)jObject["MyBooleanFalse"]); Assert.Equal(1.1f, (float)jObject["MySingle"]); Assert.Equal(2.2d, (double)jObject["MyDouble"]); Assert.Equal(3.3m, (decimal)jObject["MyDecimal"]); Assert.Equal(new DateTime(2019, 1, 30, 12, 1, 2, DateTimeKind.Utc), (DateTime)jObject["MyDateTime"]); Assert.Equal(new DateTimeOffset(2019, 1, 30, 12, 1, 2, new TimeSpan(1, 0, 0)), (DateTimeOffset)jObject["MyDateTimeOffset"]); Assert.Equal(new Guid("1B33498A-7B7D-4DDA-9C13-F6AA4AB449A6"), (Guid)jObject["MyGuid"]); } [Fact] public static void ExplicitOperators_FromValues() { Assert.Equal(1, (short)(JsonNode)(short)1); Assert.Equal(2, (int)(JsonNode)2); Assert.Equal(3, (long)(JsonNode)(long)3); Assert.Equal(4, (ushort)(JsonNode)(ushort)4); Assert.Equal<uint>(5, (uint)(JsonNode)(uint)5); Assert.Equal<ulong>(6, (ulong)(JsonNode)(ulong)6); Assert.Equal(7, (byte)(JsonNode)(byte)7); Assert.Equal(8, (sbyte)(JsonNode)(sbyte)8); Assert.Equal('a', (char)(JsonNode)'a'); Assert.Equal("Hello", (string)(JsonNode)"Hello"); Assert.True((bool)(JsonNode)true); Assert.False((bool)(JsonNode)false); Assert.Equal(1.1f, (float)(JsonNode)1.1f); Assert.Equal(2.2d, (double)(JsonNode)2.2d); Assert.Equal(3.3m, (decimal)(JsonNode)3.3m); Assert.Equal(new DateTime(2019, 1, 30, 12, 1, 2, DateTimeKind.Utc), (DateTime)(JsonNode)new DateTime(2019, 1, 30, 12, 1, 2, DateTimeKind.Utc)); Assert.Equal(new DateTimeOffset(2019, 1, 30, 12, 1, 2, new TimeSpan(1, 0, 0)), (DateTimeOffset)(JsonNode)new DateTimeOffset(2019, 1, 30, 12, 1, 2, new TimeSpan(1, 0, 0))); Assert.Equal(new Guid("1B33498A-7B7D-4DDA-9C13-F6AA4AB449A6"), (Guid)(JsonNode)new Guid("1B33498A-7B7D-4DDA-9C13-F6AA4AB449A6")); } [Fact] public static void ExplicitOperators_FromNullValues() { Assert.Null((byte?)(JsonValue)null); Assert.Null((short?)(JsonValue)null); Assert.Null((int?)(JsonValue)null); Assert.Null((long?)(JsonValue)null); Assert.Null((sbyte?)(JsonValue)null); Assert.Null((ushort?)(JsonValue)null); Assert.Null((uint?)(JsonValue)null); Assert.Null((ulong?)(JsonValue)null); Assert.Null((char?)(JsonValue)null); Assert.Null((string)(JsonValue)null); Assert.Null((bool?)(JsonValue)null); Assert.Null((float?)(JsonValue)null); Assert.Null((double?)(JsonValue)null); Assert.Null((decimal?)(JsonValue)null); Assert.Null((DateTime?)(JsonValue)null); Assert.Null((DateTimeOffset?)(JsonValue)null); Assert.Null((Guid?)(JsonValue)null); } [Fact] public static void ExplicitOperators_FromNullableValues() { Assert.NotNull((byte?)(JsonValue)(byte)42); Assert.NotNull((short?)(JsonValue)(short)42); Assert.NotNull((int?)(JsonValue)42); Assert.NotNull((long?)(JsonValue)(long)42); Assert.NotNull((sbyte?)(JsonValue)(sbyte)42); Assert.NotNull((ushort?)(JsonValue)(ushort)42); Assert.NotNull((uint?)(JsonValue)(uint)42); Assert.NotNull((ulong?)(JsonValue)(ulong)42); Assert.NotNull((char?)(JsonValue)'a'); Assert.NotNull((string)(JsonValue)""); Assert.NotNull((bool?)(JsonValue)true); Assert.NotNull((float?)(JsonValue)(float)42); Assert.NotNull((double?)(JsonValue)(double)42); Assert.NotNull((decimal?)(JsonValue)(decimal)42); Assert.NotNull((DateTime?)(JsonValue)new DateTime(2019, 1, 30, 12, 1, 2, DateTimeKind.Utc)); Assert.NotNull((DateTimeOffset?)(JsonValue)new DateTimeOffset(2019, 1, 30, 12, 1, 2, new TimeSpan(1, 0, 0))); Assert.NotNull((Guid?)(JsonValue)new Guid("1B33498A-7B7D-4DDA-9C13-F6AA4AB449A6")); } [Fact] public static void ImplicitOperators_FromNullValues() { Assert.Null((JsonValue?)(byte?)null); Assert.Null((JsonValue?)(short?)null); Assert.Null((JsonValue?)(int?)null); Assert.Null((JsonValue?)(long?)null); Assert.Null((JsonValue?)(sbyte?)null); Assert.Null((JsonValue?)(ushort?)null); Assert.Null((JsonValue?)(uint?)null); Assert.Null((JsonValue?)(ulong?)null); Assert.Null((JsonValue?)(char?)null); Assert.Null((JsonValue?)(string)null); Assert.Null((JsonValue?)(bool?)null); Assert.Null((JsonValue?)(float?)null); Assert.Null((JsonValue?)(double?)null); Assert.Null((JsonValue?)(decimal?)null); Assert.Null((JsonValue?)(DateTime?)null); Assert.Null((JsonValue?)(DateTimeOffset?)null); Assert.Null((JsonValue?)(Guid?)null); } [Fact] public static void ImplicitOperators_FromNullableValues() { #pragma warning disable xUnit2002 Assert.NotNull((JsonValue?)(byte?)42); Assert.NotNull((JsonValue?)(short?)42); Assert.NotNull((JsonValue?)(int?)42); Assert.NotNull((JsonValue?)(long?)42); Assert.NotNull((JsonValue?)(sbyte?)42); Assert.NotNull((JsonValue?)(ushort?)42); Assert.NotNull((JsonValue?)(uint?)42); Assert.NotNull((JsonValue?)(ulong?)42); Assert.NotNull((JsonValue?)(char?)'a'); Assert.NotNull((JsonValue?)(bool?)true); Assert.NotNull((JsonValue?)(float?)42); Assert.NotNull((JsonValue?)(double?)42); Assert.NotNull((JsonValue?)(decimal?)42); #pragma warning restore xUnit2002 Assert.NotNull((JsonValue?)(DateTime?)new DateTime(2019, 1, 30, 12, 1, 2, DateTimeKind.Utc)); Assert.NotNull((JsonValue?)(DateTimeOffset?)new DateTimeOffset(2019, 1, 30, 12, 1, 2, new TimeSpan(1, 0, 0))); Assert.NotNull((JsonValue?)(Guid?)new Guid("1B33498A-7B7D-4DDA-9C13-F6AA4AB449A6")); } [Fact] public static void CastsNotSupported() { // Since generics and boxing do not support casts, we get InvalidCastExceptions here. InvalidOperationException ex = Assert.Throws<InvalidOperationException>(() => (byte)(JsonNode)(long)3); // narrowing // "A value of type 'System.Int64' cannot be converted to a 'System.Byte'." Assert.Contains(typeof(long).ToString(), ex.Message); Assert.Contains(typeof(byte).ToString(), ex.Message); ex = Assert.Throws<InvalidOperationException>(() => (long)(JsonNode)(byte)3); // widening // "A value of type 'System.Byte' cannot be converted to a 'System.Int64'." Assert.Contains(typeof(byte).ToString(), ex.Message); Assert.Contains(typeof(long).ToString(), ex.Message); } [Fact] public static void Boxing() { var node = JsonValue.Create(42); Assert.Equal(42, node.GetValue<int>()); Assert.Equal<object>(42, node.GetValue<object>()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; namespace System.Text.Json.Nodes.Tests { public static class OperatorTests { private const string ExpectedPrimitiveJson = @"{" + @"""MyInt16"":1," + @"""MyInt32"":2," + @"""MyInt64"":3," + @"""MyUInt16"":4," + @"""MyUInt32"":5," + @"""MyUInt64"":6," + @"""MyByte"":7," + @"""MySByte"":8," + @"""MyChar"":""a""," + @"""MyString"":""Hello""," + @"""MyBooleanTrue"":true," + @"""MyBooleanFalse"":false," + @"""MySingle"":1.1," + @"""MyDouble"":2.2," + @"""MyDecimal"":3.3," + @"""MyDateTime"":""2019-01-30T12:01:02Z""," + @"""MyDateTimeOffset"":""2019-01-30T12:01:02+01:00""," + @"""MyGuid"":""1b33498a-7b7d-4dda-9c13-f6aa4ab449a6""" + // note lowercase @"}"; [Fact] public static void ImplicitOperators_FromProperties() { var jObject = new JsonObject(); jObject["MyInt16"] = (short)1; jObject["MyInt32"] = 2; jObject["MyInt64"] = (long)3; jObject["MyUInt16"] = (ushort)4; jObject["MyUInt32"] = (uint)5; jObject["MyUInt64"] = (ulong)6; jObject["MyByte"] = (byte)7; jObject["MySByte"] = (sbyte)8; jObject["MyChar"] = 'a'; jObject["MyString"] = "Hello"; jObject["MyBooleanTrue"] = true; jObject["MyBooleanFalse"] = false; jObject["MySingle"] = 1.1f; jObject["MyDouble"] = 2.2d; jObject["MyDecimal"] = 3.3m; jObject["MyDateTime"] = new DateTime(2019, 1, 30, 12, 1, 2, DateTimeKind.Utc); jObject["MyDateTimeOffset"] = new DateTimeOffset(2019, 1, 30, 12, 1, 2, new TimeSpan(1, 0, 0)); jObject["MyGuid"] = new Guid("1B33498A-7B7D-4DDA-9C13-F6AA4AB449A6"); string expected = ExpectedPrimitiveJson; string json = jObject.ToJsonString(); // Adjust for non-Core frameworks which do not have round-trippable floating point strings. json = json.Replace("1.10000002", "1.1").Replace("2.2000000000000002", "2.2"); Assert.Equal(expected, json); } [Fact] public static void ExplicitOperators_FromProperties() { JsonObject jObject = JsonNode.Parse(ExpectedPrimitiveJson).AsObject(); Assert.Equal(1, (short)jObject["MyInt16"]); Assert.Equal(2, (int)jObject["MyInt32"]); Assert.Equal(3, (long)jObject["MyInt64"]); Assert.Equal(4, (ushort)jObject["MyUInt16"]); Assert.Equal<uint>(5, (uint)jObject["MyUInt32"]); Assert.Equal<ulong>(6, (ulong)jObject["MyUInt64"]); Assert.Equal(7, (byte)jObject["MyByte"]); Assert.Equal(8, (sbyte)jObject["MySByte"]); Assert.Equal('a', (char)jObject["MyChar"]); Assert.Equal("Hello", (string)jObject["MyString"]); Assert.True((bool)jObject["MyBooleanTrue"]); Assert.False((bool)jObject["MyBooleanFalse"]); Assert.Equal(1.1f, (float)jObject["MySingle"]); Assert.Equal(2.2d, (double)jObject["MyDouble"]); Assert.Equal(3.3m, (decimal)jObject["MyDecimal"]); Assert.Equal(new DateTime(2019, 1, 30, 12, 1, 2, DateTimeKind.Utc), (DateTime)jObject["MyDateTime"]); Assert.Equal(new DateTimeOffset(2019, 1, 30, 12, 1, 2, new TimeSpan(1, 0, 0)), (DateTimeOffset)jObject["MyDateTimeOffset"]); Assert.Equal(new Guid("1B33498A-7B7D-4DDA-9C13-F6AA4AB449A6"), (Guid)jObject["MyGuid"]); } [Fact] public static void ExplicitOperators_FromValues() { Assert.Equal(1, (short)(JsonNode)(short)1); Assert.Equal(2, (int)(JsonNode)2); Assert.Equal(3, (long)(JsonNode)(long)3); Assert.Equal(4, (ushort)(JsonNode)(ushort)4); Assert.Equal<uint>(5, (uint)(JsonNode)(uint)5); Assert.Equal<ulong>(6, (ulong)(JsonNode)(ulong)6); Assert.Equal(7, (byte)(JsonNode)(byte)7); Assert.Equal(8, (sbyte)(JsonNode)(sbyte)8); Assert.Equal('a', (char)(JsonNode)'a'); Assert.Equal("Hello", (string)(JsonNode)"Hello"); Assert.True((bool)(JsonNode)true); Assert.False((bool)(JsonNode)false); Assert.Equal(1.1f, (float)(JsonNode)1.1f); Assert.Equal(2.2d, (double)(JsonNode)2.2d); Assert.Equal(3.3m, (decimal)(JsonNode)3.3m); Assert.Equal(new DateTime(2019, 1, 30, 12, 1, 2, DateTimeKind.Utc), (DateTime)(JsonNode)new DateTime(2019, 1, 30, 12, 1, 2, DateTimeKind.Utc)); Assert.Equal(new DateTimeOffset(2019, 1, 30, 12, 1, 2, new TimeSpan(1, 0, 0)), (DateTimeOffset)(JsonNode)new DateTimeOffset(2019, 1, 30, 12, 1, 2, new TimeSpan(1, 0, 0))); Assert.Equal(new Guid("1B33498A-7B7D-4DDA-9C13-F6AA4AB449A6"), (Guid)(JsonNode)new Guid("1B33498A-7B7D-4DDA-9C13-F6AA4AB449A6")); } [Fact] public static void ExplicitOperators_FromNullValues() { Assert.Null((byte?)(JsonValue)null); Assert.Null((short?)(JsonValue)null); Assert.Null((int?)(JsonValue)null); Assert.Null((long?)(JsonValue)null); Assert.Null((sbyte?)(JsonValue)null); Assert.Null((ushort?)(JsonValue)null); Assert.Null((uint?)(JsonValue)null); Assert.Null((ulong?)(JsonValue)null); Assert.Null((char?)(JsonValue)null); Assert.Null((string)(JsonValue)null); Assert.Null((bool?)(JsonValue)null); Assert.Null((float?)(JsonValue)null); Assert.Null((double?)(JsonValue)null); Assert.Null((decimal?)(JsonValue)null); Assert.Null((DateTime?)(JsonValue)null); Assert.Null((DateTimeOffset?)(JsonValue)null); Assert.Null((Guid?)(JsonValue)null); } [Fact] public static void ExplicitOperators_FromNullableValues() { Assert.NotNull((byte?)(JsonValue)(byte)42); Assert.NotNull((short?)(JsonValue)(short)42); Assert.NotNull((int?)(JsonValue)42); Assert.NotNull((long?)(JsonValue)(long)42); Assert.NotNull((sbyte?)(JsonValue)(sbyte)42); Assert.NotNull((ushort?)(JsonValue)(ushort)42); Assert.NotNull((uint?)(JsonValue)(uint)42); Assert.NotNull((ulong?)(JsonValue)(ulong)42); Assert.NotNull((char?)(JsonValue)'a'); Assert.NotNull((string)(JsonValue)""); Assert.NotNull((bool?)(JsonValue)true); Assert.NotNull((float?)(JsonValue)(float)42); Assert.NotNull((double?)(JsonValue)(double)42); Assert.NotNull((decimal?)(JsonValue)(decimal)42); Assert.NotNull((DateTime?)(JsonValue)new DateTime(2019, 1, 30, 12, 1, 2, DateTimeKind.Utc)); Assert.NotNull((DateTimeOffset?)(JsonValue)new DateTimeOffset(2019, 1, 30, 12, 1, 2, new TimeSpan(1, 0, 0))); Assert.NotNull((Guid?)(JsonValue)new Guid("1B33498A-7B7D-4DDA-9C13-F6AA4AB449A6")); } [Fact] public static void ImplicitOperators_FromNullValues() { Assert.Null((JsonValue?)(byte?)null); Assert.Null((JsonValue?)(short?)null); Assert.Null((JsonValue?)(int?)null); Assert.Null((JsonValue?)(long?)null); Assert.Null((JsonValue?)(sbyte?)null); Assert.Null((JsonValue?)(ushort?)null); Assert.Null((JsonValue?)(uint?)null); Assert.Null((JsonValue?)(ulong?)null); Assert.Null((JsonValue?)(char?)null); Assert.Null((JsonValue?)(string)null); Assert.Null((JsonValue?)(bool?)null); Assert.Null((JsonValue?)(float?)null); Assert.Null((JsonValue?)(double?)null); Assert.Null((JsonValue?)(decimal?)null); Assert.Null((JsonValue?)(DateTime?)null); Assert.Null((JsonValue?)(DateTimeOffset?)null); Assert.Null((JsonValue?)(Guid?)null); } [Fact] public static void ImplicitOperators_FromNullableValues() { #pragma warning disable xUnit2002 Assert.NotNull((JsonValue?)(byte?)42); Assert.NotNull((JsonValue?)(short?)42); Assert.NotNull((JsonValue?)(int?)42); Assert.NotNull((JsonValue?)(long?)42); Assert.NotNull((JsonValue?)(sbyte?)42); Assert.NotNull((JsonValue?)(ushort?)42); Assert.NotNull((JsonValue?)(uint?)42); Assert.NotNull((JsonValue?)(ulong?)42); Assert.NotNull((JsonValue?)(char?)'a'); Assert.NotNull((JsonValue?)(bool?)true); Assert.NotNull((JsonValue?)(float?)42); Assert.NotNull((JsonValue?)(double?)42); Assert.NotNull((JsonValue?)(decimal?)42); #pragma warning restore xUnit2002 Assert.NotNull((JsonValue?)(DateTime?)new DateTime(2019, 1, 30, 12, 1, 2, DateTimeKind.Utc)); Assert.NotNull((JsonValue?)(DateTimeOffset?)new DateTimeOffset(2019, 1, 30, 12, 1, 2, new TimeSpan(1, 0, 0))); Assert.NotNull((JsonValue?)(Guid?)new Guid("1B33498A-7B7D-4DDA-9C13-F6AA4AB449A6")); } [Fact] public static void CastsNotSupported() { // Since generics and boxing do not support casts, we get InvalidCastExceptions here. InvalidOperationException ex = Assert.Throws<InvalidOperationException>(() => (byte)(JsonNode)(long)3); // narrowing // "A value of type 'System.Int64' cannot be converted to a 'System.Byte'." Assert.Contains(typeof(long).ToString(), ex.Message); Assert.Contains(typeof(byte).ToString(), ex.Message); ex = Assert.Throws<InvalidOperationException>(() => (long)(JsonNode)(byte)3); // widening // "A value of type 'System.Byte' cannot be converted to a 'System.Int64'." Assert.Contains(typeof(byte).ToString(), ex.Message); Assert.Contains(typeof(long).ToString(), ex.Message); } [Fact] public static void Boxing() { var node = JsonValue.Create(42); Assert.Equal(42, node.GetValue<int>()); Assert.Equal<object>(42, node.GetValue<object>()); } } }
-1
dotnet/runtime
66,474
Update repo CMake configuration to target /W4 by default
Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
AaronRobinsonMSFT
2022-03-10T20:20:31Z
2022-03-11T04:59:21Z
ba5207b0f4054fe8963fc3e87c2bd32907516961
5ce2b9f860f7a84c3059650bb67817d59d8f4953
Update repo CMake configuration to target /W4 by default. Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
./src/coreclr/pal/src/libunwind/src/hppa/Ginit_local.c
/* libunwind - a platform-independent unwind library Copyright (C) 2003 Hewlett-Packard Co Contributed by ... This file is part of libunwind. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "unwind_i.h" #include "init.h" #ifdef UNW_REMOTE_ONLY int unw_init_local (unw_cursor_t *cursor, ucontext_t *uc) { return -UNW_EINVAL; } #else /* !UNW_REMOTE_ONLY */ static int unw_init_local_common (unw_cursor_t *cursor, ucontext_t *uc, unsigned use_prev_instr) { struct cursor *c = (struct cursor *) cursor; if (!atomic_load(&tdep_init_done)) tdep_init (); Debug (1, "(cursor=%p)\n", c); c->dwarf.as = unw_local_addr_space; c->dwarf.as_arg = uc; return common_init (c, use_prev_instr); } int unw_init_local (unw_cursor_t *cursor, ucontext_t *uc) { return unw_init_local_common(cursor, uc, 1); } int unw_init_local2 (unw_cursor_t *cursor, ucontext_t *uc, int flag) { if (!flag) { return unw_init_local_common(cursor, uc, 1); } else if (flag == UNW_INIT_SIGNAL_FRAME) { return unw_init_local_common(cursor, uc, 0); } else { return -UNW_EINVAL; } } #endif /* !UNW_REMOTE_ONLY */
/* libunwind - a platform-independent unwind library Copyright (C) 2003 Hewlett-Packard Co Contributed by ... This file is part of libunwind. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "unwind_i.h" #include "init.h" #ifdef UNW_REMOTE_ONLY int unw_init_local (unw_cursor_t *cursor, ucontext_t *uc) { return -UNW_EINVAL; } #else /* !UNW_REMOTE_ONLY */ static int unw_init_local_common (unw_cursor_t *cursor, ucontext_t *uc, unsigned use_prev_instr) { struct cursor *c = (struct cursor *) cursor; if (!atomic_load(&tdep_init_done)) tdep_init (); Debug (1, "(cursor=%p)\n", c); c->dwarf.as = unw_local_addr_space; c->dwarf.as_arg = uc; return common_init (c, use_prev_instr); } int unw_init_local (unw_cursor_t *cursor, ucontext_t *uc) { return unw_init_local_common(cursor, uc, 1); } int unw_init_local2 (unw_cursor_t *cursor, ucontext_t *uc, int flag) { if (!flag) { return unw_init_local_common(cursor, uc, 1); } else if (flag == UNW_INIT_SIGNAL_FRAME) { return unw_init_local_common(cursor, uc, 0); } else { return -UNW_EINVAL; } } #endif /* !UNW_REMOTE_ONLY */
-1
dotnet/runtime
66,474
Update repo CMake configuration to target /W4 by default
Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
AaronRobinsonMSFT
2022-03-10T20:20:31Z
2022-03-11T04:59:21Z
ba5207b0f4054fe8963fc3e87c2bd32907516961
5ce2b9f860f7a84c3059650bb67817d59d8f4953
Update repo CMake configuration to target /W4 by default. Contributes to https://github.com/dotnet/runtime/issues/66154 Disable all failing warnings. The ones listed in the SDL issue above will gradually be re-enabled. /cc @elinor-fung @am11 @jkotas
./src/tests/JIT/opt/AssertionPropagation/DynBlkNullAssertions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // "cpblk/initblk" should not generate non-null assertions because the // indirections they represent may not be realized (in case the "size" // was zero). using System; using System.Runtime.CompilerServices; public class DynBlkNullAssertions { public static int Main() { if (!TestCpBlk(ref Unsafe.NullRef<byte>(), ref Unsafe.NullRef<byte>(), 0)) { return 101; } if (!TestInitBlk(ref Unsafe.NullRef<byte>(), 0, 0)) { return 102; } return 100; } [MethodImpl(MethodImplOptions.NoInlining)] private static bool TestCpBlk(ref byte dst, ref byte src, uint size) { Unsafe.CopyBlock(ref dst, ref src, size); return Unsafe.AreSame(ref dst, ref Unsafe.NullRef<byte>()); } [MethodImpl(MethodImplOptions.NoInlining)] private static bool TestInitBlk(ref byte dst, byte value, uint size) { Unsafe.InitBlock(ref dst, value, size); return Unsafe.AreSame(ref dst, ref Unsafe.NullRef<byte>()); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // "cpblk/initblk" should not generate non-null assertions because the // indirections they represent may not be realized (in case the "size" // was zero). using System; using System.Runtime.CompilerServices; public class DynBlkNullAssertions { public static int Main() { if (!TestCpBlk(ref Unsafe.NullRef<byte>(), ref Unsafe.NullRef<byte>(), 0)) { return 101; } if (!TestInitBlk(ref Unsafe.NullRef<byte>(), 0, 0)) { return 102; } return 100; } [MethodImpl(MethodImplOptions.NoInlining)] private static bool TestCpBlk(ref byte dst, ref byte src, uint size) { Unsafe.CopyBlock(ref dst, ref src, size); return Unsafe.AreSame(ref dst, ref Unsafe.NullRef<byte>()); } [MethodImpl(MethodImplOptions.NoInlining)] private static bool TestInitBlk(ref byte dst, byte value, uint size) { Unsafe.InitBlock(ref dst, value, size); return Unsafe.AreSame(ref dst, ref Unsafe.NullRef<byte>()); } }
-1
dotnet/runtime
66,462
Support using the system version of brotli
This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
omajid
2022-03-10T17:19:11Z
2022-03-23T03:49:50Z
c3e1d21c2fb30436ae24ef7ef4f458e3270bb7e3
5ca9223639700750ff12bb1fed9fa6e397062b78
Support using the system version of brotli . This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
./src/native/external/brotli.cmake
include_directories("${CMAKE_CURRENT_LIST_DIR}/brotli/include") set (BROTLI_SOURCES_BASE common/constants.c common/context.c common/dictionary.c common/platform.c common/transform.c dec/bit_reader.c dec/decode.c dec/huffman.c dec/state.c enc/backward_references.c enc/backward_references_hq.c enc/bit_cost.c enc/block_splitter.c enc/brotli_bit_stream.c enc/cluster.c enc/command.c enc/compress_fragment.c enc/compress_fragment_two_pass.c enc/dictionary_hash.c enc/encode.c enc/encoder_dict.c enc/entropy_encode.c enc/fast_log.c enc/histogram.c enc/literal_cost.c enc/memory.c enc/metablock.c enc/static_dict.c enc/utf8_util.c ) addprefix(BROTLI_SOURCES "${CMAKE_CURRENT_LIST_DIR}/brotli" "${BROTLI_SOURCES_BASE}")
include_directories(BEFORE "${CMAKE_CURRENT_LIST_DIR}/brotli/include") set (BROTLI_SOURCES_BASE common/constants.c common/context.c common/dictionary.c common/platform.c common/transform.c dec/bit_reader.c dec/decode.c dec/huffman.c dec/state.c enc/backward_references.c enc/backward_references_hq.c enc/bit_cost.c enc/block_splitter.c enc/brotli_bit_stream.c enc/cluster.c enc/command.c enc/compress_fragment.c enc/compress_fragment_two_pass.c enc/dictionary_hash.c enc/encode.c enc/encoder_dict.c enc/entropy_encode.c enc/fast_log.c enc/histogram.c enc/literal_cost.c enc/memory.c enc/metablock.c enc/static_dict.c enc/utf8_util.c ) addprefix(BROTLI_SOURCES "${CMAKE_CURRENT_LIST_DIR}/brotli" "${BROTLI_SOURCES_BASE}")
1
dotnet/runtime
66,462
Support using the system version of brotli
This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
omajid
2022-03-10T17:19:11Z
2022-03-23T03:49:50Z
c3e1d21c2fb30436ae24ef7ef4f458e3270bb7e3
5ca9223639700750ff12bb1fed9fa6e397062b78
Support using the system version of brotli . This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
./src/native/libs/System.IO.Compression.Native/CMakeLists.txt
project(System.IO.Compression.Native C) include(${CMAKE_CURRENT_LIST_DIR}/extra_libs.cmake) set(NATIVECOMPRESSION_SOURCES pal_zlib.c ) if (NOT CLR_CMAKE_TARGET_BROWSER) include(${CLR_SRC_NATIVE_DIR}/external/brotli.cmake) set (NATIVECOMPRESSION_SOURCES ${NATIVECOMPRESSION_SOURCES} ${BROTLI_SOURCES} entrypoints.c ) endif () if (CLR_CMAKE_TARGET_UNIX OR CLR_CMAKE_TARGET_BROWSER) set(NATIVE_LIBS_EXTRA) append_extra_compression_libs(NATIVE_LIBS_EXTRA) if (CLR_CMAKE_TARGET_BROWSER) include(${CLR_SRC_NATIVE_DIR}/external/zlib.cmake) add_definitions(-DINTERNAL_ZLIB) set(NATIVECOMPRESSION_SOURCES ${ZLIB_SOURCES} ${NATIVECOMPRESSION_SOURCES}) endif() # Disable implicit fallthrough warning for Brotli set(FLAGS -Wno-implicit-fallthrough) # Delete this supression once brotli is upgraded to vNext (current latest v1.0.9 # does not contain upstream fix: https://github.com/google/brotli/commit/0a3944c) set(FLAGS "${FLAGS} -Wno-vla-parameter") set_source_files_properties(${NATIVECOMPRESSION_SOURCES} PROPERTIES COMPILE_FLAGS ${FLAGS}) if (GEN_SHARED_LIB) add_definitions(-DBROTLI_SHARED_COMPILATION) add_library(System.IO.Compression.Native SHARED ${NATIVECOMPRESSION_SOURCES} ${VERSION_FILE_PATH} ) target_link_libraries(System.IO.Compression.Native ${NATIVE_LIBS_EXTRA} ) if (NOT CLR_CMAKE_TARGET_MACCATALYST AND NOT CLR_CMAKE_TARGET_IOS AND NOT CLR_CMAKE_TARGET_TVOS AND NOT CLR_CMAKE_TARGET_ANDROID) set(DEF_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/System.IO.Compression.Native_unixexports.src) set(EXPORTS_FILE ${CMAKE_CURRENT_BINARY_DIR}/System.IO.Compression.Native.exports) generate_exports_file(${DEF_SOURCES} ${EXPORTS_FILE}) set_exports_linker_option(${EXPORTS_FILE}) add_custom_target(System.IO.Compression.Native_exports DEPENDS ${EXPORTS_FILE}) add_dependencies(System.IO.Compression.Native System.IO.Compression.Native_exports) set_property(TARGET System.IO.Compression.Native APPEND_STRING PROPERTY LINK_FLAGS ${EXPORTS_LINKER_OPTION}) set_property(TARGET System.IO.Compression.Native APPEND_STRING PROPERTY LINK_DEPENDS ${EXPORTS_FILE}) add_custom_command(TARGET System.IO.Compression.Native POST_BUILD COMMENT "Verifying System.IO.Compression.Native entry points against entrypoints.c " COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/../verify-entrypoints.sh $<TARGET_FILE:System.IO.Compression.Native> ${CMAKE_CURRENT_SOURCE_DIR}/entrypoints.c ${CMAKE_NM} VERBATIM ) endif () install_with_stripped_symbols (System.IO.Compression.Native PROGRAMS .) endif () add_library(System.IO.Compression.Native-Static STATIC ${NATIVECOMPRESSION_SOURCES} ) set_target_properties(System.IO.Compression.Native-Static PROPERTIES OUTPUT_NAME System.IO.Compression.Native CLEAN_DIRECT_OUTPUT 1) else () if (GEN_SHARED_LIB) include (GenerateExportHeader) endif () if (CLR_CMAKE_HOST_ARCH_I386 OR CLR_CMAKE_HOST_ARCH_AMD64) include(${CLR_SRC_NATIVE_DIR}/external/zlib-intel.cmake) else () include(${CLR_SRC_NATIVE_DIR}/external/zlib.cmake) endif () add_definitions(-DINTERNAL_ZLIB) set(NATIVECOMPRESSION_SOURCES ${ZLIB_SOURCES} ${NATIVECOMPRESSION_SOURCES}) if (GEN_SHARED_LIB) add_library(System.IO.Compression.Native SHARED ${NATIVECOMPRESSION_SOURCES} System.IO.Compression.Native.def # This will add versioning to the library ${VERSION_FILE_RC_PATH} ) endif () if (NOT GEN_SHARED_LIB AND NOT CLR_CMAKE_TARGET_MACCATALYST AND NOT CLR_CMAKE_TARGET_IOS AND NOT CLR_CMAKE_TARGET_TVOS AND NOT CLR_CMAKE_TARGET_ANDROID AND NOT CLR_CMAKE_TARGET_BROWSER) set(NATIVECOMPRESSION_SOURCES ${NATIVECOMPRESSION_SOURCES} entrypoints.c) endif () add_library(System.IO.Compression.Native-Static STATIC ${NATIVECOMPRESSION_SOURCES} ) if(STATIC_LIBS_ONLY) add_library(System.IO.Compression.Native.Aot STATIC ${NATIVECOMPRESSION_SOURCES} ) target_compile_options(System.IO.Compression.Native.Aot PRIVATE /guard:cf-) target_compile_options(System.IO.Compression.Native.Aot PRIVATE /GL-) add_library(System.IO.Compression.Native.Aot.GuardCF STATIC ${NATIVECOMPRESSION_SOURCES} ) target_compile_options(System.IO.Compression.Native.Aot.GuardCF PRIVATE /GL-) endif() # Allow specification of libraries that should be linked against if (GEN_SHARED_LIB) target_link_libraries(System.IO.Compression.Native ${__LinkLibraries}) endif () target_link_libraries(System.IO.Compression.Native-Static ${__LinkLibraries}) if(STATIC_LIBS_ONLY) target_link_libraries(System.IO.Compression.Native.Aot ${__LinkLibraries}) target_link_libraries(System.IO.Compression.Native.Aot.GuardCF ${__LinkLibraries}) endif() if (GEN_SHARED_LIB) GENERATE_EXPORT_HEADER( System.IO.Compression.Native BASE_NAME System.IO.Compression.Native EXPORT_MACRO_NAME System.IO.Compression.Native_EXPORT EXPORT_FILE_NAME System.IO.Compression.Native_Export.h STATIC_DEFINE System.IO.Compression.Native_BUILT_AS_STATIC ) install (TARGETS System.IO.Compression.Native DESTINATION .) install (FILES $<TARGET_PDB_FILE:System.IO.Compression.Native> DESTINATION .) endif () if(STATIC_LIBS_ONLY) install_static_library(System.IO.Compression.Native.Aot aotsdk nativeaot) install_static_library(System.IO.Compression.Native.Aot.GuardCF aotsdk nativeaot) endif() endif () install (TARGETS System.IO.Compression.Native-Static DESTINATION ${STATIC_LIB_DESTINATION} COMPONENT libs)
project(System.IO.Compression.Native C) include(${CMAKE_CURRENT_LIST_DIR}/extra_libs.cmake) set(NATIVECOMPRESSION_SOURCES pal_zlib.c ) if (NOT CLR_CMAKE_TARGET_BROWSER) if (CLR_CMAKE_USE_SYSTEM_BROTLI) add_definitions(-DFEATURE_USE_SYSTEM_BROTLI) else () include(${CLR_SRC_NATIVE_DIR}/external/brotli.cmake) set (NATIVECOMPRESSION_SOURCES ${NATIVECOMPRESSION_SOURCES} ${BROTLI_SOURCES} ) endif () set (NATIVECOMPRESSION_SOURCES ${NATIVECOMPRESSION_SOURCES} entrypoints.c ) endif () if (CLR_CMAKE_TARGET_UNIX OR CLR_CMAKE_TARGET_BROWSER) set(NATIVE_LIBS_EXTRA) append_extra_compression_libs(NATIVE_LIBS_EXTRA) if (CLR_CMAKE_TARGET_BROWSER) include(${CLR_SRC_NATIVE_DIR}/external/zlib.cmake) add_definitions(-DINTERNAL_ZLIB) set(NATIVECOMPRESSION_SOURCES ${ZLIB_SOURCES} ${NATIVECOMPRESSION_SOURCES}) endif() # Disable implicit fallthrough warning for Brotli set(FLAGS -Wno-implicit-fallthrough) # Delete this supression once brotli is upgraded to vNext (current latest v1.0.9 # does not contain upstream fix: https://github.com/google/brotli/commit/0a3944c) set(FLAGS "${FLAGS} -Wno-vla-parameter") set_source_files_properties(${NATIVECOMPRESSION_SOURCES} PROPERTIES COMPILE_FLAGS ${FLAGS}) if (GEN_SHARED_LIB) add_definitions(-DBROTLI_SHARED_COMPILATION) add_library(System.IO.Compression.Native SHARED ${NATIVECOMPRESSION_SOURCES} ${VERSION_FILE_PATH} ) target_link_libraries(System.IO.Compression.Native ${NATIVE_LIBS_EXTRA} ) if (NOT CLR_CMAKE_TARGET_MACCATALYST AND NOT CLR_CMAKE_TARGET_IOS AND NOT CLR_CMAKE_TARGET_TVOS AND NOT CLR_CMAKE_TARGET_ANDROID) set(DEF_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/System.IO.Compression.Native_unixexports.src) set(EXPORTS_FILE ${CMAKE_CURRENT_BINARY_DIR}/System.IO.Compression.Native.exports) generate_exports_file(${DEF_SOURCES} ${EXPORTS_FILE}) set_exports_linker_option(${EXPORTS_FILE}) add_custom_target(System.IO.Compression.Native_exports DEPENDS ${EXPORTS_FILE}) add_dependencies(System.IO.Compression.Native System.IO.Compression.Native_exports) set_property(TARGET System.IO.Compression.Native APPEND_STRING PROPERTY LINK_FLAGS ${EXPORTS_LINKER_OPTION}) set_property(TARGET System.IO.Compression.Native APPEND_STRING PROPERTY LINK_DEPENDS ${EXPORTS_FILE}) if (NOT CLR_CMAKE_USE_SYSTEM_BROTLI) add_custom_command(TARGET System.IO.Compression.Native POST_BUILD COMMENT "Verifying System.IO.Compression.Native entry points against entrypoints.c " COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/../verify-entrypoints.sh $<TARGET_FILE:System.IO.Compression.Native> ${CMAKE_CURRENT_SOURCE_DIR}/entrypoints.c ${CMAKE_NM} VERBATIM ) endif () endif () install_with_stripped_symbols (System.IO.Compression.Native PROGRAMS .) endif () add_library(System.IO.Compression.Native-Static STATIC ${NATIVECOMPRESSION_SOURCES} ) set_target_properties(System.IO.Compression.Native-Static PROPERTIES OUTPUT_NAME System.IO.Compression.Native CLEAN_DIRECT_OUTPUT 1) else () if (GEN_SHARED_LIB) include (GenerateExportHeader) endif () if (CLR_CMAKE_HOST_ARCH_I386 OR CLR_CMAKE_HOST_ARCH_AMD64) include(${CLR_SRC_NATIVE_DIR}/external/zlib-intel.cmake) else () include(${CLR_SRC_NATIVE_DIR}/external/zlib.cmake) endif () add_definitions(-DINTERNAL_ZLIB) set(NATIVECOMPRESSION_SOURCES ${ZLIB_SOURCES} ${NATIVECOMPRESSION_SOURCES}) if (GEN_SHARED_LIB) add_library(System.IO.Compression.Native SHARED ${NATIVECOMPRESSION_SOURCES} System.IO.Compression.Native.def # This will add versioning to the library ${VERSION_FILE_RC_PATH} ) endif () if (NOT GEN_SHARED_LIB AND NOT CLR_CMAKE_TARGET_MACCATALYST AND NOT CLR_CMAKE_TARGET_IOS AND NOT CLR_CMAKE_TARGET_TVOS AND NOT CLR_CMAKE_TARGET_ANDROID AND NOT CLR_CMAKE_TARGET_BROWSER) set(NATIVECOMPRESSION_SOURCES ${NATIVECOMPRESSION_SOURCES} entrypoints.c) endif () add_library(System.IO.Compression.Native-Static STATIC ${NATIVECOMPRESSION_SOURCES} ) if(STATIC_LIBS_ONLY) add_library(System.IO.Compression.Native.Aot STATIC ${NATIVECOMPRESSION_SOURCES} ) target_compile_options(System.IO.Compression.Native.Aot PRIVATE /guard:cf-) target_compile_options(System.IO.Compression.Native.Aot PRIVATE /GL-) add_library(System.IO.Compression.Native.Aot.GuardCF STATIC ${NATIVECOMPRESSION_SOURCES} ) target_compile_options(System.IO.Compression.Native.Aot.GuardCF PRIVATE /GL-) endif() # Allow specification of libraries that should be linked against if (GEN_SHARED_LIB) target_link_libraries(System.IO.Compression.Native ${__LinkLibraries}) endif () target_link_libraries(System.IO.Compression.Native-Static ${__LinkLibraries}) if(STATIC_LIBS_ONLY) target_link_libraries(System.IO.Compression.Native.Aot ${__LinkLibraries}) target_link_libraries(System.IO.Compression.Native.Aot.GuardCF ${__LinkLibraries}) endif() if (GEN_SHARED_LIB) GENERATE_EXPORT_HEADER( System.IO.Compression.Native BASE_NAME System.IO.Compression.Native EXPORT_MACRO_NAME System.IO.Compression.Native_EXPORT EXPORT_FILE_NAME System.IO.Compression.Native_Export.h STATIC_DEFINE System.IO.Compression.Native_BUILT_AS_STATIC ) install (TARGETS System.IO.Compression.Native DESTINATION .) install (FILES $<TARGET_PDB_FILE:System.IO.Compression.Native> DESTINATION .) endif () if(STATIC_LIBS_ONLY) install_static_library(System.IO.Compression.Native.Aot aotsdk nativeaot) install_static_library(System.IO.Compression.Native.Aot.GuardCF aotsdk nativeaot) endif() endif () install (TARGETS System.IO.Compression.Native-Static DESTINATION ${STATIC_LIB_DESTINATION} COMPONENT libs)
1
dotnet/runtime
66,462
Support using the system version of brotli
This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
omajid
2022-03-10T17:19:11Z
2022-03-23T03:49:50Z
c3e1d21c2fb30436ae24ef7ef4f458e3270bb7e3
5ca9223639700750ff12bb1fed9fa6e397062b78
Support using the system version of brotli . This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
./src/native/libs/System.IO.Compression.Native/entrypoints.c
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include <minipal/entrypoints.h> // Include System.IO.Compression.Native headers #include "pal_zlib.h" #include <external/brotli/include/brotli/decode.h> #include <external/brotli/include/brotli/encode.h> #include <external/brotli/include/brotli/port.h> #include <external/brotli/include/brotli/types.h> static const Entry s_compressionNative[] = { DllImportEntry(BrotliDecoderCreateInstance) DllImportEntry(BrotliDecoderDecompress) DllImportEntry(BrotliDecoderDecompressStream) DllImportEntry(BrotliDecoderDestroyInstance) DllImportEntry(BrotliDecoderIsFinished) DllImportEntry(BrotliEncoderCompress) DllImportEntry(BrotliEncoderCompressStream) DllImportEntry(BrotliEncoderCreateInstance) DllImportEntry(BrotliEncoderDestroyInstance) DllImportEntry(BrotliEncoderHasMoreOutput) DllImportEntry(BrotliEncoderSetParameter) DllImportEntry(CompressionNative_Crc32) DllImportEntry(CompressionNative_Deflate) DllImportEntry(CompressionNative_DeflateEnd) DllImportEntry(CompressionNative_DeflateReset) DllImportEntry(CompressionNative_DeflateInit2_) DllImportEntry(CompressionNative_Inflate) DllImportEntry(CompressionNative_InflateEnd) DllImportEntry(CompressionNative_InflateReset) DllImportEntry(CompressionNative_InflateInit2_) }; EXTERN_C const void* CompressionResolveDllImport(const char* name); EXTERN_C const void* CompressionResolveDllImport(const char* name) { return minipal_resolve_dllimport(s_compressionNative, ARRAY_SIZE(s_compressionNative), name); }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include <minipal/entrypoints.h> // Include System.IO.Compression.Native headers #include "pal_zlib.h" #include <brotli/decode.h> #include <brotli/encode.h> #include <brotli/port.h> #include <brotli/types.h> static const Entry s_compressionNative[] = { DllImportEntry(BrotliDecoderCreateInstance) DllImportEntry(BrotliDecoderDecompress) DllImportEntry(BrotliDecoderDecompressStream) DllImportEntry(BrotliDecoderDestroyInstance) DllImportEntry(BrotliDecoderIsFinished) DllImportEntry(BrotliEncoderCompress) DllImportEntry(BrotliEncoderCompressStream) DllImportEntry(BrotliEncoderCreateInstance) DllImportEntry(BrotliEncoderDestroyInstance) DllImportEntry(BrotliEncoderHasMoreOutput) DllImportEntry(BrotliEncoderSetParameter) DllImportEntry(CompressionNative_Crc32) DllImportEntry(CompressionNative_Deflate) DllImportEntry(CompressionNative_DeflateEnd) DllImportEntry(CompressionNative_DeflateReset) DllImportEntry(CompressionNative_DeflateInit2_) DllImportEntry(CompressionNative_Inflate) DllImportEntry(CompressionNative_InflateEnd) DllImportEntry(CompressionNative_InflateReset) DllImportEntry(CompressionNative_InflateInit2_) }; EXTERN_C const void* CompressionResolveDllImport(const char* name); EXTERN_C const void* CompressionResolveDllImport(const char* name) { return minipal_resolve_dllimport(s_compressionNative, ARRAY_SIZE(s_compressionNative), name); }
1
dotnet/runtime
66,462
Support using the system version of brotli
This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
omajid
2022-03-10T17:19:11Z
2022-03-23T03:49:50Z
c3e1d21c2fb30436ae24ef7ef4f458e3270bb7e3
5ca9223639700750ff12bb1fed9fa6e397062b78
Support using the system version of brotli . This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
./src/native/libs/System.IO.Compression.Native/extra_libs.cmake
macro(append_extra_compression_libs NativeLibsExtra) # TODO: remove the mono-style HOST_ variable checks once Mono is using eng/native/configureplatform.cmake to define the CLR_CMAKE_TARGET_ defines if (CLR_CMAKE_TARGET_BROWSER OR HOST_BROWSER) # nothing special to link elseif (CLR_CMAKE_TARGET_ANDROID OR HOST_ANDROID) # need special case here since we want to link against libz.so but find_package() would resolve libz.a set(ZLIB_LIBRARIES z) elseif (CLR_CMAKE_TARGET_SUNOS OR HOST_SOLARIS) set(ZLIB_LIBRARIES z m) else () find_package(ZLIB REQUIRED) endif () list(APPEND ${NativeLibsExtra} ${ZLIB_LIBRARIES}) endmacro()
macro(append_extra_compression_libs NativeLibsExtra) # TODO: remove the mono-style HOST_ variable checks once Mono is using eng/native/configureplatform.cmake to define the CLR_CMAKE_TARGET_ defines if (CLR_CMAKE_TARGET_BROWSER OR HOST_BROWSER) # nothing special to link elseif (CLR_CMAKE_TARGET_ANDROID OR HOST_ANDROID) # need special case here since we want to link against libz.so but find_package() would resolve libz.a set(ZLIB_LIBRARIES z) elseif (CLR_CMAKE_TARGET_SUNOS OR HOST_SOLARIS) set(ZLIB_LIBRARIES z m) else () find_package(ZLIB REQUIRED) endif () list(APPEND ${NativeLibsExtra} ${ZLIB_LIBRARIES}) if (CLR_CMAKE_USE_SYSTEM_BROTLI) find_library(BROTLIDEC brotlidec REQUIRED) find_library(BROTLIENC brotlienc REQUIRED) list(APPEND ${NativeLibsExtra} ${BROTLIDEC} ${BROTLIENC}) endif () endmacro()
1
dotnet/runtime
66,462
Support using the system version of brotli
This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
omajid
2022-03-10T17:19:11Z
2022-03-23T03:49:50Z
c3e1d21c2fb30436ae24ef7ef4f458e3270bb7e3
5ca9223639700750ff12bb1fed9fa6e397062b78
Support using the system version of brotli . This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
./src/native/external/zlib-intel/slide_sse.c
/* * SSE optimized hash slide * * Copyright (C) 2017 Intel Corporation * Authors: * Arjan van de Ven <[email protected]> * Jim Kukunas <[email protected]> * * For conditions of distribution and use, see copyright notice in zlib.h */ #include "deflate.h" #ifdef USE_SSE_SLIDE #include <immintrin.h> void slide_hash_sse(deflate_state *s) { unsigned n; Posf *p; uInt wsize = s->w_size; z_const __m128i xmm_wsize = _mm_set1_epi16(s->w_size); n = s->hash_size; p = &s->head[n] - 8; do { __m128i value, result; value = _mm_loadu_si128((__m128i *)p); result= _mm_subs_epu16(value, xmm_wsize); _mm_storeu_si128((__m128i *)p, result); p -= 8; n -= 8; } while (n > 0); #ifndef FASTEST n = wsize; p = &s->prev[n] - 8; do { __m128i value, result; value = _mm_loadu_si128((__m128i *)p); result= _mm_subs_epu16(value, xmm_wsize); _mm_storeu_si128((__m128i *)p, result); p -= 8; n -= 8; } while (n > 0); #endif } #endif
/* * SSE optimized hash slide * * Copyright (C) 2017 Intel Corporation * Authors: * Arjan van de Ven <[email protected]> * Jim Kukunas <[email protected]> * * For conditions of distribution and use, see copyright notice in zlib.h */ #include "deflate.h" #ifdef USE_SSE_SLIDE #include <immintrin.h> void slide_hash_sse(deflate_state *s) { unsigned n; Posf *p; uInt wsize = s->w_size; z_const __m128i xmm_wsize = _mm_set1_epi16(s->w_size); n = s->hash_size; p = &s->head[n] - 8; do { __m128i value, result; value = _mm_loadu_si128((__m128i *)p); result= _mm_subs_epu16(value, xmm_wsize); _mm_storeu_si128((__m128i *)p, result); p -= 8; n -= 8; } while (n > 0); #ifndef FASTEST n = wsize; p = &s->prev[n] - 8; do { __m128i value, result; value = _mm_loadu_si128((__m128i *)p); result= _mm_subs_epu16(value, xmm_wsize); _mm_storeu_si128((__m128i *)p, result); p -= 8; n -= 8; } while (n > 0); #endif } #endif
-1
dotnet/runtime
66,462
Support using the system version of brotli
This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
omajid
2022-03-10T17:19:11Z
2022-03-23T03:49:50Z
c3e1d21c2fb30436ae24ef7ef4f458e3270bb7e3
5ca9223639700750ff12bb1fed9fa6e397062b78
Support using the system version of brotli . This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
./src/native/external/libunwind/src/mi/Lget_proc_name.c
#define UNW_LOCAL_ONLY #include <libunwind.h> #if defined(UNW_LOCAL_ONLY) && !defined(UNW_REMOTE_ONLY) #include "Gget_proc_name.c" #endif
#define UNW_LOCAL_ONLY #include <libunwind.h> #if defined(UNW_LOCAL_ONLY) && !defined(UNW_REMOTE_ONLY) #include "Gget_proc_name.c" #endif
-1
dotnet/runtime
66,462
Support using the system version of brotli
This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
omajid
2022-03-10T17:19:11Z
2022-03-23T03:49:50Z
c3e1d21c2fb30436ae24ef7ef4f458e3270bb7e3
5ca9223639700750ff12bb1fed9fa6e397062b78
Support using the system version of brotli . This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
./src/native/external/libunwind/src/ia64/Gtables.c
/* libunwind - a platform-independent unwind library Copyright (c) 2001-2005 Hewlett-Packard Development Company, L.P. Contributed by David Mosberger-Tang <[email protected]> This file is part of libunwind. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <assert.h> #include <stdlib.h> #include <stddef.h> #include "unwind_i.h" #ifdef HAVE_IA64INTRIN_H # include <ia64intrin.h> #endif extern unw_addr_space_t _ULia64_local_addr_space; struct ia64_table_entry { uint64_t start_offset; uint64_t end_offset; uint64_t info_offset; }; #ifdef UNW_LOCAL_ONLY static inline int is_local_addr_space (unw_addr_space_t as) { return 1; } static inline int read_mem (unw_addr_space_t as, unw_word_t addr, unw_word_t *valp, void *arg) { *valp = *(unw_word_t *) addr; return 0; } #else /* !UNW_LOCAL_ONLY */ static inline int is_local_addr_space (unw_addr_space_t as) { return as == unw_local_addr_space; } static inline int read_mem (unw_addr_space_t as, unw_word_t addr, unw_word_t *valp, void *arg) { unw_accessors_t *a = unw_get_accessors_int (as); return (*a->access_mem) (as, addr, valp, 0, arg); } /* Helper macro for reading an ia64_table_entry from remote memory. */ #define remote_read(addr, member) \ (*a->access_mem) (as, (addr) + offsetof (struct ia64_table_entry, \ member), &member, 0, arg) /* Lookup an unwind-table entry in remote memory. Returns 1 if an entry is found, 0 if no entry is found, negative if an error occurred reading remote memory. */ static int remote_lookup (unw_addr_space_t as, unw_word_t table, size_t table_size, unw_word_t rel_ip, struct ia64_table_entry *e, void *arg) { unw_word_t e_addr = 0, start_offset, end_offset, info_offset; unw_accessors_t *a = unw_get_accessors_int (as); unsigned long lo, hi, mid; int ret; /* do a binary search for right entry: */ for (lo = 0, hi = table_size / sizeof (struct ia64_table_entry); lo < hi;) { mid = (lo + hi) / 2; e_addr = table + mid * sizeof (struct ia64_table_entry); if ((ret = remote_read (e_addr, start_offset)) < 0) return ret; if (rel_ip < start_offset) hi = mid; else { if ((ret = remote_read (e_addr, end_offset)) < 0) return ret; if (rel_ip >= end_offset) lo = mid + 1; else break; } } if (rel_ip < start_offset || rel_ip >= end_offset) return 0; e->start_offset = start_offset; e->end_offset = end_offset; if ((ret = remote_read (e_addr, info_offset)) < 0) return ret; e->info_offset = info_offset; return 1; } HIDDEN void tdep_put_unwind_info (unw_addr_space_t as, unw_proc_info_t *pi, void *arg) { if (!pi->unwind_info) return; if (is_local_addr_space (as)) { free (pi->unwind_info); pi->unwind_info = NULL; } } unw_word_t _Uia64_find_dyn_list (unw_addr_space_t as, unw_dyn_info_t *di, void *arg) { unw_word_t hdr_addr, info_addr, hdr, directives, pers, cookie, off; unw_word_t start_offset, end_offset, info_offset, segbase; struct ia64_table_entry *e; size_t table_size; unw_word_t gp = di->gp; int ret; switch (di->format) { case UNW_INFO_FORMAT_DYNAMIC: default: return 0; case UNW_INFO_FORMAT_TABLE: e = (struct ia64_table_entry *) di->u.ti.table_data; table_size = di->u.ti.table_len * sizeof (di->u.ti.table_data[0]); segbase = di->u.ti.segbase; if (table_size < sizeof (struct ia64_table_entry)) return 0; start_offset = e[0].start_offset; end_offset = e[0].end_offset; info_offset = e[0].info_offset; break; case UNW_INFO_FORMAT_REMOTE_TABLE: { unw_accessors_t *a = unw_get_accessors_int (as); unw_word_t e_addr = di->u.rti.table_data; table_size = di->u.rti.table_len * sizeof (unw_word_t); segbase = di->u.rti.segbase; if (table_size < sizeof (struct ia64_table_entry)) return 0; if ( (ret = remote_read (e_addr, start_offset) < 0) || (ret = remote_read (e_addr, end_offset) < 0) || (ret = remote_read (e_addr, info_offset) < 0)) return ret; } break; } if (start_offset != end_offset) /* dyn-list entry cover a zero-length "procedure" and should be first entry (note: technically a binary could contain code below the segment base, but this doesn't happen for normal binaries and certainly doesn't happen when libunwind is a separate shared object. For weird cases, the application may have to provide its own (slower) version of this routine. */ return 0; hdr_addr = info_offset + segbase; info_addr = hdr_addr + 8; /* read the header word: */ if ((ret = read_mem (as, hdr_addr, &hdr, arg)) < 0) return ret; if (IA64_UNW_VER (hdr) != 1 || IA64_UNW_FLAG_EHANDLER (hdr) || IA64_UNW_FLAG_UHANDLER (hdr)) /* dyn-list entry must be version 1 and doesn't have ehandler or uhandler */ return 0; if (IA64_UNW_LENGTH (hdr) != 1) /* dyn-list entry must consist of a single word of NOP directives */ return 0; if ( ((ret = read_mem (as, info_addr, &directives, arg)) < 0) || ((ret = read_mem (as, info_addr + 0x08, &pers, arg)) < 0) || ((ret = read_mem (as, info_addr + 0x10, &cookie, arg)) < 0) || ((ret = read_mem (as, info_addr + 0x18, &off, arg)) < 0)) return 0; if (directives != 0 || pers != 0 || (!as->big_endian && cookie != 0x7473696c2d6e7964ULL) || ( as->big_endian && cookie != 0x64796e2d6c697374ULL)) return 0; /* OK, we ran the gauntlet and found it: */ return off + gp; } #endif /* !UNW_LOCAL_ONLY */ static inline const struct ia64_table_entry * lookup (struct ia64_table_entry *table, size_t table_size, unw_word_t rel_ip) { const struct ia64_table_entry *e = 0; unsigned long lo, hi, mid; /* do a binary search for right entry: */ for (lo = 0, hi = table_size / sizeof (struct ia64_table_entry); lo < hi;) { mid = (lo + hi) / 2; e = table + mid; if (rel_ip < e->start_offset) hi = mid; else if (rel_ip >= e->end_offset) lo = mid + 1; else break; } if (rel_ip < e->start_offset || rel_ip >= e->end_offset) return NULL; return e; } int unw_search_ia64_unwind_table (unw_addr_space_t as, unw_word_t ip, unw_dyn_info_t *di, unw_proc_info_t *pi, int need_unwind_info, void *arg) { unw_word_t addr, hdr_addr, info_addr, info_end_addr, hdr, *wp; const struct ia64_table_entry *e = NULL; unw_word_t handler_offset, segbase = 0; int ret, is_local; #ifndef UNW_LOCAL_ONLY struct ia64_table_entry ent; #endif assert ((di->format == UNW_INFO_FORMAT_TABLE || di->format == UNW_INFO_FORMAT_REMOTE_TABLE) && (ip >= di->start_ip && ip < di->end_ip)); pi->flags = 0; pi->unwind_info = 0; pi->handler = 0; if (likely (di->format == UNW_INFO_FORMAT_TABLE)) { segbase = di->u.ti.segbase; e = lookup ((struct ia64_table_entry *) di->u.ti.table_data, di->u.ti.table_len * sizeof (unw_word_t), ip - segbase); } #ifndef UNW_LOCAL_ONLY else { segbase = di->u.rti.segbase; if ((ret = remote_lookup (as, di->u.rti.table_data, di->u.rti.table_len * sizeof (unw_word_t), ip - segbase, &ent, arg)) < 0) return ret; if (ret) e = &ent; } #endif if (!e) { /* IP is inside this table's range, but there is no explicit unwind info => use default conventions (i.e., this is NOT an error). */ memset (pi, 0, sizeof (*pi)); pi->start_ip = 0; pi->end_ip = 0; pi->gp = di->gp; pi->lsda = 0; return 0; } pi->start_ip = e->start_offset + segbase; pi->end_ip = e->end_offset + segbase; hdr_addr = e->info_offset + segbase; info_addr = hdr_addr + 8; /* Read the header word. Note: the actual unwind-info is always assumed to reside in memory, independent of whether di->format is UNW_INFO_FORMAT_TABLE or UNW_INFO_FORMAT_REMOTE_TABLE. */ if ((ret = read_mem (as, hdr_addr, &hdr, arg)) < 0) return ret; if (IA64_UNW_VER (hdr) != 1) { Debug (1, "Unknown header version %ld (hdr word=0x%lx @ 0x%lx)\n", IA64_UNW_VER (hdr), (unsigned long) hdr, (unsigned long) hdr_addr); return -UNW_EBADVERSION; } info_end_addr = info_addr + 8 * IA64_UNW_LENGTH (hdr); is_local = is_local_addr_space (as); /* If we must have the unwind-info, return it. Also, if we are in the local address-space, return the unwind-info because it's so cheap to do so and it may come in handy later on. */ if (need_unwind_info || is_local) { pi->unwind_info_size = 8 * IA64_UNW_LENGTH (hdr); if (is_local) pi->unwind_info = (void *) (uintptr_t) info_addr; else { /* Internalize unwind info. Note: since we're doing this only for non-local address spaces, there is no signal-safety issue and it is OK to use malloc()/free(). */ pi->unwind_info = malloc (8 * IA64_UNW_LENGTH (hdr)); if (!pi->unwind_info) return -UNW_ENOMEM; wp = (unw_word_t *) pi->unwind_info; for (addr = info_addr; addr < info_end_addr; addr += 8, ++wp) { if ((ret = read_mem (as, addr, wp, arg)) < 0) { free (pi->unwind_info); return ret; } } } } if (IA64_UNW_FLAG_EHANDLER (hdr) || IA64_UNW_FLAG_UHANDLER (hdr)) { /* read the personality routine address (address is gp-relative): */ if ((ret = read_mem (as, info_end_addr, &handler_offset, arg)) < 0) return ret; Debug (4, "handler ptr @ offset=%lx, gp=%lx\n", handler_offset, di->gp); if ((read_mem (as, handler_offset + di->gp, &pi->handler, arg)) < 0) return ret; } pi->lsda = info_end_addr + 8; pi->gp = di->gp; pi->format = di->format; return 0; } #ifndef UNW_REMOTE_ONLY # if defined(HAVE_DL_ITERATE_PHDR) # include <link.h> # include <stdlib.h> # if __GLIBC__ < 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ < 2) \ || (__GLIBC__ == 2 && __GLIBC_MINOR__ == 2 && !defined(DT_CONFIG)) # error You need GLIBC 2.2.4 or later on IA-64 Linux # endif # if defined(HAVE_GETUNWIND) extern unsigned long getunwind (void *buf, size_t len); # else /* HAVE_GETUNWIND */ # include <unistd.h> # include <sys/syscall.h> # ifndef __NR_getunwind # define __NR_getunwind 1215 # endif static unsigned long getunwind (void *buf, size_t len) { return syscall (SYS_getunwind, buf, len); } # endif /* HAVE_GETUNWIND */ static unw_dyn_info_t kernel_table; static int get_kernel_table (unw_dyn_info_t *di) { struct ia64_table_entry *ktab, *etab; size_t size; Debug (16, "getting kernel table"); size = getunwind (NULL, 0); ktab = sos_alloc (size); if (!ktab) { Dprintf (__FILE__".%s: failed to allocate %zu bytes", __FUNCTION__, size); return -UNW_ENOMEM; } getunwind (ktab, size); /* Determine length of kernel's unwind table & relocate its entries. */ for (etab = ktab; etab->start_offset; ++etab) etab->info_offset += (uint64_t) ktab; di->format = UNW_INFO_FORMAT_TABLE; di->gp = 0; di->start_ip = ktab[0].start_offset; di->end_ip = etab[-1].end_offset; di->u.ti.name_ptr = (unw_word_t) "<kernel>"; di->u.ti.segbase = 0; di->u.ti.table_len = ((char *) etab - (char *) ktab) / sizeof (unw_word_t); di->u.ti.table_data = (unw_word_t *) ktab; Debug (16, "found table `%s': [%lx-%lx) segbase=%lx len=%lu\n", (char *) di->u.ti.name_ptr, di->start_ip, di->end_ip, di->u.ti.segbase, di->u.ti.table_len); return 0; } # ifndef UNW_LOCAL_ONLY /* This is exported for the benefit of libunwind-ptrace.a. */ int _Uia64_get_kernel_table (unw_dyn_info_t *di) { int ret; if (!kernel_table.u.ti.table_data) if ((ret = get_kernel_table (&kernel_table)) < 0) return ret; memcpy (di, &kernel_table, sizeof (*di)); return 0; } # endif /* !UNW_LOCAL_ONLY */ static inline unsigned long current_gp (void) { # if defined(__GNUC__) && !defined(__INTEL_COMPILER) register unsigned long gp __asm__("gp"); return gp; # elif HAVE_IA64INTRIN_H return __getReg (_IA64_REG_GP); # else # error Implement me. # endif } static int callback (struct dl_phdr_info *info, size_t size, void *ptr) { unw_dyn_info_t *di = ptr; const Elf64_Phdr *phdr, *p_unwind, *p_dynamic, *p_text; long n; Elf64_Addr load_base, segbase = 0; /* Make sure struct dl_phdr_info is at least as big as we need. */ if (size < offsetof (struct dl_phdr_info, dlpi_phnum) + sizeof (info->dlpi_phnum)) return -1; Debug (16, "checking `%s' (load_base=%lx)\n", info->dlpi_name, info->dlpi_addr); phdr = info->dlpi_phdr; load_base = info->dlpi_addr; p_text = NULL; p_unwind = NULL; p_dynamic = NULL; /* See if PC falls into one of the loaded segments. Find the unwind segment at the same time. */ for (n = info->dlpi_phnum; --n >= 0; phdr++) { if (phdr->p_type == PT_LOAD) { Elf64_Addr vaddr = phdr->p_vaddr + load_base; if (di->u.ti.segbase >= vaddr && di->u.ti.segbase < vaddr + phdr->p_memsz) p_text = phdr; } else if (phdr->p_type == PT_IA_64_UNWIND) p_unwind = phdr; else if (phdr->p_type == PT_DYNAMIC) p_dynamic = phdr; } if (!p_text || !p_unwind) return 0; if (likely (p_unwind->p_vaddr >= p_text->p_vaddr && p_unwind->p_vaddr < p_text->p_vaddr + p_text->p_memsz)) /* normal case: unwind table is inside text segment */ segbase = p_text->p_vaddr + load_base; else { /* Special case: unwind table is in some other segment; this happens for the Linux kernel's gate DSO, for example. */ phdr = info->dlpi_phdr; for (n = info->dlpi_phnum; --n >= 0; phdr++) { if (phdr->p_type == PT_LOAD && p_unwind->p_vaddr >= phdr->p_vaddr && p_unwind->p_vaddr < phdr->p_vaddr + phdr->p_memsz) { segbase = phdr->p_vaddr + load_base; break; } } } if (p_dynamic) { /* For dynamicly linked executables and shared libraries, DT_PLTGOT is the gp value for that object. */ Elf64_Dyn *dyn = (Elf64_Dyn *)(p_dynamic->p_vaddr + load_base); for (; dyn->d_tag != DT_NULL; ++dyn) if (dyn->d_tag == DT_PLTGOT) { /* On IA-64, _DYNAMIC is writable and GLIBC has relocated it. */ di->gp = dyn->d_un.d_ptr; break; } } else /* Otherwise this is a static executable with no _DYNAMIC. The gp is constant program-wide. */ di->gp = current_gp(); di->format = UNW_INFO_FORMAT_TABLE; di->start_ip = p_text->p_vaddr + load_base; di->end_ip = p_text->p_vaddr + load_base + p_text->p_memsz; di->u.ti.name_ptr = (unw_word_t) info->dlpi_name; di->u.ti.table_data = (void *) (p_unwind->p_vaddr + load_base); di->u.ti.table_len = p_unwind->p_memsz / sizeof (unw_word_t); di->u.ti.segbase = segbase; Debug (16, "found table `%s': segbase=%lx, len=%lu, gp=%lx, " "table_data=%p\n", (char *) di->u.ti.name_ptr, di->u.ti.segbase, di->u.ti.table_len, di->gp, di->u.ti.table_data); return 1; } # ifdef HAVE_DL_PHDR_REMOVALS_COUNTER static inline int validate_cache (unw_addr_space_t as) { /* Note: we don't need to serialize here with respect to dl_iterate_phdr() because if somebody were to remove an object that is required to complete the unwind on whose behalf we're validating the cache here, we'd be hosed anyhow. What we're guarding against here is the case where library FOO gets mapped, unwind info for FOO gets cached, FOO gets unmapped, BAR gets mapped in the place where FOO was and then we unwind across a function in FOO. Since no thread can execute in BAR before FOO has been removed, we are guaranteed that dl_phdr_removals_counter() would have been incremented before we get here. */ unsigned long long removals = dl_phdr_removals_counter (); if (removals == as->shared_object_removals) return 1; as->shared_object_removals = removals; unw_flush_cache (as, 0, 0); return -1; } # else /* !HAVE_DL_PHDR_REMOVALS_COUNTER */ /* Check whether any phdrs have been removed since we last flushed the cache. If so we flush the cache and return -1, if not, we do nothing and return 1. */ static int check_callback (struct dl_phdr_info *info, size_t size, void *ptr) { # ifdef HAVE_STRUCT_DL_PHDR_INFO_DLPI_SUBS unw_addr_space_t as = ptr; if (size < offsetof (struct dl_phdr_info, dlpi_subs) + sizeof (info->dlpi_subs)) /* It would be safer to flush the cache here, but that would disable caching for older libc's which would be incompatible with the behavior of older versions of libunwind so we return 1 instead and hope nobody runs into stale cache info... */ return 1; if (info->dlpi_subs == as->shared_object_removals) return 1; as->shared_object_removals = info->dlpi_subs; unw_flush_cache (as, 0, 0); return -1; /* indicate that there were removals */ # else return 1; # endif } static inline int validate_cache (unw_addr_space_t as) { intrmask_t saved_mask; int ret; SIGPROCMASK (SIG_SETMASK, &unwi_full_mask, &saved_mask); ret = dl_iterate_phdr (check_callback, as); SIGPROCMASK (SIG_SETMASK, &saved_mask, NULL); return ret; } # endif /* HAVE_DL_PHDR_REMOVALS_COUNTER */ # elif defined(HAVE_DLMODINFO) /* Support for HP-UX-style dlmodinfo() */ # include <dlfcn.h> static inline int validate_cache (unw_addr_space_t as) { return 1; } # endif /* !HAVE_DLMODINFO */ HIDDEN int tdep_find_proc_info (unw_addr_space_t as, unw_word_t ip, unw_proc_info_t *pi, int need_unwind_info, void *arg) { # if defined(HAVE_DL_ITERATE_PHDR) unw_dyn_info_t di, *dip = &di; intrmask_t saved_mask; int ret; di.u.ti.segbase = ip; /* this is cheap... */ SIGPROCMASK (SIG_SETMASK, &unwi_full_mask, &saved_mask); ret = dl_iterate_phdr (callback, &di); SIGPROCMASK (SIG_SETMASK, &saved_mask, NULL); if (ret <= 0) { if (!kernel_table.u.ti.table_data) { if ((ret = get_kernel_table (&kernel_table)) < 0) return ret; } if (ip < kernel_table.start_ip || ip >= kernel_table.end_ip) return -UNW_ENOINFO; dip = &kernel_table; } # elif defined(HAVE_DLMODINFO) # define UNWIND_TBL_32BIT 0x8000000000000000 struct load_module_desc lmd; unw_dyn_info_t di, *dip = &di; struct unwind_header { uint64_t header_version; uint64_t start_offset; uint64_t end_offset; } *uhdr; if (!dlmodinfo (ip, &lmd, sizeof (lmd), NULL, 0, 0)) return -UNW_ENOINFO; di.format = UNW_INFO_FORMAT_TABLE; di.start_ip = lmd.text_base; di.end_ip = lmd.text_base + lmd.text_size; di.gp = lmd.linkage_ptr; di.u.ti.name_ptr = 0; /* no obvious table-name available */ di.u.ti.segbase = lmd.text_base; uhdr = (struct unwind_header *) lmd.unwind_base; if ((uhdr->header_version & ~UNWIND_TBL_32BIT) != 1 && (uhdr->header_version & ~UNWIND_TBL_32BIT) != 2) { Debug (1, "encountered unknown unwind header version %ld\n", (long) (uhdr->header_version & ~UNWIND_TBL_32BIT)); return -UNW_EBADVERSION; } if (uhdr->header_version & UNWIND_TBL_32BIT) { Debug (1, "32-bit unwind tables are not supported yet\n"); return -UNW_EINVAL; } di.u.ti.table_data = (unw_word_t *) (di.u.ti.segbase + uhdr->start_offset); di.u.ti.table_len = ((uhdr->end_offset - uhdr->start_offset) / sizeof (unw_word_t)); Debug (16, "found table `%s': segbase=%lx, len=%lu, gp=%lx, " "table_data=%p\n", (char *) di.u.ti.name_ptr, di.u.ti.segbase, di.u.ti.table_len, di.gp, di.u.ti.table_data); # endif /* now search the table: */ return tdep_search_unwind_table (as, ip, dip, pi, need_unwind_info, arg); } /* Returns 1 if the cache is up-to-date or -1 if the cache contained stale data and had to be flushed. */ HIDDEN int ia64_local_validate_cache (unw_addr_space_t as, void *arg) { return validate_cache (as); } #endif /* !UNW_REMOTE_ONLY */
/* libunwind - a platform-independent unwind library Copyright (c) 2001-2005 Hewlett-Packard Development Company, L.P. Contributed by David Mosberger-Tang <[email protected]> This file is part of libunwind. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <assert.h> #include <stdlib.h> #include <stddef.h> #include "unwind_i.h" #ifdef HAVE_IA64INTRIN_H # include <ia64intrin.h> #endif extern unw_addr_space_t _ULia64_local_addr_space; struct ia64_table_entry { uint64_t start_offset; uint64_t end_offset; uint64_t info_offset; }; #ifdef UNW_LOCAL_ONLY static inline int is_local_addr_space (unw_addr_space_t as) { return 1; } static inline int read_mem (unw_addr_space_t as, unw_word_t addr, unw_word_t *valp, void *arg) { *valp = *(unw_word_t *) addr; return 0; } #else /* !UNW_LOCAL_ONLY */ static inline int is_local_addr_space (unw_addr_space_t as) { return as == unw_local_addr_space; } static inline int read_mem (unw_addr_space_t as, unw_word_t addr, unw_word_t *valp, void *arg) { unw_accessors_t *a = unw_get_accessors_int (as); return (*a->access_mem) (as, addr, valp, 0, arg); } /* Helper macro for reading an ia64_table_entry from remote memory. */ #define remote_read(addr, member) \ (*a->access_mem) (as, (addr) + offsetof (struct ia64_table_entry, \ member), &member, 0, arg) /* Lookup an unwind-table entry in remote memory. Returns 1 if an entry is found, 0 if no entry is found, negative if an error occurred reading remote memory. */ static int remote_lookup (unw_addr_space_t as, unw_word_t table, size_t table_size, unw_word_t rel_ip, struct ia64_table_entry *e, void *arg) { unw_word_t e_addr = 0, start_offset, end_offset, info_offset; unw_accessors_t *a = unw_get_accessors_int (as); unsigned long lo, hi, mid; int ret; /* do a binary search for right entry: */ for (lo = 0, hi = table_size / sizeof (struct ia64_table_entry); lo < hi;) { mid = (lo + hi) / 2; e_addr = table + mid * sizeof (struct ia64_table_entry); if ((ret = remote_read (e_addr, start_offset)) < 0) return ret; if (rel_ip < start_offset) hi = mid; else { if ((ret = remote_read (e_addr, end_offset)) < 0) return ret; if (rel_ip >= end_offset) lo = mid + 1; else break; } } if (rel_ip < start_offset || rel_ip >= end_offset) return 0; e->start_offset = start_offset; e->end_offset = end_offset; if ((ret = remote_read (e_addr, info_offset)) < 0) return ret; e->info_offset = info_offset; return 1; } HIDDEN void tdep_put_unwind_info (unw_addr_space_t as, unw_proc_info_t *pi, void *arg) { if (!pi->unwind_info) return; if (is_local_addr_space (as)) { free (pi->unwind_info); pi->unwind_info = NULL; } } unw_word_t _Uia64_find_dyn_list (unw_addr_space_t as, unw_dyn_info_t *di, void *arg) { unw_word_t hdr_addr, info_addr, hdr, directives, pers, cookie, off; unw_word_t start_offset, end_offset, info_offset, segbase; struct ia64_table_entry *e; size_t table_size; unw_word_t gp = di->gp; int ret; switch (di->format) { case UNW_INFO_FORMAT_DYNAMIC: default: return 0; case UNW_INFO_FORMAT_TABLE: e = (struct ia64_table_entry *) di->u.ti.table_data; table_size = di->u.ti.table_len * sizeof (di->u.ti.table_data[0]); segbase = di->u.ti.segbase; if (table_size < sizeof (struct ia64_table_entry)) return 0; start_offset = e[0].start_offset; end_offset = e[0].end_offset; info_offset = e[0].info_offset; break; case UNW_INFO_FORMAT_REMOTE_TABLE: { unw_accessors_t *a = unw_get_accessors_int (as); unw_word_t e_addr = di->u.rti.table_data; table_size = di->u.rti.table_len * sizeof (unw_word_t); segbase = di->u.rti.segbase; if (table_size < sizeof (struct ia64_table_entry)) return 0; if ( (ret = remote_read (e_addr, start_offset) < 0) || (ret = remote_read (e_addr, end_offset) < 0) || (ret = remote_read (e_addr, info_offset) < 0)) return ret; } break; } if (start_offset != end_offset) /* dyn-list entry cover a zero-length "procedure" and should be first entry (note: technically a binary could contain code below the segment base, but this doesn't happen for normal binaries and certainly doesn't happen when libunwind is a separate shared object. For weird cases, the application may have to provide its own (slower) version of this routine. */ return 0; hdr_addr = info_offset + segbase; info_addr = hdr_addr + 8; /* read the header word: */ if ((ret = read_mem (as, hdr_addr, &hdr, arg)) < 0) return ret; if (IA64_UNW_VER (hdr) != 1 || IA64_UNW_FLAG_EHANDLER (hdr) || IA64_UNW_FLAG_UHANDLER (hdr)) /* dyn-list entry must be version 1 and doesn't have ehandler or uhandler */ return 0; if (IA64_UNW_LENGTH (hdr) != 1) /* dyn-list entry must consist of a single word of NOP directives */ return 0; if ( ((ret = read_mem (as, info_addr, &directives, arg)) < 0) || ((ret = read_mem (as, info_addr + 0x08, &pers, arg)) < 0) || ((ret = read_mem (as, info_addr + 0x10, &cookie, arg)) < 0) || ((ret = read_mem (as, info_addr + 0x18, &off, arg)) < 0)) return 0; if (directives != 0 || pers != 0 || (!as->big_endian && cookie != 0x7473696c2d6e7964ULL) || ( as->big_endian && cookie != 0x64796e2d6c697374ULL)) return 0; /* OK, we ran the gauntlet and found it: */ return off + gp; } #endif /* !UNW_LOCAL_ONLY */ static inline const struct ia64_table_entry * lookup (struct ia64_table_entry *table, size_t table_size, unw_word_t rel_ip) { const struct ia64_table_entry *e = 0; unsigned long lo, hi, mid; /* do a binary search for right entry: */ for (lo = 0, hi = table_size / sizeof (struct ia64_table_entry); lo < hi;) { mid = (lo + hi) / 2; e = table + mid; if (rel_ip < e->start_offset) hi = mid; else if (rel_ip >= e->end_offset) lo = mid + 1; else break; } if (rel_ip < e->start_offset || rel_ip >= e->end_offset) return NULL; return e; } int unw_search_ia64_unwind_table (unw_addr_space_t as, unw_word_t ip, unw_dyn_info_t *di, unw_proc_info_t *pi, int need_unwind_info, void *arg) { unw_word_t addr, hdr_addr, info_addr, info_end_addr, hdr, *wp; const struct ia64_table_entry *e = NULL; unw_word_t handler_offset, segbase = 0; int ret, is_local; #ifndef UNW_LOCAL_ONLY struct ia64_table_entry ent; #endif assert ((di->format == UNW_INFO_FORMAT_TABLE || di->format == UNW_INFO_FORMAT_REMOTE_TABLE) && (ip >= di->start_ip && ip < di->end_ip)); pi->flags = 0; pi->unwind_info = 0; pi->handler = 0; if (likely (di->format == UNW_INFO_FORMAT_TABLE)) { segbase = di->u.ti.segbase; e = lookup ((struct ia64_table_entry *) di->u.ti.table_data, di->u.ti.table_len * sizeof (unw_word_t), ip - segbase); } #ifndef UNW_LOCAL_ONLY else { segbase = di->u.rti.segbase; if ((ret = remote_lookup (as, di->u.rti.table_data, di->u.rti.table_len * sizeof (unw_word_t), ip - segbase, &ent, arg)) < 0) return ret; if (ret) e = &ent; } #endif if (!e) { /* IP is inside this table's range, but there is no explicit unwind info => use default conventions (i.e., this is NOT an error). */ memset (pi, 0, sizeof (*pi)); pi->start_ip = 0; pi->end_ip = 0; pi->gp = di->gp; pi->lsda = 0; return 0; } pi->start_ip = e->start_offset + segbase; pi->end_ip = e->end_offset + segbase; hdr_addr = e->info_offset + segbase; info_addr = hdr_addr + 8; /* Read the header word. Note: the actual unwind-info is always assumed to reside in memory, independent of whether di->format is UNW_INFO_FORMAT_TABLE or UNW_INFO_FORMAT_REMOTE_TABLE. */ if ((ret = read_mem (as, hdr_addr, &hdr, arg)) < 0) return ret; if (IA64_UNW_VER (hdr) != 1) { Debug (1, "Unknown header version %ld (hdr word=0x%lx @ 0x%lx)\n", IA64_UNW_VER (hdr), (unsigned long) hdr, (unsigned long) hdr_addr); return -UNW_EBADVERSION; } info_end_addr = info_addr + 8 * IA64_UNW_LENGTH (hdr); is_local = is_local_addr_space (as); /* If we must have the unwind-info, return it. Also, if we are in the local address-space, return the unwind-info because it's so cheap to do so and it may come in handy later on. */ if (need_unwind_info || is_local) { pi->unwind_info_size = 8 * IA64_UNW_LENGTH (hdr); if (is_local) pi->unwind_info = (void *) (uintptr_t) info_addr; else { /* Internalize unwind info. Note: since we're doing this only for non-local address spaces, there is no signal-safety issue and it is OK to use malloc()/free(). */ pi->unwind_info = malloc (8 * IA64_UNW_LENGTH (hdr)); if (!pi->unwind_info) return -UNW_ENOMEM; wp = (unw_word_t *) pi->unwind_info; for (addr = info_addr; addr < info_end_addr; addr += 8, ++wp) { if ((ret = read_mem (as, addr, wp, arg)) < 0) { free (pi->unwind_info); return ret; } } } } if (IA64_UNW_FLAG_EHANDLER (hdr) || IA64_UNW_FLAG_UHANDLER (hdr)) { /* read the personality routine address (address is gp-relative): */ if ((ret = read_mem (as, info_end_addr, &handler_offset, arg)) < 0) return ret; Debug (4, "handler ptr @ offset=%lx, gp=%lx\n", handler_offset, di->gp); if ((read_mem (as, handler_offset + di->gp, &pi->handler, arg)) < 0) return ret; } pi->lsda = info_end_addr + 8; pi->gp = di->gp; pi->format = di->format; return 0; } #ifndef UNW_REMOTE_ONLY # if defined(HAVE_DL_ITERATE_PHDR) # include <link.h> # include <stdlib.h> # if __GLIBC__ < 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ < 2) \ || (__GLIBC__ == 2 && __GLIBC_MINOR__ == 2 && !defined(DT_CONFIG)) # error You need GLIBC 2.2.4 or later on IA-64 Linux # endif # if defined(HAVE_GETUNWIND) extern unsigned long getunwind (void *buf, size_t len); # else /* HAVE_GETUNWIND */ # include <unistd.h> # include <sys/syscall.h> # ifndef __NR_getunwind # define __NR_getunwind 1215 # endif static unsigned long getunwind (void *buf, size_t len) { return syscall (SYS_getunwind, buf, len); } # endif /* HAVE_GETUNWIND */ static unw_dyn_info_t kernel_table; static int get_kernel_table (unw_dyn_info_t *di) { struct ia64_table_entry *ktab, *etab; size_t size; Debug (16, "getting kernel table"); size = getunwind (NULL, 0); ktab = sos_alloc (size); if (!ktab) { Dprintf (__FILE__".%s: failed to allocate %zu bytes", __FUNCTION__, size); return -UNW_ENOMEM; } getunwind (ktab, size); /* Determine length of kernel's unwind table & relocate its entries. */ for (etab = ktab; etab->start_offset; ++etab) etab->info_offset += (uint64_t) ktab; di->format = UNW_INFO_FORMAT_TABLE; di->gp = 0; di->start_ip = ktab[0].start_offset; di->end_ip = etab[-1].end_offset; di->u.ti.name_ptr = (unw_word_t) "<kernel>"; di->u.ti.segbase = 0; di->u.ti.table_len = ((char *) etab - (char *) ktab) / sizeof (unw_word_t); di->u.ti.table_data = (unw_word_t *) ktab; Debug (16, "found table `%s': [%lx-%lx) segbase=%lx len=%lu\n", (char *) di->u.ti.name_ptr, di->start_ip, di->end_ip, di->u.ti.segbase, di->u.ti.table_len); return 0; } # ifndef UNW_LOCAL_ONLY /* This is exported for the benefit of libunwind-ptrace.a. */ int _Uia64_get_kernel_table (unw_dyn_info_t *di) { int ret; if (!kernel_table.u.ti.table_data) if ((ret = get_kernel_table (&kernel_table)) < 0) return ret; memcpy (di, &kernel_table, sizeof (*di)); return 0; } # endif /* !UNW_LOCAL_ONLY */ static inline unsigned long current_gp (void) { # if defined(__GNUC__) && !defined(__INTEL_COMPILER) register unsigned long gp __asm__("gp"); return gp; # elif HAVE_IA64INTRIN_H return __getReg (_IA64_REG_GP); # else # error Implement me. # endif } static int callback (struct dl_phdr_info *info, size_t size, void *ptr) { unw_dyn_info_t *di = ptr; const Elf64_Phdr *phdr, *p_unwind, *p_dynamic, *p_text; long n; Elf64_Addr load_base, segbase = 0; /* Make sure struct dl_phdr_info is at least as big as we need. */ if (size < offsetof (struct dl_phdr_info, dlpi_phnum) + sizeof (info->dlpi_phnum)) return -1; Debug (16, "checking `%s' (load_base=%lx)\n", info->dlpi_name, info->dlpi_addr); phdr = info->dlpi_phdr; load_base = info->dlpi_addr; p_text = NULL; p_unwind = NULL; p_dynamic = NULL; /* See if PC falls into one of the loaded segments. Find the unwind segment at the same time. */ for (n = info->dlpi_phnum; --n >= 0; phdr++) { if (phdr->p_type == PT_LOAD) { Elf64_Addr vaddr = phdr->p_vaddr + load_base; if (di->u.ti.segbase >= vaddr && di->u.ti.segbase < vaddr + phdr->p_memsz) p_text = phdr; } else if (phdr->p_type == PT_IA_64_UNWIND) p_unwind = phdr; else if (phdr->p_type == PT_DYNAMIC) p_dynamic = phdr; } if (!p_text || !p_unwind) return 0; if (likely (p_unwind->p_vaddr >= p_text->p_vaddr && p_unwind->p_vaddr < p_text->p_vaddr + p_text->p_memsz)) /* normal case: unwind table is inside text segment */ segbase = p_text->p_vaddr + load_base; else { /* Special case: unwind table is in some other segment; this happens for the Linux kernel's gate DSO, for example. */ phdr = info->dlpi_phdr; for (n = info->dlpi_phnum; --n >= 0; phdr++) { if (phdr->p_type == PT_LOAD && p_unwind->p_vaddr >= phdr->p_vaddr && p_unwind->p_vaddr < phdr->p_vaddr + phdr->p_memsz) { segbase = phdr->p_vaddr + load_base; break; } } } if (p_dynamic) { /* For dynamicly linked executables and shared libraries, DT_PLTGOT is the gp value for that object. */ Elf64_Dyn *dyn = (Elf64_Dyn *)(p_dynamic->p_vaddr + load_base); for (; dyn->d_tag != DT_NULL; ++dyn) if (dyn->d_tag == DT_PLTGOT) { /* On IA-64, _DYNAMIC is writable and GLIBC has relocated it. */ di->gp = dyn->d_un.d_ptr; break; } } else /* Otherwise this is a static executable with no _DYNAMIC. The gp is constant program-wide. */ di->gp = current_gp(); di->format = UNW_INFO_FORMAT_TABLE; di->start_ip = p_text->p_vaddr + load_base; di->end_ip = p_text->p_vaddr + load_base + p_text->p_memsz; di->u.ti.name_ptr = (unw_word_t) info->dlpi_name; di->u.ti.table_data = (void *) (p_unwind->p_vaddr + load_base); di->u.ti.table_len = p_unwind->p_memsz / sizeof (unw_word_t); di->u.ti.segbase = segbase; Debug (16, "found table `%s': segbase=%lx, len=%lu, gp=%lx, " "table_data=%p\n", (char *) di->u.ti.name_ptr, di->u.ti.segbase, di->u.ti.table_len, di->gp, di->u.ti.table_data); return 1; } # ifdef HAVE_DL_PHDR_REMOVALS_COUNTER static inline int validate_cache (unw_addr_space_t as) { /* Note: we don't need to serialize here with respect to dl_iterate_phdr() because if somebody were to remove an object that is required to complete the unwind on whose behalf we're validating the cache here, we'd be hosed anyhow. What we're guarding against here is the case where library FOO gets mapped, unwind info for FOO gets cached, FOO gets unmapped, BAR gets mapped in the place where FOO was and then we unwind across a function in FOO. Since no thread can execute in BAR before FOO has been removed, we are guaranteed that dl_phdr_removals_counter() would have been incremented before we get here. */ unsigned long long removals = dl_phdr_removals_counter (); if (removals == as->shared_object_removals) return 1; as->shared_object_removals = removals; unw_flush_cache (as, 0, 0); return -1; } # else /* !HAVE_DL_PHDR_REMOVALS_COUNTER */ /* Check whether any phdrs have been removed since we last flushed the cache. If so we flush the cache and return -1, if not, we do nothing and return 1. */ static int check_callback (struct dl_phdr_info *info, size_t size, void *ptr) { # ifdef HAVE_STRUCT_DL_PHDR_INFO_DLPI_SUBS unw_addr_space_t as = ptr; if (size < offsetof (struct dl_phdr_info, dlpi_subs) + sizeof (info->dlpi_subs)) /* It would be safer to flush the cache here, but that would disable caching for older libc's which would be incompatible with the behavior of older versions of libunwind so we return 1 instead and hope nobody runs into stale cache info... */ return 1; if (info->dlpi_subs == as->shared_object_removals) return 1; as->shared_object_removals = info->dlpi_subs; unw_flush_cache (as, 0, 0); return -1; /* indicate that there were removals */ # else return 1; # endif } static inline int validate_cache (unw_addr_space_t as) { intrmask_t saved_mask; int ret; SIGPROCMASK (SIG_SETMASK, &unwi_full_mask, &saved_mask); ret = dl_iterate_phdr (check_callback, as); SIGPROCMASK (SIG_SETMASK, &saved_mask, NULL); return ret; } # endif /* HAVE_DL_PHDR_REMOVALS_COUNTER */ # elif defined(HAVE_DLMODINFO) /* Support for HP-UX-style dlmodinfo() */ # include <dlfcn.h> static inline int validate_cache (unw_addr_space_t as) { return 1; } # endif /* !HAVE_DLMODINFO */ HIDDEN int tdep_find_proc_info (unw_addr_space_t as, unw_word_t ip, unw_proc_info_t *pi, int need_unwind_info, void *arg) { # if defined(HAVE_DL_ITERATE_PHDR) unw_dyn_info_t di, *dip = &di; intrmask_t saved_mask; int ret; di.u.ti.segbase = ip; /* this is cheap... */ SIGPROCMASK (SIG_SETMASK, &unwi_full_mask, &saved_mask); ret = dl_iterate_phdr (callback, &di); SIGPROCMASK (SIG_SETMASK, &saved_mask, NULL); if (ret <= 0) { if (!kernel_table.u.ti.table_data) { if ((ret = get_kernel_table (&kernel_table)) < 0) return ret; } if (ip < kernel_table.start_ip || ip >= kernel_table.end_ip) return -UNW_ENOINFO; dip = &kernel_table; } # elif defined(HAVE_DLMODINFO) # define UNWIND_TBL_32BIT 0x8000000000000000 struct load_module_desc lmd; unw_dyn_info_t di, *dip = &di; struct unwind_header { uint64_t header_version; uint64_t start_offset; uint64_t end_offset; } *uhdr; if (!dlmodinfo (ip, &lmd, sizeof (lmd), NULL, 0, 0)) return -UNW_ENOINFO; di.format = UNW_INFO_FORMAT_TABLE; di.start_ip = lmd.text_base; di.end_ip = lmd.text_base + lmd.text_size; di.gp = lmd.linkage_ptr; di.u.ti.name_ptr = 0; /* no obvious table-name available */ di.u.ti.segbase = lmd.text_base; uhdr = (struct unwind_header *) lmd.unwind_base; if ((uhdr->header_version & ~UNWIND_TBL_32BIT) != 1 && (uhdr->header_version & ~UNWIND_TBL_32BIT) != 2) { Debug (1, "encountered unknown unwind header version %ld\n", (long) (uhdr->header_version & ~UNWIND_TBL_32BIT)); return -UNW_EBADVERSION; } if (uhdr->header_version & UNWIND_TBL_32BIT) { Debug (1, "32-bit unwind tables are not supported yet\n"); return -UNW_EINVAL; } di.u.ti.table_data = (unw_word_t *) (di.u.ti.segbase + uhdr->start_offset); di.u.ti.table_len = ((uhdr->end_offset - uhdr->start_offset) / sizeof (unw_word_t)); Debug (16, "found table `%s': segbase=%lx, len=%lu, gp=%lx, " "table_data=%p\n", (char *) di.u.ti.name_ptr, di.u.ti.segbase, di.u.ti.table_len, di.gp, di.u.ti.table_data); # endif /* now search the table: */ return tdep_search_unwind_table (as, ip, dip, pi, need_unwind_info, arg); } /* Returns 1 if the cache is up-to-date or -1 if the cache contained stale data and had to be flushed. */ HIDDEN int ia64_local_validate_cache (unw_addr_space_t as, void *arg) { return validate_cache (as); } #endif /* !UNW_REMOTE_ONLY */
-1
dotnet/runtime
66,462
Support using the system version of brotli
This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
omajid
2022-03-10T17:19:11Z
2022-03-23T03:49:50Z
c3e1d21c2fb30436ae24ef7ef4f458e3270bb7e3
5ca9223639700750ff12bb1fed9fa6e397062b78
Support using the system version of brotli . This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
./src/coreclr/md/CMakeLists.txt
add_compile_definitions(FEATURE_METADATA_EMIT) add_compile_definitions(FEATURE_METADATA_INTERNAL_APIS) add_compile_definitions($<$<OR:$<BOOL:$<TARGET_PROPERTY:DAC_COMPONENT>>,$<BOOL:$<TARGET_PROPERTY:DBI_COMPONENT>>>:FEATURE_METADATA_EMIT_IN_DEBUGGER>) add_compile_definitions($<$<NOT:$<OR:$<BOOL:$<TARGET_PROPERTY:DAC_COMPONENT>>,$<BOOL:$<TARGET_PROPERTY:DBI_COMPONENT>>>>:FEATURE_METADATA_IN_VM>) add_compile_definitions($<$<BOOL:$<TARGET_PROPERTY:DBI_COMPONENT>>:FEATURE_METADATA_CUSTOM_DATA_SOURCE>) add_compile_definitions($<$<BOOL:$<TARGET_PROPERTY:DBI_COMPONENT>>:FEATURE_METADATA_DEBUGGEE_DATA_SOURCE>) add_compile_definitions($<$<BOOL:$<TARGET_PROPERTY:DBI_COMPONENT>>:FEATURE_METADATA_LOAD_TRUSTED_IMAGES>) add_compile_definitions($<$<BOOL:$<TARGET_PROPERTY:DBI_COMPONENT>>:FEATURE_METADATA_RELEASE_MEMORY_ON_REOPEN>) add_compile_definitions($<$<NOT:$<OR:$<BOOL:$<TARGET_PROPERTY:DAC_COMPONENT>>,$<BOOL:$<TARGET_PROPERTY:DBI_COMPONENT>>>>:FEATURE_METADATA_VERIFY_LAYOUTS>) if (CLR_CMAKE_HOST_WIN32) set(CMAKE_MSVC_RUNTIME_LIBRARY MultiThreaded$<$<AND:$<BOOL:$<TARGET_PROPERTY:DBI_COMPONENT>>,$<CONFIG:DEBUG>>:Debug>) endif() add_subdirectory(compiler) add_subdirectory(runtime) add_subdirectory(enc) add_subdirectory(ceefilegen) add_subdirectory(datasource) add_subdirectory(staticmd)
add_compile_definitions(FEATURE_METADATA_EMIT) add_compile_definitions(FEATURE_METADATA_INTERNAL_APIS) add_compile_definitions($<$<OR:$<BOOL:$<TARGET_PROPERTY:DAC_COMPONENT>>,$<BOOL:$<TARGET_PROPERTY:DBI_COMPONENT>>>:FEATURE_METADATA_EMIT_IN_DEBUGGER>) add_compile_definitions($<$<NOT:$<OR:$<BOOL:$<TARGET_PROPERTY:DAC_COMPONENT>>,$<BOOL:$<TARGET_PROPERTY:DBI_COMPONENT>>>>:FEATURE_METADATA_IN_VM>) add_compile_definitions($<$<BOOL:$<TARGET_PROPERTY:DBI_COMPONENT>>:FEATURE_METADATA_CUSTOM_DATA_SOURCE>) add_compile_definitions($<$<BOOL:$<TARGET_PROPERTY:DBI_COMPONENT>>:FEATURE_METADATA_DEBUGGEE_DATA_SOURCE>) add_compile_definitions($<$<BOOL:$<TARGET_PROPERTY:DBI_COMPONENT>>:FEATURE_METADATA_LOAD_TRUSTED_IMAGES>) add_compile_definitions($<$<BOOL:$<TARGET_PROPERTY:DBI_COMPONENT>>:FEATURE_METADATA_RELEASE_MEMORY_ON_REOPEN>) add_compile_definitions($<$<NOT:$<OR:$<BOOL:$<TARGET_PROPERTY:DAC_COMPONENT>>,$<BOOL:$<TARGET_PROPERTY:DBI_COMPONENT>>>>:FEATURE_METADATA_VERIFY_LAYOUTS>) if (CLR_CMAKE_HOST_WIN32) set(CMAKE_MSVC_RUNTIME_LIBRARY MultiThreaded$<$<AND:$<BOOL:$<TARGET_PROPERTY:DBI_COMPONENT>>,$<CONFIG:DEBUG>>:Debug>) endif() add_subdirectory(compiler) add_subdirectory(runtime) add_subdirectory(enc) add_subdirectory(ceefilegen) add_subdirectory(datasource) add_subdirectory(staticmd)
-1
dotnet/runtime
66,462
Support using the system version of brotli
This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
omajid
2022-03-10T17:19:11Z
2022-03-23T03:49:50Z
c3e1d21c2fb30436ae24ef7ef4f458e3270bb7e3
5ca9223639700750ff12bb1fed9fa6e397062b78
Support using the system version of brotli . This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
./src/native/external/libunwind/src/tilegx/Lregs.c
#define UNW_LOCAL_ONLY #include <libunwind.h> #if defined(UNW_LOCAL_ONLY) && !defined(UNW_REMOTE_ONLY) #include "Gregs.c" #endif
#define UNW_LOCAL_ONLY #include <libunwind.h> #if defined(UNW_LOCAL_ONLY) && !defined(UNW_REMOTE_ONLY) #include "Gregs.c" #endif
-1
dotnet/runtime
66,462
Support using the system version of brotli
This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
omajid
2022-03-10T17:19:11Z
2022-03-23T03:49:50Z
c3e1d21c2fb30436ae24ef7ef4f458e3270bb7e3
5ca9223639700750ff12bb1fed9fa6e397062b78
Support using the system version of brotli . This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
./src/mono/mono/eventpipe/test/ep-test-driver.c
#define DRIVER_EXTERNAL_TESTS #define DRIVER_NAME "eventpipe-tests" #include "ep-tests.h" #include "mono/eglib/test/driver.c"
#define DRIVER_EXTERNAL_TESTS #define DRIVER_NAME "eventpipe-tests" #include "ep-tests.h" #include "mono/eglib/test/driver.c"
-1
dotnet/runtime
66,462
Support using the system version of brotli
This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
omajid
2022-03-10T17:19:11Z
2022-03-23T03:49:50Z
c3e1d21c2fb30436ae24ef7ef4f458e3270bb7e3
5ca9223639700750ff12bb1fed9fa6e397062b78
Support using the system version of brotli . This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
./src/mono/mono/utils/mono-linked-list-set.c
/** * \file * A lock-free split ordered list. * * Author: * Rodrigo Kumpera ([email protected]) * * (C) 2011 Novell, Inc * * This is an implementation of Maged Michael's lock-free linked-list set. * For more details see: * "High Performance Dynamic Lock-Free Hash Tables and List-Based Sets" * Maged M. Michael 2002 * * http://www.research.ibm.com/people/m/michael/spaa-2002.pdf */ #include <mono/utils/mono-linked-list-set.h> #include <mono/utils/atomic.h> static gpointer mask (gpointer n, uintptr_t bit) { return (gpointer)(((uintptr_t)n) | bit); } gpointer mono_lls_get_hazardous_pointer_with_mask (gpointer volatile *pp, MonoThreadHazardPointers *hp, int hazard_index) { gpointer p; for (;;) { /* Get the pointer */ p = *pp; /* If we don't have hazard pointers just return the pointer. */ if (!hp) return p; /* Make it hazardous */ mono_hazard_pointer_set (hp, hazard_index, mono_lls_pointer_unmask (p)); mono_memory_barrier (); /* Check that it's still the same. If not, try again. */ if (*pp != p) { mono_hazard_pointer_clear (hp, hazard_index); continue; } break; } return p; } /* Initialize @list and will use @free_node_func to release memory. If @free_node_func is null the caller is responsible for releasing node memory. */ void mono_lls_init (MonoLinkedListSet *list, void (*free_node_func)(void *)) { list->head = NULL; list->free_node_func = free_node_func; } /* Search @list for element with key @key. The nodes next, cur and prev are returned in @hp. Returns true if a node with key @key was found. */ gboolean mono_lls_find (MonoLinkedListSet *list, MonoThreadHazardPointers *hp, uintptr_t key) { MonoLinkedListSetNode *cur, *next; MonoLinkedListSetNode **prev; uintptr_t cur_key; try_again: prev = &list->head; /* * prev is not really a hazardous pointer, but we return prev * in hazard pointer 2, so we set it here. Note also that * prev is not a pointer to a node. We use here the fact that * the first element in a node is the next pointer, so it * works, but it's not pretty. */ mono_hazard_pointer_set (hp, 2, prev); cur = (MonoLinkedListSetNode *) mono_lls_get_hazardous_pointer_with_mask ((gpointer*)prev, hp, 1); while (1) { if (cur == NULL) return FALSE; next = (MonoLinkedListSetNode *) mono_lls_get_hazardous_pointer_with_mask ((gpointer*)&cur->next, hp, 0); cur_key = cur->key; /* * We need to make sure that we dereference prev below * after reading cur->next above, so we need a read * barrier. */ mono_memory_read_barrier (); if (*prev != cur) goto try_again; if (!mono_lls_pointer_get_mark (next)) { if (cur_key >= key) return cur_key == key; prev = &cur->next; mono_hazard_pointer_set (hp, 2, cur); } else { next = (MonoLinkedListSetNode *) mono_lls_pointer_unmask (next); if (mono_atomic_cas_ptr ((volatile gpointer*)prev, next, cur) == cur) { /* The hazard pointer must be cleared after the CAS. */ mono_memory_write_barrier (); mono_hazard_pointer_clear (hp, 1); if (list->free_node_func) mono_thread_hazardous_queue_free (cur, list->free_node_func); } else goto try_again; } cur = (MonoLinkedListSetNode *) mono_lls_pointer_unmask (next); mono_hazard_pointer_set (hp, 1, cur); } } /* Insert @value into @list. The nodes value, cur and prev are returned in @hp. Return true if @value was inserted by this call. If it returns FALSE, it's the caller resposibility to release memory. */ gboolean mono_lls_insert (MonoLinkedListSet *list, MonoThreadHazardPointers *hp, MonoLinkedListSetNode *value) { MonoLinkedListSetNode *cur, **prev; /*We must do a store barrier before inserting to make sure all values in @node are globally visible.*/ mono_memory_barrier (); while (1) { if (mono_lls_find (list, hp, value->key)) return FALSE; cur = (MonoLinkedListSetNode *) mono_hazard_pointer_get_val (hp, 1); prev = (MonoLinkedListSetNode **) mono_hazard_pointer_get_val (hp, 2); value->next = cur; mono_hazard_pointer_set (hp, 0, value); /* The CAS must happen after setting the hazard pointer. */ mono_memory_write_barrier (); if (mono_atomic_cas_ptr ((volatile gpointer*)prev, value, cur) == cur) return TRUE; } } /* Search @list for element with key @key and remove it. The nodes next, cur and prev are returned in @hp Returns true if @value was removed by this call. */ gboolean mono_lls_remove (MonoLinkedListSet *list, MonoThreadHazardPointers *hp, MonoLinkedListSetNode *value) { MonoLinkedListSetNode *cur, **prev, *next; while (1) { if (!mono_lls_find (list, hp, value->key)) return FALSE; next = (MonoLinkedListSetNode *) mono_hazard_pointer_get_val (hp, 0); cur = (MonoLinkedListSetNode *) mono_hazard_pointer_get_val (hp, 1); prev = (MonoLinkedListSetNode **) mono_hazard_pointer_get_val (hp, 2); g_assert (cur == value); if (mono_atomic_cas_ptr ((volatile gpointer*)&cur->next, mask (next, 1), next) != next) continue; /* The second CAS must happen before the first. */ mono_memory_write_barrier (); if (mono_atomic_cas_ptr ((volatile gpointer*)prev, mono_lls_pointer_unmask (next), cur) == cur) { /* The CAS must happen before the hazard pointer clear. */ mono_memory_write_barrier (); mono_hazard_pointer_clear (hp, 1); if (list->free_node_func) mono_thread_hazardous_queue_free (value, list->free_node_func); } else mono_lls_find (list, hp, value->key); return TRUE; } }
/** * \file * A lock-free split ordered list. * * Author: * Rodrigo Kumpera ([email protected]) * * (C) 2011 Novell, Inc * * This is an implementation of Maged Michael's lock-free linked-list set. * For more details see: * "High Performance Dynamic Lock-Free Hash Tables and List-Based Sets" * Maged M. Michael 2002 * * http://www.research.ibm.com/people/m/michael/spaa-2002.pdf */ #include <mono/utils/mono-linked-list-set.h> #include <mono/utils/atomic.h> static gpointer mask (gpointer n, uintptr_t bit) { return (gpointer)(((uintptr_t)n) | bit); } gpointer mono_lls_get_hazardous_pointer_with_mask (gpointer volatile *pp, MonoThreadHazardPointers *hp, int hazard_index) { gpointer p; for (;;) { /* Get the pointer */ p = *pp; /* If we don't have hazard pointers just return the pointer. */ if (!hp) return p; /* Make it hazardous */ mono_hazard_pointer_set (hp, hazard_index, mono_lls_pointer_unmask (p)); mono_memory_barrier (); /* Check that it's still the same. If not, try again. */ if (*pp != p) { mono_hazard_pointer_clear (hp, hazard_index); continue; } break; } return p; } /* Initialize @list and will use @free_node_func to release memory. If @free_node_func is null the caller is responsible for releasing node memory. */ void mono_lls_init (MonoLinkedListSet *list, void (*free_node_func)(void *)) { list->head = NULL; list->free_node_func = free_node_func; } /* Search @list for element with key @key. The nodes next, cur and prev are returned in @hp. Returns true if a node with key @key was found. */ gboolean mono_lls_find (MonoLinkedListSet *list, MonoThreadHazardPointers *hp, uintptr_t key) { MonoLinkedListSetNode *cur, *next; MonoLinkedListSetNode **prev; uintptr_t cur_key; try_again: prev = &list->head; /* * prev is not really a hazardous pointer, but we return prev * in hazard pointer 2, so we set it here. Note also that * prev is not a pointer to a node. We use here the fact that * the first element in a node is the next pointer, so it * works, but it's not pretty. */ mono_hazard_pointer_set (hp, 2, prev); cur = (MonoLinkedListSetNode *) mono_lls_get_hazardous_pointer_with_mask ((gpointer*)prev, hp, 1); while (1) { if (cur == NULL) return FALSE; next = (MonoLinkedListSetNode *) mono_lls_get_hazardous_pointer_with_mask ((gpointer*)&cur->next, hp, 0); cur_key = cur->key; /* * We need to make sure that we dereference prev below * after reading cur->next above, so we need a read * barrier. */ mono_memory_read_barrier (); if (*prev != cur) goto try_again; if (!mono_lls_pointer_get_mark (next)) { if (cur_key >= key) return cur_key == key; prev = &cur->next; mono_hazard_pointer_set (hp, 2, cur); } else { next = (MonoLinkedListSetNode *) mono_lls_pointer_unmask (next); if (mono_atomic_cas_ptr ((volatile gpointer*)prev, next, cur) == cur) { /* The hazard pointer must be cleared after the CAS. */ mono_memory_write_barrier (); mono_hazard_pointer_clear (hp, 1); if (list->free_node_func) mono_thread_hazardous_queue_free (cur, list->free_node_func); } else goto try_again; } cur = (MonoLinkedListSetNode *) mono_lls_pointer_unmask (next); mono_hazard_pointer_set (hp, 1, cur); } } /* Insert @value into @list. The nodes value, cur and prev are returned in @hp. Return true if @value was inserted by this call. If it returns FALSE, it's the caller resposibility to release memory. */ gboolean mono_lls_insert (MonoLinkedListSet *list, MonoThreadHazardPointers *hp, MonoLinkedListSetNode *value) { MonoLinkedListSetNode *cur, **prev; /*We must do a store barrier before inserting to make sure all values in @node are globally visible.*/ mono_memory_barrier (); while (1) { if (mono_lls_find (list, hp, value->key)) return FALSE; cur = (MonoLinkedListSetNode *) mono_hazard_pointer_get_val (hp, 1); prev = (MonoLinkedListSetNode **) mono_hazard_pointer_get_val (hp, 2); value->next = cur; mono_hazard_pointer_set (hp, 0, value); /* The CAS must happen after setting the hazard pointer. */ mono_memory_write_barrier (); if (mono_atomic_cas_ptr ((volatile gpointer*)prev, value, cur) == cur) return TRUE; } } /* Search @list for element with key @key and remove it. The nodes next, cur and prev are returned in @hp Returns true if @value was removed by this call. */ gboolean mono_lls_remove (MonoLinkedListSet *list, MonoThreadHazardPointers *hp, MonoLinkedListSetNode *value) { MonoLinkedListSetNode *cur, **prev, *next; while (1) { if (!mono_lls_find (list, hp, value->key)) return FALSE; next = (MonoLinkedListSetNode *) mono_hazard_pointer_get_val (hp, 0); cur = (MonoLinkedListSetNode *) mono_hazard_pointer_get_val (hp, 1); prev = (MonoLinkedListSetNode **) mono_hazard_pointer_get_val (hp, 2); g_assert (cur == value); if (mono_atomic_cas_ptr ((volatile gpointer*)&cur->next, mask (next, 1), next) != next) continue; /* The second CAS must happen before the first. */ mono_memory_write_barrier (); if (mono_atomic_cas_ptr ((volatile gpointer*)prev, mono_lls_pointer_unmask (next), cur) == cur) { /* The CAS must happen before the hazard pointer clear. */ mono_memory_write_barrier (); mono_hazard_pointer_clear (hp, 1); if (list->free_node_func) mono_thread_hazardous_queue_free (value, list->free_node_func); } else mono_lls_find (list, hp, value->key); return TRUE; } }
-1
dotnet/runtime
66,462
Support using the system version of brotli
This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
omajid
2022-03-10T17:19:11Z
2022-03-23T03:49:50Z
c3e1d21c2fb30436ae24ef7ef4f458e3270bb7e3
5ca9223639700750ff12bb1fed9fa6e397062b78
Support using the system version of brotli . This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
./src/libraries/System.Private.Xml/tests/Xslt/TestFiles/TestData/xsltc/baseline/infft6.txt
/class:fft6 /out:fft6.dll fft6.xsl
/class:fft6 /out:fft6.dll fft6.xsl
-1
dotnet/runtime
66,462
Support using the system version of brotli
This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
omajid
2022-03-10T17:19:11Z
2022-03-23T03:49:50Z
c3e1d21c2fb30436ae24ef7ef4f458e3270bb7e3
5ca9223639700750ff12bb1fed9fa6e397062b78
Support using the system version of brotli . This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
./src/native/libs/System.Security.Cryptography.Native.Apple/pal_keychain_macos.c
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include "pal_keychain_macos.h" #include "pal_utilities.h" int32_t AppleCryptoNative_SecKeychainItemCopyKeychain(SecKeychainItemRef item, SecKeychainRef* pKeychainOut) { if (pKeychainOut != NULL) *pKeychainOut = NULL; if (item == NULL) return errSecNoSuchKeychain; CFTypeID itemType = CFGetTypeID(item); if (itemType == SecKeyGetTypeID() || itemType == SecIdentityGetTypeID() || itemType == SecCertificateGetTypeID()) { OSStatus status = SecKeychainItemCopyKeychain(item, pKeychainOut); if (status == noErr) { return status; } // Acceptable error codes if (status == errSecNoSuchKeychain || status == errSecInvalidItemRef) { return noErr; } return status; } return errSecParam; } int32_t AppleCryptoNative_SecKeychainCreate(const char* pathName, uint32_t passphraseLength, const uint8_t* passphraseUtf8, SecKeychainRef* pKeychainOut) { return SecKeychainCreate(pathName, passphraseLength, passphraseUtf8, false, NULL, pKeychainOut); } int32_t AppleCryptoNative_SecKeychainDelete(SecKeychainRef keychain) { return SecKeychainDelete(keychain); } int32_t AppleCryptoNative_SecKeychainCopyDefault(SecKeychainRef* pKeychainOut) { if (pKeychainOut != NULL) *pKeychainOut = NULL; return SecKeychainCopyDefault(pKeychainOut); } int32_t AppleCryptoNative_SecKeychainOpen(const char* pszKeychainPath, SecKeychainRef* pKeychainOut) { if (pKeychainOut != NULL) *pKeychainOut = NULL; if (pszKeychainPath == NULL) return errSecParam; return SecKeychainOpen(pszKeychainPath, pKeychainOut); } int32_t AppleCryptoNative_SecKeychainUnlock(SecKeychainRef keychain, uint32_t passphraseLength, const uint8_t* passphraseUtf8) { return SecKeychainUnlock(keychain, passphraseLength, passphraseUtf8, true); } int32_t AppleCryptoNative_SetKeychainNeverLock(SecKeychainRef keychain) { SecKeychainSettings settings = { .version = SEC_KEYCHAIN_SETTINGS_VERS1, .useLockInterval = 0, .lockOnSleep = 0, .lockInterval = INT_MAX, }; return SecKeychainSetSettings(keychain, &settings); } static int32_t EnumerateKeychain(SecKeychainRef keychain, CFStringRef matchType, CFArrayRef* pCertsOut, int32_t* pOSStatus) { if (pCertsOut != NULL) *pCertsOut = NULL; if (pOSStatus != NULL) *pOSStatus = noErr; assert(matchType != NULL); if (keychain == NULL || pCertsOut == NULL || pOSStatus == NULL) return -1; CFMutableDictionaryRef query = CFDictionaryCreateMutable( kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); if (query == NULL) return -2; int32_t ret = 0; CFTypeRef result = NULL; const void* constKeychain = keychain; CFArrayRef searchList = CFArrayCreate(NULL, &constKeychain, 1, &kCFTypeArrayCallBacks); if (searchList == NULL) { ret = -3; } else { CFDictionarySetValue(query, kSecReturnRef, kCFBooleanTrue); CFDictionarySetValue(query, kSecMatchLimit, kSecMatchLimitAll); CFDictionarySetValue(query, kSecClass, matchType); CFDictionarySetValue(query, kSecMatchSearchList, searchList); *pOSStatus = SecItemCopyMatching(query, &result); if (*pOSStatus == noErr) { if (result == NULL || CFGetTypeID(result) != CFArrayGetTypeID()) { ret = -3; } else { CFRetain(result); *pCertsOut = (CFArrayRef)result; ret = 1; } } else if (*pOSStatus == errSecItemNotFound) { *pOSStatus = noErr; ret = 1; } else { ret = 0; } } if (searchList != NULL) CFRelease(searchList); if (result != NULL) CFRelease(result); CFRelease(query); return ret; } int32_t AppleCryptoNative_SecKeychainEnumerateCerts(SecKeychainRef keychain, CFArrayRef* pCertsOut, int32_t* pOSStatus) { return EnumerateKeychain(keychain, kSecClassCertificate, pCertsOut, pOSStatus); } int32_t AppleCryptoNative_SecKeychainEnumerateIdentities(SecKeychainRef keychain, CFArrayRef* pIdentitiesOut, int32_t* pOSStatus) { return EnumerateKeychain(keychain, kSecClassIdentity, pIdentitiesOut, pOSStatus); } static OSStatus DeleteInKeychain(CFTypeRef needle, SecKeychainRef haystack) { CFMutableDictionaryRef query = CFDictionaryCreateMutable( kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); if (query == NULL) return errSecAllocate; const void* constHaystack = haystack; CFArrayRef searchList = CFArrayCreate(NULL, &constHaystack, 1, &kCFTypeArrayCallBacks); if (searchList == NULL) { CFRelease(query); return errSecAllocate; } CFArrayRef itemMatch = CFArrayCreate(NULL, (const void**)(&needle), 1, &kCFTypeArrayCallBacks); if (itemMatch == NULL) { CFRelease(searchList); CFRelease(query); return errSecAllocate; } CFDictionarySetValue(query, kSecReturnRef, kCFBooleanTrue); CFDictionarySetValue(query, kSecMatchSearchList, searchList); CFDictionarySetValue(query, kSecMatchItemList, itemMatch); CFDictionarySetValue(query, kSecClass, kSecClassIdentity); OSStatus status = SecItemDelete(query); if (status == errSecItemNotFound) { status = noErr; } if (status == noErr) { CFDictionarySetValue(query, kSecClass, kSecClassCertificate); status = SecItemDelete(query); } if (status == errSecItemNotFound) { status = noErr; } CFRelease(itemMatch); CFRelease(searchList); CFRelease(query); return status; } static bool IsCertInKeychain(CFTypeRef needle, SecKeychainRef haystack) { CFMutableDictionaryRef query = CFDictionaryCreateMutable( kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); if (query == NULL) return errSecAllocate; const void* constHaystack = haystack; CFTypeRef result = NULL; CFArrayRef searchList = CFArrayCreate(NULL, &constHaystack, 1, &kCFTypeArrayCallBacks); if (searchList == NULL) { CFRelease(query); return errSecAllocate; } CFArrayRef itemMatch = CFArrayCreate(NULL, (const void**)(&needle), 1, &kCFTypeArrayCallBacks); if (itemMatch == NULL) { CFRelease(searchList); CFRelease(query); return errSecAllocate; } CFDictionarySetValue(query, kSecReturnRef, kCFBooleanTrue); CFDictionarySetValue(query, kSecMatchSearchList, searchList); CFDictionarySetValue(query, kSecMatchItemList, itemMatch); CFDictionarySetValue(query, kSecClass, kSecClassCertificate); OSStatus status = SecItemCopyMatching(query, &result); bool ret = true; if (status == errSecItemNotFound) { ret = false; } CFRelease(itemMatch); CFRelease(searchList); CFRelease(query); return ret; } static int32_t CheckTrustSettings(SecCertificateRef cert) { const int32_t kErrorUserTrust = 2; const int32_t kErrorAdminTrust = 3; OSStatus status = noErr; CFArrayRef settings = NULL; if (status == noErr) { status = SecTrustSettingsCopyTrustSettings(cert, kSecTrustSettingsDomainUser, &settings); } if (settings != NULL) { CFRelease(settings); settings = NULL; } if (status == noErr) { return kErrorUserTrust; } status = SecTrustSettingsCopyTrustSettings(cert, kSecTrustSettingsDomainAdmin, &settings); if (settings != NULL) { CFRelease(settings); settings = NULL; } if (status == noErr) { return kErrorAdminTrust; } return 0; } int32_t AppleCryptoNative_X509StoreAddCertificate(CFTypeRef certOrIdentity, SecKeychainRef keychain, int32_t* pOSStatus) { if (pOSStatus != NULL) *pOSStatus = noErr; if (certOrIdentity == NULL || keychain == NULL || pOSStatus == NULL) return -1; SecCertificateRef cert = NULL; SecKeyRef privateKey = NULL; CFTypeID inputType = CFGetTypeID(certOrIdentity); OSStatus status = noErr; if (inputType == SecCertificateGetTypeID()) { cert = (SecCertificateRef)CONST_CAST(void*, certOrIdentity); CFRetain(cert); } else if (inputType == SecIdentityGetTypeID()) { SecIdentityRef identity = (SecIdentityRef)CONST_CAST(void*, certOrIdentity); status = SecIdentityCopyCertificate(identity, &cert); if (status == noErr) { status = SecIdentityCopyPrivateKey(identity, &privateKey); } } else { return -1; } SecKeychainItemRef itemCopy = NULL; // Copy the private key into the new keychain first, because it can fail due to // non-exportability. Certificates can only fail for things like I/O errors saving the // keychain back to disk. if (status == noErr && privateKey != NULL) { status = SecKeychainItemCreateCopy((SecKeychainItemRef)privateKey, keychain, NULL, &itemCopy); } if (status == errSecDuplicateItem) { status = noErr; } // Since we don't care about the itemCopy we'd ideally pass NULL to SecKeychainItemCreateCopy, // but even though the documentation says it can be null, clang gives an error that null isn't // allowed. if (itemCopy != NULL) { CFRelease(itemCopy); itemCopy = NULL; } if (status == noErr && cert != NULL) { status = SecKeychainItemCreateCopy((SecKeychainItemRef)cert, keychain, NULL, &itemCopy); } if (status == errSecDuplicateItem) { status = noErr; } if (itemCopy != NULL) { CFRelease(itemCopy); itemCopy = NULL; } if (privateKey != NULL) { CFRelease(privateKey); privateKey = NULL; } if (cert != NULL) { CFRelease(cert); cert = NULL; } *pOSStatus = status; return status == noErr; } int32_t AppleCryptoNative_X509StoreRemoveCertificate(CFTypeRef certOrIdentity, SecKeychainRef keychain, uint8_t isReadOnlyMode, int32_t* pOSStatus) { if (pOSStatus != NULL) *pOSStatus = noErr; if (certOrIdentity == NULL || keychain == NULL || pOSStatus == NULL) return -1; SecCertificateRef cert = NULL; SecIdentityRef identity = NULL; CFTypeID inputType = CFGetTypeID(certOrIdentity); OSStatus status = noErr; if (inputType == SecCertificateGetTypeID()) { cert = (SecCertificateRef)CONST_CAST(void*, certOrIdentity); CFRetain(cert); } else if (inputType == SecIdentityGetTypeID()) { identity = (SecIdentityRef)CONST_CAST(void*, certOrIdentity); status = SecIdentityCopyCertificate(identity, &cert); if (status != noErr) { *pOSStatus = status; return 0; } } else { return -1; } const int32_t kErrorReadonlyDelete = 4; int32_t ret = 0; if (isReadOnlyMode) { ret = kErrorReadonlyDelete; } else { ret = CheckTrustSettings(cert); } if (ret != 0) { if (!IsCertInKeychain(cert, keychain)) { CFRelease(cert); return 1; } CFRelease(cert); return ret; } *pOSStatus = DeleteInKeychain(cert, keychain); CFRelease(cert); return *pOSStatus == noErr; }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include "pal_keychain_macos.h" #include "pal_utilities.h" int32_t AppleCryptoNative_SecKeychainItemCopyKeychain(SecKeychainItemRef item, SecKeychainRef* pKeychainOut) { if (pKeychainOut != NULL) *pKeychainOut = NULL; if (item == NULL) return errSecNoSuchKeychain; CFTypeID itemType = CFGetTypeID(item); if (itemType == SecKeyGetTypeID() || itemType == SecIdentityGetTypeID() || itemType == SecCertificateGetTypeID()) { OSStatus status = SecKeychainItemCopyKeychain(item, pKeychainOut); if (status == noErr) { return status; } // Acceptable error codes if (status == errSecNoSuchKeychain || status == errSecInvalidItemRef) { return noErr; } return status; } return errSecParam; } int32_t AppleCryptoNative_SecKeychainCreate(const char* pathName, uint32_t passphraseLength, const uint8_t* passphraseUtf8, SecKeychainRef* pKeychainOut) { return SecKeychainCreate(pathName, passphraseLength, passphraseUtf8, false, NULL, pKeychainOut); } int32_t AppleCryptoNative_SecKeychainDelete(SecKeychainRef keychain) { return SecKeychainDelete(keychain); } int32_t AppleCryptoNative_SecKeychainCopyDefault(SecKeychainRef* pKeychainOut) { if (pKeychainOut != NULL) *pKeychainOut = NULL; return SecKeychainCopyDefault(pKeychainOut); } int32_t AppleCryptoNative_SecKeychainOpen(const char* pszKeychainPath, SecKeychainRef* pKeychainOut) { if (pKeychainOut != NULL) *pKeychainOut = NULL; if (pszKeychainPath == NULL) return errSecParam; return SecKeychainOpen(pszKeychainPath, pKeychainOut); } int32_t AppleCryptoNative_SecKeychainUnlock(SecKeychainRef keychain, uint32_t passphraseLength, const uint8_t* passphraseUtf8) { return SecKeychainUnlock(keychain, passphraseLength, passphraseUtf8, true); } int32_t AppleCryptoNative_SetKeychainNeverLock(SecKeychainRef keychain) { SecKeychainSettings settings = { .version = SEC_KEYCHAIN_SETTINGS_VERS1, .useLockInterval = 0, .lockOnSleep = 0, .lockInterval = INT_MAX, }; return SecKeychainSetSettings(keychain, &settings); } static int32_t EnumerateKeychain(SecKeychainRef keychain, CFStringRef matchType, CFArrayRef* pCertsOut, int32_t* pOSStatus) { if (pCertsOut != NULL) *pCertsOut = NULL; if (pOSStatus != NULL) *pOSStatus = noErr; assert(matchType != NULL); if (keychain == NULL || pCertsOut == NULL || pOSStatus == NULL) return -1; CFMutableDictionaryRef query = CFDictionaryCreateMutable( kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); if (query == NULL) return -2; int32_t ret = 0; CFTypeRef result = NULL; const void* constKeychain = keychain; CFArrayRef searchList = CFArrayCreate(NULL, &constKeychain, 1, &kCFTypeArrayCallBacks); if (searchList == NULL) { ret = -3; } else { CFDictionarySetValue(query, kSecReturnRef, kCFBooleanTrue); CFDictionarySetValue(query, kSecMatchLimit, kSecMatchLimitAll); CFDictionarySetValue(query, kSecClass, matchType); CFDictionarySetValue(query, kSecMatchSearchList, searchList); *pOSStatus = SecItemCopyMatching(query, &result); if (*pOSStatus == noErr) { if (result == NULL || CFGetTypeID(result) != CFArrayGetTypeID()) { ret = -3; } else { CFRetain(result); *pCertsOut = (CFArrayRef)result; ret = 1; } } else if (*pOSStatus == errSecItemNotFound) { *pOSStatus = noErr; ret = 1; } else { ret = 0; } } if (searchList != NULL) CFRelease(searchList); if (result != NULL) CFRelease(result); CFRelease(query); return ret; } int32_t AppleCryptoNative_SecKeychainEnumerateCerts(SecKeychainRef keychain, CFArrayRef* pCertsOut, int32_t* pOSStatus) { return EnumerateKeychain(keychain, kSecClassCertificate, pCertsOut, pOSStatus); } int32_t AppleCryptoNative_SecKeychainEnumerateIdentities(SecKeychainRef keychain, CFArrayRef* pIdentitiesOut, int32_t* pOSStatus) { return EnumerateKeychain(keychain, kSecClassIdentity, pIdentitiesOut, pOSStatus); } static OSStatus DeleteInKeychain(CFTypeRef needle, SecKeychainRef haystack) { CFMutableDictionaryRef query = CFDictionaryCreateMutable( kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); if (query == NULL) return errSecAllocate; const void* constHaystack = haystack; CFArrayRef searchList = CFArrayCreate(NULL, &constHaystack, 1, &kCFTypeArrayCallBacks); if (searchList == NULL) { CFRelease(query); return errSecAllocate; } CFArrayRef itemMatch = CFArrayCreate(NULL, (const void**)(&needle), 1, &kCFTypeArrayCallBacks); if (itemMatch == NULL) { CFRelease(searchList); CFRelease(query); return errSecAllocate; } CFDictionarySetValue(query, kSecReturnRef, kCFBooleanTrue); CFDictionarySetValue(query, kSecMatchSearchList, searchList); CFDictionarySetValue(query, kSecMatchItemList, itemMatch); CFDictionarySetValue(query, kSecClass, kSecClassIdentity); OSStatus status = SecItemDelete(query); if (status == errSecItemNotFound) { status = noErr; } if (status == noErr) { CFDictionarySetValue(query, kSecClass, kSecClassCertificate); status = SecItemDelete(query); } if (status == errSecItemNotFound) { status = noErr; } CFRelease(itemMatch); CFRelease(searchList); CFRelease(query); return status; } static bool IsCertInKeychain(CFTypeRef needle, SecKeychainRef haystack) { CFMutableDictionaryRef query = CFDictionaryCreateMutable( kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); if (query == NULL) return errSecAllocate; const void* constHaystack = haystack; CFTypeRef result = NULL; CFArrayRef searchList = CFArrayCreate(NULL, &constHaystack, 1, &kCFTypeArrayCallBacks); if (searchList == NULL) { CFRelease(query); return errSecAllocate; } CFArrayRef itemMatch = CFArrayCreate(NULL, (const void**)(&needle), 1, &kCFTypeArrayCallBacks); if (itemMatch == NULL) { CFRelease(searchList); CFRelease(query); return errSecAllocate; } CFDictionarySetValue(query, kSecReturnRef, kCFBooleanTrue); CFDictionarySetValue(query, kSecMatchSearchList, searchList); CFDictionarySetValue(query, kSecMatchItemList, itemMatch); CFDictionarySetValue(query, kSecClass, kSecClassCertificate); OSStatus status = SecItemCopyMatching(query, &result); bool ret = true; if (status == errSecItemNotFound) { ret = false; } CFRelease(itemMatch); CFRelease(searchList); CFRelease(query); return ret; } static int32_t CheckTrustSettings(SecCertificateRef cert) { const int32_t kErrorUserTrust = 2; const int32_t kErrorAdminTrust = 3; OSStatus status = noErr; CFArrayRef settings = NULL; if (status == noErr) { status = SecTrustSettingsCopyTrustSettings(cert, kSecTrustSettingsDomainUser, &settings); } if (settings != NULL) { CFRelease(settings); settings = NULL; } if (status == noErr) { return kErrorUserTrust; } status = SecTrustSettingsCopyTrustSettings(cert, kSecTrustSettingsDomainAdmin, &settings); if (settings != NULL) { CFRelease(settings); settings = NULL; } if (status == noErr) { return kErrorAdminTrust; } return 0; } int32_t AppleCryptoNative_X509StoreAddCertificate(CFTypeRef certOrIdentity, SecKeychainRef keychain, int32_t* pOSStatus) { if (pOSStatus != NULL) *pOSStatus = noErr; if (certOrIdentity == NULL || keychain == NULL || pOSStatus == NULL) return -1; SecCertificateRef cert = NULL; SecKeyRef privateKey = NULL; CFTypeID inputType = CFGetTypeID(certOrIdentity); OSStatus status = noErr; if (inputType == SecCertificateGetTypeID()) { cert = (SecCertificateRef)CONST_CAST(void*, certOrIdentity); CFRetain(cert); } else if (inputType == SecIdentityGetTypeID()) { SecIdentityRef identity = (SecIdentityRef)CONST_CAST(void*, certOrIdentity); status = SecIdentityCopyCertificate(identity, &cert); if (status == noErr) { status = SecIdentityCopyPrivateKey(identity, &privateKey); } } else { return -1; } SecKeychainItemRef itemCopy = NULL; // Copy the private key into the new keychain first, because it can fail due to // non-exportability. Certificates can only fail for things like I/O errors saving the // keychain back to disk. if (status == noErr && privateKey != NULL) { status = SecKeychainItemCreateCopy((SecKeychainItemRef)privateKey, keychain, NULL, &itemCopy); } if (status == errSecDuplicateItem) { status = noErr; } // Since we don't care about the itemCopy we'd ideally pass NULL to SecKeychainItemCreateCopy, // but even though the documentation says it can be null, clang gives an error that null isn't // allowed. if (itemCopy != NULL) { CFRelease(itemCopy); itemCopy = NULL; } if (status == noErr && cert != NULL) { status = SecKeychainItemCreateCopy((SecKeychainItemRef)cert, keychain, NULL, &itemCopy); } if (status == errSecDuplicateItem) { status = noErr; } if (itemCopy != NULL) { CFRelease(itemCopy); itemCopy = NULL; } if (privateKey != NULL) { CFRelease(privateKey); privateKey = NULL; } if (cert != NULL) { CFRelease(cert); cert = NULL; } *pOSStatus = status; return status == noErr; } int32_t AppleCryptoNative_X509StoreRemoveCertificate(CFTypeRef certOrIdentity, SecKeychainRef keychain, uint8_t isReadOnlyMode, int32_t* pOSStatus) { if (pOSStatus != NULL) *pOSStatus = noErr; if (certOrIdentity == NULL || keychain == NULL || pOSStatus == NULL) return -1; SecCertificateRef cert = NULL; SecIdentityRef identity = NULL; CFTypeID inputType = CFGetTypeID(certOrIdentity); OSStatus status = noErr; if (inputType == SecCertificateGetTypeID()) { cert = (SecCertificateRef)CONST_CAST(void*, certOrIdentity); CFRetain(cert); } else if (inputType == SecIdentityGetTypeID()) { identity = (SecIdentityRef)CONST_CAST(void*, certOrIdentity); status = SecIdentityCopyCertificate(identity, &cert); if (status != noErr) { *pOSStatus = status; return 0; } } else { return -1; } const int32_t kErrorReadonlyDelete = 4; int32_t ret = 0; if (isReadOnlyMode) { ret = kErrorReadonlyDelete; } else { ret = CheckTrustSettings(cert); } if (ret != 0) { if (!IsCertInKeychain(cert, keychain)) { CFRelease(cert); return 1; } CFRelease(cert); return ret; } *pOSStatus = DeleteInKeychain(cert, keychain); CFRelease(cert); return *pOSStatus == noErr; }
-1
dotnet/runtime
66,462
Support using the system version of brotli
This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
omajid
2022-03-10T17:19:11Z
2022-03-23T03:49:50Z
c3e1d21c2fb30436ae24ef7ef4f458e3270bb7e3
5ca9223639700750ff12bb1fed9fa6e397062b78
Support using the system version of brotli . This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
./src/mono/mono/utils/monobitset.c
/** * \file */ #include <glib.h> #include <string.h> #include "monobitset.h" #include "config.h" #define BITS_PER_CHUNK MONO_BITSET_BITS_PER_CHUNK /** * mono_bitset_alloc_size: * \param max_size The number of bits you want to hold * \param flags unused * \returns the number of bytes required to hold the bitset. * Useful to allocate it on the stack or with mempool. * Use with \c mono_bitset_mem_new. */ guint32 mono_bitset_alloc_size (guint32 max_size, guint32 flags) { guint32 real_size = (max_size + BITS_PER_CHUNK - 1) / BITS_PER_CHUNK; return sizeof (MonoBitSet) + sizeof (gsize) * (real_size - MONO_ZERO_LEN_ARRAY); } /** * mono_bitset_new: * \param max_size The numer of bits you want to hold * \param flags bitfield of flags * \returns a bitset of size \p max_size. It must be freed using * \c mono_bitset_free. */ MonoBitSet * mono_bitset_new (guint32 max_size, guint32 flags) { guint32 real_size = (max_size + BITS_PER_CHUNK - 1) / BITS_PER_CHUNK; MonoBitSet *result; result = (MonoBitSet *) g_malloc0 (sizeof (MonoBitSet) + sizeof (gsize) * (real_size - MONO_ZERO_LEN_ARRAY)); result->size = real_size * BITS_PER_CHUNK; result->flags = flags; return result; } /** * mono_bitset_mem_new: * \param mem The location the bitset is stored * \param max_size The number of bits you want to hold * \param flags bitfield of flags * * Return \p mem, which is now a initialized bitset of size \p max_size. It is * not freed even if called with \c mono_bitset_free. \p mem must be at least * as big as \c mono_bitset_alloc_size returns for the same \p max_size. */ MonoBitSet * mono_bitset_mem_new (gpointer mem, guint32 max_size, guint32 flags) { guint32 real_size = (max_size + BITS_PER_CHUNK - 1) / BITS_PER_CHUNK; MonoBitSet *result = (MonoBitSet *) mem; result->size = real_size * BITS_PER_CHUNK; result->flags = flags | MONO_BITSET_DONT_FREE; return result; } /* * mono_bitset_free: * \param set bitset ptr to free * * Free bitset unless flags have \c MONO_BITSET_DONT_FREE set. Does not * free anything if flag \c MONO_BITSET_DONT_FREE is set or bitset was * made with \c mono_bitset_mem_new. */ void mono_bitset_free (MonoBitSet *set) { if (set && !(set->flags & MONO_BITSET_DONT_FREE)) g_free (set); } /** * mono_bitset_set: * \param set bitset ptr * \param pos set bit at this pos * * Set bit at \p pos, counting from 0. */ void mono_bitset_set (MonoBitSet *set, guint32 pos) { int j = pos / BITS_PER_CHUNK; int bit = pos % BITS_PER_CHUNK; g_assert (pos < set->size); set->data [j] |= (gsize)1 << bit; } /** * mono_bitset_test: * \param set bitset ptr * \param pos test bit at this pos * Test bit at \p pos, counting from 0. * \returns a nonzero value if set, 0 otherwise. */ int mono_bitset_test (const MonoBitSet *set, guint32 pos) { int j = pos / BITS_PER_CHUNK; int bit = pos % BITS_PER_CHUNK; g_return_val_if_fail (pos < set->size, 0); return (set->data [j] & ((gsize)1 << bit)) > 0; } /** * mono_bitset_test_bulk: * \param set bitset ptr * \param pos test bit at this pos * \returns 32/64 bits from the bitset, starting from \p pos, which must be * divisible with 32/64. */ gsize mono_bitset_test_bulk (const MonoBitSet *set, guint32 pos) { int j = pos / BITS_PER_CHUNK; if (pos >= set->size) return 0; else return set->data [j]; } /** * mono_bitset_clear: * \param set bitset ptr * \param pos unset bit at this pos * * Unset bit at \p pos, counting from 0. */ void mono_bitset_clear (MonoBitSet *set, guint32 pos) { int j = pos / BITS_PER_CHUNK; int bit = pos % BITS_PER_CHUNK; g_assert (pos < set->size); set->data [j] &= ~((gsize)1 << bit); } /** * mono_bitset_clear_all: * \param set bitset ptr * * Unset all bits. */ void mono_bitset_clear_all (MonoBitSet *set) { memset (set->data, 0, set->size / 8); } /** * mono_bitset_set_all: * \param set bitset ptr * * Set all bits. */ void mono_bitset_set_all (MonoBitSet *set) { memset (set->data, -1, set->size / 8); } /** * mono_bitset_invert: * \param set bitset ptr * * Flip all bits. */ void mono_bitset_invert (MonoBitSet *set) { int i; for (i = 0; i < set->size / BITS_PER_CHUNK; ++i) set->data [i] = ~set->data [i]; } /** * mono_bitset_size: * \param set bitset ptr * \returns the number of bits this bitset can hold. */ guint32 mono_bitset_size (const MonoBitSet *set) { return (guint32)set->size; } /* * should test wich version is faster. */ #if 1 /** * mono_bitset_count: * \param set bitset ptr * \returns number of bits that are set. */ guint32 mono_bitset_count (const MonoBitSet *set) { guint32 i, count; gsize d; count = 0; for (i = 0; i < set->size / BITS_PER_CHUNK; ++i) { d = set->data [i]; #if defined (__GNUC__) && !defined (HOST_WIN32) // The builtins do work on Win32, but can cause a not worthwhile runtime dependency. // See https://github.com/mono/mono/pull/14248. if (sizeof (gsize) == sizeof (unsigned int)) count += __builtin_popcount (d); else count += __builtin_popcountll (d); #else while (d) { count ++; d &= (d - 1); } #endif } return count; } #else guint32 mono_bitset_count (const MonoBitSet *set) { static const guint32 table [] = { 0x55555555, 0x33333333, 0x0F0F0F0F, 0x00FF00FF, 0x0000FFFF }; guint32 i, count, val; count = 0; for (i = 0; i < set->size / BITS_PER_CHUNK;+i) { if (set->data [i]) { val = set->data [i]; val = (val & table [0]) ((val >> 1) & table [0]); val = (val & table [1]) ((val >> 2) & table [1]); val = (val & table [2]) ((val >> 4) & table [2]); val = (val & table [3]) ((val >> 8) & table [3]); val = (val & table [4]) ((val >> 16) & table [4]); count += val; } } return count; } #endif #if 0 const static int bitstart_mask [] = { 0xffffffff, 0xfffffffe, 0xfffffffc, 0xfffffff8, 0xfffffff0, 0xffffffe0, 0xffffffc0, 0xffffff80, 0xffffff00, 0xfffffe00, 0xfffffc00, 0xfffff800, 0xfffff000, 0xffffe000, 0xffffc000, 0xffff8000, 0xffff0000, 0xfffe0000, 0xfffc0000, 0xfff80000, 0xfff00000, 0xffe00000, 0xffc00000, 0xff800000, 0xff000000, 0xfe000000, 0xfc000000, 0xf8000000, 0xf0000000, 0xe0000000, 0xc0000000, 0x80000000, 0x00000000 }; #define my_g_bit_nth_lsf(m,n) (ffs((m) & bitstart_mask [(n)+1])-1) #define my_g_bit_nth_lsf_nomask(m) (ffs((m))-1) #else static gint my_g_bit_nth_lsf (gsize mask, gint nth_bit) { nth_bit ++; mask >>= nth_bit; if ((mask == 0) || (nth_bit == BITS_PER_CHUNK)) return -1; #if (defined(__i386__) && defined(__GNUC__)) { int r; /* This depends on mask != 0 */ __asm__("bsfl %1,%0\n\t" : "=r" (r) : "g" (mask)); return nth_bit + r; } #elif defined(__x86_64) && defined(__GNUC__) { guint64 r; __asm__("bsfq %1,%0\n\t" : "=r" (r) : "rm" (mask)); return nth_bit + r; } #else while (! (mask & 0x1)) { mask >>= 1; nth_bit ++; } return nth_bit; #endif } static gint my_g_bit_nth_lsf_nomask (gsize mask) { /* Mask is expected to be != 0 */ #if (defined(__i386__) && defined(__GNUC__)) int r; __asm__("bsfl %1,%0\n\t" : "=r" (r) : "rm" (mask)); return r; #elif defined(__x86_64) && defined(__GNUC__) guint64 r; __asm__("bsfq %1,%0\n\t" : "=r" (r) : "rm" (mask)); return r; #else int nth_bit = 0; while (! (mask & 0x1)) { mask >>= 1; nth_bit ++; } return nth_bit; #endif } #endif static int my_g_bit_nth_msf (gsize mask, gint nth_bit) { int i; if (nth_bit == 0) return -1; mask <<= BITS_PER_CHUNK - nth_bit; i = BITS_PER_CHUNK; while ((i > 0) && !(mask >> (BITS_PER_CHUNK - 8))) { mask <<= 8; i -= 8; } if (mask == 0) return -1; do { i--; if (mask & ((gsize)1 << (BITS_PER_CHUNK - 1))) return i - (BITS_PER_CHUNK - nth_bit); mask <<= 1; } while (mask); return -1; } static int find_first_unset (gsize mask, gint nth_bit) { do { nth_bit++; if (!(mask & ((gsize)1 << nth_bit))) { if (nth_bit == BITS_PER_CHUNK) /* On 64 bit platforms, 1 << 64 == 1 */ return -1; else return nth_bit; } } while (nth_bit < BITS_PER_CHUNK); return -1; } /** * mono_bitset_find_start: * \param set bitset ptr * Equivalent to <code>mono_bitset_find_first (set, -1)</code> but faster. */ int mono_bitset_find_start (const MonoBitSet *set) { int i; for (i = 0; i < set->size / BITS_PER_CHUNK; ++i) { if (set->data [i]) return my_g_bit_nth_lsf_nomask (set->data [i]) + i * BITS_PER_CHUNK; } return -1; } /** * mono_bitset_find_first: * \param set bitset ptr * \param pos pos to search after (not including) * \returns position of first set bit after \p pos. If \p pos < 0, begin search from * start. Return \c -1 if no bit set is found. */ int mono_bitset_find_first (const MonoBitSet *set, gint pos) { int j; int bit; int result, i; if (pos < 0) { j = 0; bit = -1; } else { j = pos / BITS_PER_CHUNK; bit = pos % BITS_PER_CHUNK; g_assert (pos < set->size); } /*g_print ("find first from %d (j: %d, bit: %d)\n", pos, j, bit);*/ if (set->data [j]) { result = my_g_bit_nth_lsf (set->data [j], bit); if (result != -1) return result + j * BITS_PER_CHUNK; } for (i = ++j; i < set->size / BITS_PER_CHUNK; ++i) { if (set->data [i]) return my_g_bit_nth_lsf (set->data [i], -1) + i * BITS_PER_CHUNK; } return -1; } /** * mono_bitset_find_last: * \param set bitset ptr * \param pos pos to search before (not including) * \returns position of last set bit before \p pos. If \p pos < 0 search is * started from the end. Returns \c -1 if no set bit is found. */ int mono_bitset_find_last (const MonoBitSet *set, gint pos) { int j, bit, result, i; if (pos < 0) pos = (gint)(set->size - 1); j = pos / BITS_PER_CHUNK; bit = pos % BITS_PER_CHUNK; g_return_val_if_fail (pos < set->size, -1); if (set->data [j]) { result = my_g_bit_nth_msf (set->data [j], bit); if (result != -1) return result + j * BITS_PER_CHUNK; } for (i = --j; i >= 0; --i) { if (set->data [i]) return my_g_bit_nth_msf (set->data [i], BITS_PER_CHUNK) + i * BITS_PER_CHUNK; } return -1; } /** * mono_bitset_find_first_unset: * \param set bitset ptr * \param pos pos to search after (not including) * \returns position of first unset bit after \p pos. If \p pos < 0 begin search from * start. Return \c -1 if no bit set is found. */ int mono_bitset_find_first_unset (const MonoBitSet *set, gint pos) { int j; int bit; int result, i; if (pos < 0) { j = 0; bit = -1; } else { j = pos / BITS_PER_CHUNK; bit = pos % BITS_PER_CHUNK; g_return_val_if_fail (pos < set->size, -1); } /*g_print ("find first from %d (j: %d, bit: %d)\n", pos, j, bit);*/ if (set->data [j] != -1) { result = find_first_unset (set->data [j], bit); if (result != -1) return result + j * BITS_PER_CHUNK; } for (i = ++j; i < set->size / BITS_PER_CHUNK; ++i) { if (set->data [i] != -1) { return find_first_unset (set->data [i], -1) + i * BITS_PER_CHUNK; } } return -1; } /** * mono_bitset_clone: * \param set bitset ptr to clone * \param new_size number of bits the cloned bitset can hold * \returns a cloned bitset of size \p new_size. \c MONO_BITSET_DONT_FREE * unset in cloned bitset. If \p new_size is 0, the cloned object is just * as big. */ MonoBitSet* mono_bitset_clone (const MonoBitSet *set, guint32 new_size) { MonoBitSet *result; if (!new_size) new_size = (guint32)set->size; result = mono_bitset_new (new_size, (guint32)set->flags); result->flags &= ~MONO_BITSET_DONT_FREE; memcpy (result->data, set->data, set->size / 8); return result; } /** * mono_bitset_copyto: * \param src bitset ptr to copy from * \param dest bitset ptr to copy to * * Copy one bitset to another. */ void mono_bitset_copyto (const MonoBitSet *src, MonoBitSet *dest) { g_assert (dest->size <= src->size); memcpy (&dest->data, &src->data, dest->size / 8); } /** * mono_bitset_union: * \param dest bitset ptr to hold union * \param src bitset ptr to copy * * Make union of one bitset and another. */ void mono_bitset_union (MonoBitSet *dest, const MonoBitSet *src) { int i; size_t size; g_assert (src->size <= dest->size); size = dest->size / BITS_PER_CHUNK; for (i = 0; i < size; ++i) dest->data [i] |= src->data [i]; } /** * mono_bitset_intersection: * \param dest bitset ptr to hold intersection * \param src bitset ptr to copy * * Make intersection of one bitset and another. */ void mono_bitset_intersection (MonoBitSet *dest, const MonoBitSet *src) { int i; size_t size; g_assert (src->size <= dest->size); size = dest->size / BITS_PER_CHUNK; for (i = 0; i < size; ++i) dest->data [i] &= src->data [i]; } /** * mono_bitset_intersection_2: * \param dest bitset ptr to hold intersection * \param src1 first bitset * \param src2 second bitset * * Make intersection of two bitsets */ void mono_bitset_intersection_2 (MonoBitSet *dest, const MonoBitSet *src1, const MonoBitSet *src2) { int i; size_t size; g_assert (src1->size <= dest->size); g_assert (src2->size <= dest->size); size = dest->size / BITS_PER_CHUNK; for (i = 0; i < size; ++i) dest->data [i] = src1->data [i] & src2->data [i]; } /** * mono_bitset_sub: * \param dest bitset ptr to hold bitset - src * \param src bitset ptr to copy * * Unset all bits in \p dest that are set in \p src. */ void mono_bitset_sub (MonoBitSet *dest, const MonoBitSet *src) { int i; size_t size; g_assert (src->size <= dest->size); size = src->size / BITS_PER_CHUNK; for (i = 0; i < size; ++i) dest->data [i] &= ~src->data [i]; } /** * mono_bitset_equal: * \param src bitset ptr * \param src1 bitset ptr * \returns TRUE if their size are the same and the same bits are set in * both bitsets. */ gboolean mono_bitset_equal (const MonoBitSet *src, const MonoBitSet *src1) { int i; if (src->size != src1->size) return FALSE; for (i = 0; i < src->size / BITS_PER_CHUNK; ++i) if (src->data [i] != src1->data [i]) return FALSE; return TRUE; } /** * mono_bitset_foreach: * \param set bitset ptr * \param func Function to call for every set bit * \param data pass this as second arg to func * Calls \p func for every bit set in bitset. Argument 1 is the number of * the bit set, argument 2 is data */ void mono_bitset_foreach (MonoBitSet *set, MonoBitSetFunc func, gpointer data) { int i, j; for (i = 0; i < set->size / BITS_PER_CHUNK; ++i) { if (set->data [i]) { for (j = 0; j < BITS_PER_CHUNK; ++j) if (set->data [i] & ((gsize)1 << j)) func (j + i * BITS_PER_CHUNK, data); } } } gboolean mono_bitset_test_safe (const MonoBitSet *set, guint32 pos) { return set && set->size > pos && mono_bitset_test (set, pos); } #ifdef TEST_BITSET /* * Compile with: * gcc -g -Wall -DTEST_BITSET -o monobitset monobitset.c `pkg-config --cflags --libs glib-2.0` */ int main() { MonoBitSet *set1, *set2, *set3, *set4; int error = 1; int count, i; set1 = mono_bitset_new (60, 0); set4 = mono_bitset_new (60, 0); if (mono_bitset_count (set1) != 0) return error; error++; mono_bitset_set (set1, 33); if (mono_bitset_count (set1) != 1) return error; error++; /* g_print("should be 33: %d\n", mono_bitset_find_first (set1, 0)); */ if (mono_bitset_find_first (set1, 0) != 33) return error; error++; if (mono_bitset_find_first (set1, 33) != -1) return error; error++; /* test 5 */ if (mono_bitset_find_first (set1, -100) != 33) return error; error++; if (mono_bitset_find_last (set1, -1) != 33) return error; error++; if (mono_bitset_find_last (set1, 33) != -1) return error; error++; if (mono_bitset_find_last (set1, -100) != 33) return error; error++; if (mono_bitset_find_last (set1, 34) != 33) return error; error++; /* test 10 */ if (!mono_bitset_test (set1, 33)) return error; error++; if (mono_bitset_test (set1, 32) || mono_bitset_test (set1, 34)) return error; error++; set2 = mono_bitset_clone (set1, 0); if (mono_bitset_count (set2) != 1) return error; error++; mono_bitset_invert (set2); if (mono_bitset_count (set2) != (mono_bitset_size (set2) - 1)) return error; error++; mono_bitset_clear (set2, 10); if (mono_bitset_count (set2) != (mono_bitset_size (set2) - 2)) return error; error++; /* test 15 */ set3 = mono_bitset_clone (set2, 0); mono_bitset_union (set3, set1); if (mono_bitset_count (set3) != (mono_bitset_size (set3) - 1)) return error; error++; mono_bitset_clear_all (set2); if (mono_bitset_count (set2) != 0) return error; error++; mono_bitset_invert (set2); if (mono_bitset_count (set2) != mono_bitset_size (set2)) return error; error++; mono_bitset_set (set4, 0); mono_bitset_set (set4, 1); mono_bitset_set (set4, 10); if (mono_bitset_count (set4) != 3) return error; error++; count = 0; for (i = mono_bitset_find_first (set4, -1); i != -1; i = mono_bitset_find_first (set4, i)) { count ++; switch (count) { case 1: if (i != 0) return error; break; case 2: if (i != 1) return error; break; case 3: if (i != 10) return error; break; } /* g_print ("count got: %d at %d\n", count, i); */ } if (count != 3) return error; error++; if (mono_bitset_find_first (set4, -1) != 0) return error; error++; /* 20 */ mono_bitset_set (set4, 31); if (mono_bitset_find_first (set4, 10) != 31) return error; error++; mono_bitset_free (set1); set1 = mono_bitset_new (200, 0); mono_bitset_set (set1, 0); mono_bitset_set (set1, 1); mono_bitset_set (set1, 10); mono_bitset_set (set1, 31); mono_bitset_set (set1, 150); mono_bitset_free (set1); mono_bitset_free (set2); mono_bitset_free (set3); mono_bitset_free (set4); g_print ("total tests passed: %d\n", error - 1); return 0; } #endif
/** * \file */ #include <glib.h> #include <string.h> #include "monobitset.h" #include "config.h" #define BITS_PER_CHUNK MONO_BITSET_BITS_PER_CHUNK /** * mono_bitset_alloc_size: * \param max_size The number of bits you want to hold * \param flags unused * \returns the number of bytes required to hold the bitset. * Useful to allocate it on the stack or with mempool. * Use with \c mono_bitset_mem_new. */ guint32 mono_bitset_alloc_size (guint32 max_size, guint32 flags) { guint32 real_size = (max_size + BITS_PER_CHUNK - 1) / BITS_PER_CHUNK; return sizeof (MonoBitSet) + sizeof (gsize) * (real_size - MONO_ZERO_LEN_ARRAY); } /** * mono_bitset_new: * \param max_size The numer of bits you want to hold * \param flags bitfield of flags * \returns a bitset of size \p max_size. It must be freed using * \c mono_bitset_free. */ MonoBitSet * mono_bitset_new (guint32 max_size, guint32 flags) { guint32 real_size = (max_size + BITS_PER_CHUNK - 1) / BITS_PER_CHUNK; MonoBitSet *result; result = (MonoBitSet *) g_malloc0 (sizeof (MonoBitSet) + sizeof (gsize) * (real_size - MONO_ZERO_LEN_ARRAY)); result->size = real_size * BITS_PER_CHUNK; result->flags = flags; return result; } /** * mono_bitset_mem_new: * \param mem The location the bitset is stored * \param max_size The number of bits you want to hold * \param flags bitfield of flags * * Return \p mem, which is now a initialized bitset of size \p max_size. It is * not freed even if called with \c mono_bitset_free. \p mem must be at least * as big as \c mono_bitset_alloc_size returns for the same \p max_size. */ MonoBitSet * mono_bitset_mem_new (gpointer mem, guint32 max_size, guint32 flags) { guint32 real_size = (max_size + BITS_PER_CHUNK - 1) / BITS_PER_CHUNK; MonoBitSet *result = (MonoBitSet *) mem; result->size = real_size * BITS_PER_CHUNK; result->flags = flags | MONO_BITSET_DONT_FREE; return result; } /* * mono_bitset_free: * \param set bitset ptr to free * * Free bitset unless flags have \c MONO_BITSET_DONT_FREE set. Does not * free anything if flag \c MONO_BITSET_DONT_FREE is set or bitset was * made with \c mono_bitset_mem_new. */ void mono_bitset_free (MonoBitSet *set) { if (set && !(set->flags & MONO_BITSET_DONT_FREE)) g_free (set); } /** * mono_bitset_set: * \param set bitset ptr * \param pos set bit at this pos * * Set bit at \p pos, counting from 0. */ void mono_bitset_set (MonoBitSet *set, guint32 pos) { int j = pos / BITS_PER_CHUNK; int bit = pos % BITS_PER_CHUNK; g_assert (pos < set->size); set->data [j] |= (gsize)1 << bit; } /** * mono_bitset_test: * \param set bitset ptr * \param pos test bit at this pos * Test bit at \p pos, counting from 0. * \returns a nonzero value if set, 0 otherwise. */ int mono_bitset_test (const MonoBitSet *set, guint32 pos) { int j = pos / BITS_PER_CHUNK; int bit = pos % BITS_PER_CHUNK; g_return_val_if_fail (pos < set->size, 0); return (set->data [j] & ((gsize)1 << bit)) > 0; } /** * mono_bitset_test_bulk: * \param set bitset ptr * \param pos test bit at this pos * \returns 32/64 bits from the bitset, starting from \p pos, which must be * divisible with 32/64. */ gsize mono_bitset_test_bulk (const MonoBitSet *set, guint32 pos) { int j = pos / BITS_PER_CHUNK; if (pos >= set->size) return 0; else return set->data [j]; } /** * mono_bitset_clear: * \param set bitset ptr * \param pos unset bit at this pos * * Unset bit at \p pos, counting from 0. */ void mono_bitset_clear (MonoBitSet *set, guint32 pos) { int j = pos / BITS_PER_CHUNK; int bit = pos % BITS_PER_CHUNK; g_assert (pos < set->size); set->data [j] &= ~((gsize)1 << bit); } /** * mono_bitset_clear_all: * \param set bitset ptr * * Unset all bits. */ void mono_bitset_clear_all (MonoBitSet *set) { memset (set->data, 0, set->size / 8); } /** * mono_bitset_set_all: * \param set bitset ptr * * Set all bits. */ void mono_bitset_set_all (MonoBitSet *set) { memset (set->data, -1, set->size / 8); } /** * mono_bitset_invert: * \param set bitset ptr * * Flip all bits. */ void mono_bitset_invert (MonoBitSet *set) { int i; for (i = 0; i < set->size / BITS_PER_CHUNK; ++i) set->data [i] = ~set->data [i]; } /** * mono_bitset_size: * \param set bitset ptr * \returns the number of bits this bitset can hold. */ guint32 mono_bitset_size (const MonoBitSet *set) { return (guint32)set->size; } /* * should test wich version is faster. */ #if 1 /** * mono_bitset_count: * \param set bitset ptr * \returns number of bits that are set. */ guint32 mono_bitset_count (const MonoBitSet *set) { guint32 i, count; gsize d; count = 0; for (i = 0; i < set->size / BITS_PER_CHUNK; ++i) { d = set->data [i]; #if defined (__GNUC__) && !defined (HOST_WIN32) // The builtins do work on Win32, but can cause a not worthwhile runtime dependency. // See https://github.com/mono/mono/pull/14248. if (sizeof (gsize) == sizeof (unsigned int)) count += __builtin_popcount (d); else count += __builtin_popcountll (d); #else while (d) { count ++; d &= (d - 1); } #endif } return count; } #else guint32 mono_bitset_count (const MonoBitSet *set) { static const guint32 table [] = { 0x55555555, 0x33333333, 0x0F0F0F0F, 0x00FF00FF, 0x0000FFFF }; guint32 i, count, val; count = 0; for (i = 0; i < set->size / BITS_PER_CHUNK;+i) { if (set->data [i]) { val = set->data [i]; val = (val & table [0]) ((val >> 1) & table [0]); val = (val & table [1]) ((val >> 2) & table [1]); val = (val & table [2]) ((val >> 4) & table [2]); val = (val & table [3]) ((val >> 8) & table [3]); val = (val & table [4]) ((val >> 16) & table [4]); count += val; } } return count; } #endif #if 0 const static int bitstart_mask [] = { 0xffffffff, 0xfffffffe, 0xfffffffc, 0xfffffff8, 0xfffffff0, 0xffffffe0, 0xffffffc0, 0xffffff80, 0xffffff00, 0xfffffe00, 0xfffffc00, 0xfffff800, 0xfffff000, 0xffffe000, 0xffffc000, 0xffff8000, 0xffff0000, 0xfffe0000, 0xfffc0000, 0xfff80000, 0xfff00000, 0xffe00000, 0xffc00000, 0xff800000, 0xff000000, 0xfe000000, 0xfc000000, 0xf8000000, 0xf0000000, 0xe0000000, 0xc0000000, 0x80000000, 0x00000000 }; #define my_g_bit_nth_lsf(m,n) (ffs((m) & bitstart_mask [(n)+1])-1) #define my_g_bit_nth_lsf_nomask(m) (ffs((m))-1) #else static gint my_g_bit_nth_lsf (gsize mask, gint nth_bit) { nth_bit ++; mask >>= nth_bit; if ((mask == 0) || (nth_bit == BITS_PER_CHUNK)) return -1; #if (defined(__i386__) && defined(__GNUC__)) { int r; /* This depends on mask != 0 */ __asm__("bsfl %1,%0\n\t" : "=r" (r) : "g" (mask)); return nth_bit + r; } #elif defined(__x86_64) && defined(__GNUC__) { guint64 r; __asm__("bsfq %1,%0\n\t" : "=r" (r) : "rm" (mask)); return nth_bit + r; } #else while (! (mask & 0x1)) { mask >>= 1; nth_bit ++; } return nth_bit; #endif } static gint my_g_bit_nth_lsf_nomask (gsize mask) { /* Mask is expected to be != 0 */ #if (defined(__i386__) && defined(__GNUC__)) int r; __asm__("bsfl %1,%0\n\t" : "=r" (r) : "rm" (mask)); return r; #elif defined(__x86_64) && defined(__GNUC__) guint64 r; __asm__("bsfq %1,%0\n\t" : "=r" (r) : "rm" (mask)); return r; #else int nth_bit = 0; while (! (mask & 0x1)) { mask >>= 1; nth_bit ++; } return nth_bit; #endif } #endif static int my_g_bit_nth_msf (gsize mask, gint nth_bit) { int i; if (nth_bit == 0) return -1; mask <<= BITS_PER_CHUNK - nth_bit; i = BITS_PER_CHUNK; while ((i > 0) && !(mask >> (BITS_PER_CHUNK - 8))) { mask <<= 8; i -= 8; } if (mask == 0) return -1; do { i--; if (mask & ((gsize)1 << (BITS_PER_CHUNK - 1))) return i - (BITS_PER_CHUNK - nth_bit); mask <<= 1; } while (mask); return -1; } static int find_first_unset (gsize mask, gint nth_bit) { do { nth_bit++; if (!(mask & ((gsize)1 << nth_bit))) { if (nth_bit == BITS_PER_CHUNK) /* On 64 bit platforms, 1 << 64 == 1 */ return -1; else return nth_bit; } } while (nth_bit < BITS_PER_CHUNK); return -1; } /** * mono_bitset_find_start: * \param set bitset ptr * Equivalent to <code>mono_bitset_find_first (set, -1)</code> but faster. */ int mono_bitset_find_start (const MonoBitSet *set) { int i; for (i = 0; i < set->size / BITS_PER_CHUNK; ++i) { if (set->data [i]) return my_g_bit_nth_lsf_nomask (set->data [i]) + i * BITS_PER_CHUNK; } return -1; } /** * mono_bitset_find_first: * \param set bitset ptr * \param pos pos to search after (not including) * \returns position of first set bit after \p pos. If \p pos < 0, begin search from * start. Return \c -1 if no bit set is found. */ int mono_bitset_find_first (const MonoBitSet *set, gint pos) { int j; int bit; int result, i; if (pos < 0) { j = 0; bit = -1; } else { j = pos / BITS_PER_CHUNK; bit = pos % BITS_PER_CHUNK; g_assert (pos < set->size); } /*g_print ("find first from %d (j: %d, bit: %d)\n", pos, j, bit);*/ if (set->data [j]) { result = my_g_bit_nth_lsf (set->data [j], bit); if (result != -1) return result + j * BITS_PER_CHUNK; } for (i = ++j; i < set->size / BITS_PER_CHUNK; ++i) { if (set->data [i]) return my_g_bit_nth_lsf (set->data [i], -1) + i * BITS_PER_CHUNK; } return -1; } /** * mono_bitset_find_last: * \param set bitset ptr * \param pos pos to search before (not including) * \returns position of last set bit before \p pos. If \p pos < 0 search is * started from the end. Returns \c -1 if no set bit is found. */ int mono_bitset_find_last (const MonoBitSet *set, gint pos) { int j, bit, result, i; if (pos < 0) pos = (gint)(set->size - 1); j = pos / BITS_PER_CHUNK; bit = pos % BITS_PER_CHUNK; g_return_val_if_fail (pos < set->size, -1); if (set->data [j]) { result = my_g_bit_nth_msf (set->data [j], bit); if (result != -1) return result + j * BITS_PER_CHUNK; } for (i = --j; i >= 0; --i) { if (set->data [i]) return my_g_bit_nth_msf (set->data [i], BITS_PER_CHUNK) + i * BITS_PER_CHUNK; } return -1; } /** * mono_bitset_find_first_unset: * \param set bitset ptr * \param pos pos to search after (not including) * \returns position of first unset bit after \p pos. If \p pos < 0 begin search from * start. Return \c -1 if no bit set is found. */ int mono_bitset_find_first_unset (const MonoBitSet *set, gint pos) { int j; int bit; int result, i; if (pos < 0) { j = 0; bit = -1; } else { j = pos / BITS_PER_CHUNK; bit = pos % BITS_PER_CHUNK; g_return_val_if_fail (pos < set->size, -1); } /*g_print ("find first from %d (j: %d, bit: %d)\n", pos, j, bit);*/ if (set->data [j] != -1) { result = find_first_unset (set->data [j], bit); if (result != -1) return result + j * BITS_PER_CHUNK; } for (i = ++j; i < set->size / BITS_PER_CHUNK; ++i) { if (set->data [i] != -1) { return find_first_unset (set->data [i], -1) + i * BITS_PER_CHUNK; } } return -1; } /** * mono_bitset_clone: * \param set bitset ptr to clone * \param new_size number of bits the cloned bitset can hold * \returns a cloned bitset of size \p new_size. \c MONO_BITSET_DONT_FREE * unset in cloned bitset. If \p new_size is 0, the cloned object is just * as big. */ MonoBitSet* mono_bitset_clone (const MonoBitSet *set, guint32 new_size) { MonoBitSet *result; if (!new_size) new_size = (guint32)set->size; result = mono_bitset_new (new_size, (guint32)set->flags); result->flags &= ~MONO_BITSET_DONT_FREE; memcpy (result->data, set->data, set->size / 8); return result; } /** * mono_bitset_copyto: * \param src bitset ptr to copy from * \param dest bitset ptr to copy to * * Copy one bitset to another. */ void mono_bitset_copyto (const MonoBitSet *src, MonoBitSet *dest) { g_assert (dest->size <= src->size); memcpy (&dest->data, &src->data, dest->size / 8); } /** * mono_bitset_union: * \param dest bitset ptr to hold union * \param src bitset ptr to copy * * Make union of one bitset and another. */ void mono_bitset_union (MonoBitSet *dest, const MonoBitSet *src) { int i; size_t size; g_assert (src->size <= dest->size); size = dest->size / BITS_PER_CHUNK; for (i = 0; i < size; ++i) dest->data [i] |= src->data [i]; } /** * mono_bitset_intersection: * \param dest bitset ptr to hold intersection * \param src bitset ptr to copy * * Make intersection of one bitset and another. */ void mono_bitset_intersection (MonoBitSet *dest, const MonoBitSet *src) { int i; size_t size; g_assert (src->size <= dest->size); size = dest->size / BITS_PER_CHUNK; for (i = 0; i < size; ++i) dest->data [i] &= src->data [i]; } /** * mono_bitset_intersection_2: * \param dest bitset ptr to hold intersection * \param src1 first bitset * \param src2 second bitset * * Make intersection of two bitsets */ void mono_bitset_intersection_2 (MonoBitSet *dest, const MonoBitSet *src1, const MonoBitSet *src2) { int i; size_t size; g_assert (src1->size <= dest->size); g_assert (src2->size <= dest->size); size = dest->size / BITS_PER_CHUNK; for (i = 0; i < size; ++i) dest->data [i] = src1->data [i] & src2->data [i]; } /** * mono_bitset_sub: * \param dest bitset ptr to hold bitset - src * \param src bitset ptr to copy * * Unset all bits in \p dest that are set in \p src. */ void mono_bitset_sub (MonoBitSet *dest, const MonoBitSet *src) { int i; size_t size; g_assert (src->size <= dest->size); size = src->size / BITS_PER_CHUNK; for (i = 0; i < size; ++i) dest->data [i] &= ~src->data [i]; } /** * mono_bitset_equal: * \param src bitset ptr * \param src1 bitset ptr * \returns TRUE if their size are the same and the same bits are set in * both bitsets. */ gboolean mono_bitset_equal (const MonoBitSet *src, const MonoBitSet *src1) { int i; if (src->size != src1->size) return FALSE; for (i = 0; i < src->size / BITS_PER_CHUNK; ++i) if (src->data [i] != src1->data [i]) return FALSE; return TRUE; } /** * mono_bitset_foreach: * \param set bitset ptr * \param func Function to call for every set bit * \param data pass this as second arg to func * Calls \p func for every bit set in bitset. Argument 1 is the number of * the bit set, argument 2 is data */ void mono_bitset_foreach (MonoBitSet *set, MonoBitSetFunc func, gpointer data) { int i, j; for (i = 0; i < set->size / BITS_PER_CHUNK; ++i) { if (set->data [i]) { for (j = 0; j < BITS_PER_CHUNK; ++j) if (set->data [i] & ((gsize)1 << j)) func (j + i * BITS_PER_CHUNK, data); } } } gboolean mono_bitset_test_safe (const MonoBitSet *set, guint32 pos) { return set && set->size > pos && mono_bitset_test (set, pos); } #ifdef TEST_BITSET /* * Compile with: * gcc -g -Wall -DTEST_BITSET -o monobitset monobitset.c `pkg-config --cflags --libs glib-2.0` */ int main() { MonoBitSet *set1, *set2, *set3, *set4; int error = 1; int count, i; set1 = mono_bitset_new (60, 0); set4 = mono_bitset_new (60, 0); if (mono_bitset_count (set1) != 0) return error; error++; mono_bitset_set (set1, 33); if (mono_bitset_count (set1) != 1) return error; error++; /* g_print("should be 33: %d\n", mono_bitset_find_first (set1, 0)); */ if (mono_bitset_find_first (set1, 0) != 33) return error; error++; if (mono_bitset_find_first (set1, 33) != -1) return error; error++; /* test 5 */ if (mono_bitset_find_first (set1, -100) != 33) return error; error++; if (mono_bitset_find_last (set1, -1) != 33) return error; error++; if (mono_bitset_find_last (set1, 33) != -1) return error; error++; if (mono_bitset_find_last (set1, -100) != 33) return error; error++; if (mono_bitset_find_last (set1, 34) != 33) return error; error++; /* test 10 */ if (!mono_bitset_test (set1, 33)) return error; error++; if (mono_bitset_test (set1, 32) || mono_bitset_test (set1, 34)) return error; error++; set2 = mono_bitset_clone (set1, 0); if (mono_bitset_count (set2) != 1) return error; error++; mono_bitset_invert (set2); if (mono_bitset_count (set2) != (mono_bitset_size (set2) - 1)) return error; error++; mono_bitset_clear (set2, 10); if (mono_bitset_count (set2) != (mono_bitset_size (set2) - 2)) return error; error++; /* test 15 */ set3 = mono_bitset_clone (set2, 0); mono_bitset_union (set3, set1); if (mono_bitset_count (set3) != (mono_bitset_size (set3) - 1)) return error; error++; mono_bitset_clear_all (set2); if (mono_bitset_count (set2) != 0) return error; error++; mono_bitset_invert (set2); if (mono_bitset_count (set2) != mono_bitset_size (set2)) return error; error++; mono_bitset_set (set4, 0); mono_bitset_set (set4, 1); mono_bitset_set (set4, 10); if (mono_bitset_count (set4) != 3) return error; error++; count = 0; for (i = mono_bitset_find_first (set4, -1); i != -1; i = mono_bitset_find_first (set4, i)) { count ++; switch (count) { case 1: if (i != 0) return error; break; case 2: if (i != 1) return error; break; case 3: if (i != 10) return error; break; } /* g_print ("count got: %d at %d\n", count, i); */ } if (count != 3) return error; error++; if (mono_bitset_find_first (set4, -1) != 0) return error; error++; /* 20 */ mono_bitset_set (set4, 31); if (mono_bitset_find_first (set4, 10) != 31) return error; error++; mono_bitset_free (set1); set1 = mono_bitset_new (200, 0); mono_bitset_set (set1, 0); mono_bitset_set (set1, 1); mono_bitset_set (set1, 10); mono_bitset_set (set1, 31); mono_bitset_set (set1, 150); mono_bitset_free (set1); mono_bitset_free (set2); mono_bitset_free (set3); mono_bitset_free (set4); g_print ("total tests passed: %d\n", error - 1); return 0; } #endif
-1
dotnet/runtime
66,462
Support using the system version of brotli
This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
omajid
2022-03-10T17:19:11Z
2022-03-23T03:49:50Z
c3e1d21c2fb30436ae24ef7ef4f458e3270bb7e3
5ca9223639700750ff12bb1fed9fa6e397062b78
Support using the system version of brotli . This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
./src/coreclr/hosts/corerun/CMakeLists.txt
project(corerun) set(CMAKE_INCLUDE_CURRENT_DIR ON) if(CLR_CMAKE_HOST_WIN32) add_definitions(-DFX_VER_INTERNALNAME_STR=corerun.exe) else(CLR_CMAKE_HOST_WIN32) include(configure.cmake) endif(CLR_CMAKE_HOST_WIN32) #Required to expose symbols for global symbol discovery. set(CLR_CMAKE_KEEP_NATIVE_SYMBOLS TRUE) add_executable_clr(corerun corerun.cpp dotenv.cpp native.rc ) if(CLR_CMAKE_HOST_WIN32) target_link_libraries(corerun advapi32.lib oleaut32.lib uuid.lib user32.lib ${STATIC_MT_CRT_LIB} ${STATIC_MT_VCRT_LIB} ) else(CLR_CMAKE_HOST_WIN32) target_link_libraries(corerun ${CMAKE_DL_LIBS}) # Required to expose symbols for global symbol discovery target_link_libraries(corerun -rdynamic) # Android implements pthread natively if(NOT CLR_CMAKE_TARGET_ANDROID) target_link_libraries(corerun pthread) endif() endif(CLR_CMAKE_HOST_WIN32) install_clr(TARGETS corerun DESTINATIONS . COMPONENT hosts)
project(corerun) set(CMAKE_INCLUDE_CURRENT_DIR ON) if(CLR_CMAKE_HOST_WIN32) add_definitions(-DFX_VER_INTERNALNAME_STR=corerun.exe) else(CLR_CMAKE_HOST_WIN32) include(configure.cmake) endif(CLR_CMAKE_HOST_WIN32) #Required to expose symbols for global symbol discovery. set(CLR_CMAKE_KEEP_NATIVE_SYMBOLS TRUE) add_executable_clr(corerun corerun.cpp dotenv.cpp native.rc ) if(CLR_CMAKE_HOST_WIN32) target_link_libraries(corerun advapi32.lib oleaut32.lib uuid.lib user32.lib ${STATIC_MT_CRT_LIB} ${STATIC_MT_VCRT_LIB} ) else(CLR_CMAKE_HOST_WIN32) target_link_libraries(corerun ${CMAKE_DL_LIBS}) # Required to expose symbols for global symbol discovery target_link_libraries(corerun -rdynamic) # Android implements pthread natively if(NOT CLR_CMAKE_TARGET_ANDROID) target_link_libraries(corerun pthread) endif() endif(CLR_CMAKE_HOST_WIN32) install_clr(TARGETS corerun DESTINATIONS . COMPONENT hosts)
-1
dotnet/runtime
66,462
Support using the system version of brotli
This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
omajid
2022-03-10T17:19:11Z
2022-03-23T03:49:50Z
c3e1d21c2fb30436ae24ef7ef4f458e3270bb7e3
5ca9223639700750ff12bb1fed9fa6e397062b78
Support using the system version of brotli . This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
./src/mono/wasm/runtime/driver.c
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include <emscripten.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <assert.h> #include <dlfcn.h> #include <sys/stat.h> #include <mono/metadata/appdomain.h> #include <mono/metadata/assembly.h> #include <mono/metadata/class.h> #include <mono/metadata/tokentype.h> #include <mono/metadata/threads.h> #include <mono/metadata/image.h> #include <mono/metadata/loader.h> #include <mono/metadata/mono-gc.h> #include <mono/metadata/object.h> // FIXME: unavailable in emscripten // #include <mono/metadata/gc-internals.h> #include <mono/metadata/mono-private-unstable.h> #include <mono/utils/mono-logger.h> #include <mono/utils/mono-dl-fallback.h> #include <mono/jit/jit.h> #include <mono/jit/mono-private-unstable.h> #include "pinvoke.h" #ifdef CORE_BINDINGS void core_initialize_internals (); #endif extern MonoString* mono_wasm_invoke_js (MonoString *str, int *is_exception); // Blazor specific custom routines - see dotnet_support.js for backing code extern void* mono_wasm_invoke_js_blazor (MonoString **exceptionMessage, void *callInfo, void* arg0, void* arg1, void* arg2); void mono_wasm_enable_debugging (int); int mono_wasm_marshal_type_from_mono_type (int mono_type, MonoClass *klass, MonoType *type); int mono_wasm_register_root (char *start, size_t size, const char *name); void mono_wasm_deregister_root (char *addr); void mono_ee_interp_init (const char *opts); void mono_marshal_ilgen_init (void); void mono_method_builder_ilgen_init (void); void mono_sgen_mono_ilgen_init (void); void mono_icall_table_init (void); void mono_aot_register_module (void **aot_info); char *monoeg_g_getenv(const char *variable); int monoeg_g_setenv(const char *variable, const char *value, int overwrite); int32_t monoeg_g_hasenv(const char *variable); void mono_free (void*); int32_t mini_parse_debug_option (const char *option); char *mono_method_get_full_name (MonoMethod *method); #define MARSHAL_TYPE_NULL 0 #define MARSHAL_TYPE_INT 1 #define MARSHAL_TYPE_FP64 2 #define MARSHAL_TYPE_STRING 3 #define MARSHAL_TYPE_VT 4 #define MARSHAL_TYPE_DELEGATE 5 #define MARSHAL_TYPE_TASK 6 #define MARSHAL_TYPE_OBJECT 7 #define MARSHAL_TYPE_BOOL 8 #define MARSHAL_TYPE_ENUM 9 #define MARSHAL_TYPE_DATE 20 #define MARSHAL_TYPE_DATEOFFSET 21 #define MARSHAL_TYPE_URI 22 #define MARSHAL_TYPE_SAFEHANDLE 23 // typed array marshalling #define MARSHAL_ARRAY_BYTE 10 #define MARSHAL_ARRAY_UBYTE 11 #define MARSHAL_ARRAY_UBYTE_C 12 #define MARSHAL_ARRAY_SHORT 13 #define MARSHAL_ARRAY_USHORT 14 #define MARSHAL_ARRAY_INT 15 #define MARSHAL_ARRAY_UINT 16 #define MARSHAL_ARRAY_FLOAT 17 #define MARSHAL_ARRAY_DOUBLE 18 #define MARSHAL_TYPE_FP32 24 #define MARSHAL_TYPE_UINT32 25 #define MARSHAL_TYPE_INT64 26 #define MARSHAL_TYPE_UINT64 27 #define MARSHAL_TYPE_CHAR 28 #define MARSHAL_TYPE_STRING_INTERNED 29 #define MARSHAL_TYPE_VOID 30 #define MARSHAL_TYPE_POINTER 32 // errors #define MARSHAL_ERROR_BUFFER_TOO_SMALL 512 #define MARSHAL_ERROR_NULL_CLASS_POINTER 513 #define MARSHAL_ERROR_NULL_TYPE_POINTER 514 static MonoClass* datetime_class; static MonoClass* datetimeoffset_class; static MonoClass* uri_class; static MonoClass* task_class; static MonoClass* safehandle_class; static MonoClass* voidtaskresult_class; static int resolved_datetime_class = 0, resolved_datetimeoffset_class = 0, resolved_uri_class = 0, resolved_task_class = 0, resolved_safehandle_class = 0, resolved_voidtaskresult_class = 0; int mono_wasm_enable_gc = 1; /* Not part of public headers */ #define MONO_ICALL_TABLE_CALLBACKS_VERSION 2 typedef struct { int version; void* (*lookup) (MonoMethod *method, char *classname, char *methodname, char *sigstart, int32_t *uses_handles); const char* (*lookup_icall_symbol) (void* func); } MonoIcallTableCallbacks; int mono_string_instance_is_interned (MonoString *str_raw); void mono_install_icall_table_callbacks (const MonoIcallTableCallbacks *cb); int mono_regression_test_step (int verbose_level, char *image, char *method_name); void mono_trace_init (void); #define g_new(type, size) ((type *) malloc (sizeof (type) * (size))) #define g_new0(type, size) ((type *) calloc (sizeof (type), (size))) static MonoDomain *root_domain; #define RUNTIMECONFIG_BIN_FILE "runtimeconfig.bin" extern void mono_wasm_trace_logger (const char *log_domain, const char *log_level, const char *message, mono_bool fatal, void *user_data); static void wasm_trace_logger (const char *log_domain, const char *log_level, const char *message, mono_bool fatal, void *user_data) { mono_wasm_trace_logger(log_domain, log_level, message, fatal, user_data); if (fatal) exit (1); } typedef uint32_t target_mword; typedef target_mword SgenDescriptor; typedef SgenDescriptor MonoGCDescriptor; MONO_API int mono_gc_register_root (char *start, size_t size, MonoGCDescriptor descr, MonoGCRootSource source, void *key, const char *msg); void mono_gc_deregister_root (char* addr); EMSCRIPTEN_KEEPALIVE int mono_wasm_register_root (char *start, size_t size, const char *name) { return mono_gc_register_root (start, size, (MonoGCDescriptor)NULL, MONO_ROOT_SOURCE_EXTERNAL, NULL, name ? name : "mono_wasm_register_root"); } EMSCRIPTEN_KEEPALIVE void mono_wasm_deregister_root (char *addr) { mono_gc_deregister_root (addr); } #ifdef DRIVER_GEN #include "driver-gen.c" #endif typedef struct WasmAssembly_ WasmAssembly; struct WasmAssembly_ { MonoBundledAssembly assembly; WasmAssembly *next; }; static WasmAssembly *assemblies; static int assembly_count; EMSCRIPTEN_KEEPALIVE int mono_wasm_add_assembly (const char *name, const unsigned char *data, unsigned int size) { int len = strlen (name); if (!strcasecmp (".pdb", &name [len - 4])) { char *new_name = strdup (name); //FIXME handle debugging assemblies with .exe extension strcpy (&new_name [len - 3], "dll"); mono_register_symfile_for_assembly (new_name, data, size); return 1; } WasmAssembly *entry = g_new0 (WasmAssembly, 1); entry->assembly.name = strdup (name); entry->assembly.data = data; entry->assembly.size = size; entry->next = assemblies; assemblies = entry; ++assembly_count; return mono_has_pdb_checksum ((char*)data, size); } int mono_wasm_assembly_already_added (const char *assembly_name) { if (assembly_count == 0) return 0; WasmAssembly *entry = assemblies; while (entry != NULL) { int entry_name_minus_extn_len = strlen(entry->assembly.name) - 4; if (entry_name_minus_extn_len == strlen(assembly_name) && strncmp (entry->assembly.name, assembly_name, entry_name_minus_extn_len) == 0) return 1; entry = entry->next; } return 0; } typedef struct WasmSatelliteAssembly_ WasmSatelliteAssembly; struct WasmSatelliteAssembly_ { MonoBundledSatelliteAssembly *assembly; WasmSatelliteAssembly *next; }; static WasmSatelliteAssembly *satellite_assemblies; static int satellite_assembly_count; EMSCRIPTEN_KEEPALIVE void mono_wasm_add_satellite_assembly (const char *name, const char *culture, const unsigned char *data, unsigned int size) { WasmSatelliteAssembly *entry = g_new0 (WasmSatelliteAssembly, 1); entry->assembly = mono_create_new_bundled_satellite_assembly (name, culture, data, size); entry->next = satellite_assemblies; satellite_assemblies = entry; ++satellite_assembly_count; } EMSCRIPTEN_KEEPALIVE void mono_wasm_setenv (const char *name, const char *value) { monoeg_g_setenv (strdup (name), strdup (value), 1); } static void *sysglobal_native_handle; static void* wasm_dl_load (const char *name, int flags, char **err, void *user_data) { void* handle = wasm_dl_lookup_pinvoke_table (name); if (handle) return handle; if (!strcmp (name, "System.Globalization.Native")) return sysglobal_native_handle; #if WASM_SUPPORTS_DLOPEN return dlopen(name, flags); #endif return NULL; } static void* wasm_dl_symbol (void *handle, const char *name, char **err, void *user_data) { if (handle == sysglobal_native_handle) assert (0); #if WASM_SUPPORTS_DLOPEN if (!wasm_dl_is_pinvoke_tables (handle)) { return dlsym (handle, name); } #endif PinvokeImport *table = (PinvokeImport*)handle; for (int i = 0; table [i].name; ++i) { if (!strcmp (table [i].name, name)) return table [i].func; } return NULL; } #if !defined(ENABLE_AOT) || defined(EE_MODE_LLVMONLY_INTERP) #define NEED_INTERP 1 #ifndef LINK_ICALLS // FIXME: llvm+interp mode needs this to call icalls #define NEED_NORMAL_ICALL_TABLES 1 #endif #endif #ifdef LINK_ICALLS #include "icall-table.h" static int compare_int (const void *k1, const void *k2) { return *(int*)k1 - *(int*)k2; } static void* icall_table_lookup (MonoMethod *method, char *classname, char *methodname, char *sigstart, int32_t *uses_handles) { uint32_t token = mono_method_get_token (method); assert (token); assert ((token & MONO_TOKEN_METHOD_DEF) == MONO_TOKEN_METHOD_DEF); uint32_t token_idx = token - MONO_TOKEN_METHOD_DEF; int *indexes = NULL; int indexes_size = 0; uint8_t *handles = NULL; void **funcs = NULL; *uses_handles = 0; const char *image_name = mono_image_get_name (mono_class_get_image (mono_method_get_class (method))); #if defined(ICALL_TABLE_mscorlib) if (!strcmp (image_name, "mscorlib")) { indexes = mscorlib_icall_indexes; indexes_size = sizeof (mscorlib_icall_indexes) / 4; handles = mscorlib_icall_handles; funcs = mscorlib_icall_funcs; assert (sizeof (mscorlib_icall_indexes [0]) == 4); } #endif #if defined(ICALL_TABLE_corlib) if (!strcmp (image_name, "System.Private.CoreLib")) { indexes = corlib_icall_indexes; indexes_size = sizeof (corlib_icall_indexes) / 4; handles = corlib_icall_handles; funcs = corlib_icall_funcs; assert (sizeof (corlib_icall_indexes [0]) == 4); } #endif #ifdef ICALL_TABLE_System if (!strcmp (image_name, "System")) { indexes = System_icall_indexes; indexes_size = sizeof (System_icall_indexes) / 4; handles = System_icall_handles; funcs = System_icall_funcs; } #endif assert (indexes); void *p = bsearch (&token_idx, indexes, indexes_size, 4, compare_int); if (!p) { return NULL; printf ("wasm: Unable to lookup icall: %s\n", mono_method_get_name (method)); exit (1); } uint32_t idx = (int*)p - indexes; *uses_handles = handles [idx]; //printf ("ICALL: %s %x %d %d\n", methodname, token, idx, (int)(funcs [idx])); return funcs [idx]; } static const char* icall_table_lookup_symbol (void *func) { assert (0); return NULL; } #endif /* * get_native_to_interp: * * Return a pointer to a wasm function which can be used to enter the interpreter to * execute METHOD from native code. * EXTRA_ARG is the argument passed to the interp entry functions in the runtime. */ void* get_native_to_interp (MonoMethod *method, void *extra_arg) { MonoClass *klass = mono_method_get_class (method); MonoImage *image = mono_class_get_image (klass); MonoAssembly *assembly = mono_image_get_assembly (image); MonoAssemblyName *aname = mono_assembly_get_name (assembly); const char *name = mono_assembly_name_get_name (aname); const char *class_name = mono_class_get_name (klass); const char *method_name = mono_method_get_name (method); char key [128]; int len; assert (strlen (name) < 100); snprintf (key, sizeof(key), "%s_%s_%s", name, class_name, method_name); len = strlen (key); for (int i = 0; i < len; ++i) { if (key [i] == '.') key [i] = '_'; } void *addr = wasm_dl_get_native_to_interp (key, extra_arg); return addr; } void mono_initialize_internals () { mono_add_internal_call ("Interop/Runtime::InvokeJS", mono_wasm_invoke_js); // TODO: what happens when two types in different assemblies have the same FQN? // Blazor specific custom routines - see dotnet_support.js for backing code mono_add_internal_call ("WebAssembly.JSInterop.InternalCalls::InvokeJS", mono_wasm_invoke_js_blazor); #ifdef CORE_BINDINGS core_initialize_internals(); #endif } EMSCRIPTEN_KEEPALIVE void mono_wasm_register_bundled_satellite_assemblies () { /* In legacy satellite_assembly_count is always false */ if (satellite_assembly_count) { MonoBundledSatelliteAssembly **satellite_bundle_array = g_new0 (MonoBundledSatelliteAssembly *, satellite_assembly_count + 1); WasmSatelliteAssembly *cur = satellite_assemblies; int i = 0; while (cur) { satellite_bundle_array [i] = cur->assembly; cur = cur->next; ++i; } mono_register_bundled_satellite_assemblies ((const MonoBundledSatelliteAssembly **)satellite_bundle_array); } } void mono_wasm_link_icu_shim (void); void cleanup_runtime_config (MonovmRuntimeConfigArguments *args, void *user_data) { free (args); free (user_data); } EMSCRIPTEN_KEEPALIVE void mono_wasm_load_runtime (const char *unused, int debug_level) { const char *interp_opts = ""; #ifndef INVARIANT_GLOBALIZATION mono_wasm_link_icu_shim (); #endif #ifdef DEBUG // monoeg_g_setenv ("MONO_LOG_LEVEL", "debug", 0); // monoeg_g_setenv ("MONO_LOG_MASK", "gc", 0); // Setting this env var allows Diagnostic.Debug to write to stderr. In a browser environment this // output will be sent to the console. Right now this is the only way to emit debug logging from // corlib assemblies. // monoeg_g_setenv ("COMPlus_DebugWriteToStdErr", "1", 0); #endif // When the list of app context properties changes, please update RuntimeConfigReservedProperties for // target _WasmGenerateRuntimeConfig in WasmApp.targets file const char *appctx_keys[2]; appctx_keys [0] = "APP_CONTEXT_BASE_DIRECTORY"; appctx_keys [1] = "RUNTIME_IDENTIFIER"; const char *appctx_values[2]; appctx_values [0] = "/"; appctx_values [1] = "browser-wasm"; char *file_name = RUNTIMECONFIG_BIN_FILE; int str_len = strlen (file_name) + 1; // +1 is for the "/" char *file_path = (char *)malloc (sizeof (char) * (str_len +1)); // +1 is for the terminating null character int num_char = snprintf (file_path, (str_len + 1), "/%s", file_name); struct stat buffer; assert (num_char > 0 && num_char == str_len); if (stat (file_path, &buffer) == 0) { MonovmRuntimeConfigArguments *arg = (MonovmRuntimeConfigArguments *)malloc (sizeof (MonovmRuntimeConfigArguments)); arg->kind = 0; arg->runtimeconfig.name.path = file_path; monovm_runtimeconfig_initialize (arg, cleanup_runtime_config, file_path); } else { free (file_path); } monovm_initialize (2, appctx_keys, appctx_values); mini_parse_debug_option ("top-runtime-invoke-unhandled"); mono_dl_fallback_register (wasm_dl_load, wasm_dl_symbol, NULL, NULL); mono_wasm_install_get_native_to_interp_tramp (get_native_to_interp); #ifdef ENABLE_AOT monoeg_g_setenv ("MONO_AOT_MODE", "aot", 1); // Defined in driver-gen.c register_aot_modules (); #ifdef EE_MODE_LLVMONLY_INTERP mono_jit_set_aot_mode (MONO_AOT_MODE_LLVMONLY_INTERP); #else mono_jit_set_aot_mode (MONO_AOT_MODE_LLVMONLY); #endif #else mono_jit_set_aot_mode (MONO_AOT_MODE_INTERP_ONLY); /* * debug_level > 0 enables debugging and sets the debug log level to debug_level * debug_level == 0 disables debugging and enables interpreter optimizations * debug_level < 0 enabled debugging and disables debug logging. * * Note: when debugging is enabled interpreter optimizations are disabled. */ if (debug_level) { // Disable optimizations which interfere with debugging interp_opts = "-all"; mono_wasm_enable_debugging (debug_level); } #endif #ifdef LINK_ICALLS /* Link in our own linked icall table */ static const MonoIcallTableCallbacks mono_icall_table_callbacks = { MONO_ICALL_TABLE_CALLBACKS_VERSION, icall_table_lookup, icall_table_lookup_symbol }; mono_install_icall_table_callbacks (&mono_icall_table_callbacks); #endif #ifdef NEED_NORMAL_ICALL_TABLES mono_icall_table_init (); #endif #ifdef NEED_INTERP mono_ee_interp_init (interp_opts); mono_marshal_ilgen_init (); mono_method_builder_ilgen_init (); mono_sgen_mono_ilgen_init (); #endif if (assembly_count) { MonoBundledAssembly **bundle_array = g_new0 (MonoBundledAssembly*, assembly_count + 1); WasmAssembly *cur = assemblies; int i = 0; while (cur) { bundle_array [i] = &cur->assembly; cur = cur->next; ++i; } mono_register_bundled_assemblies ((const MonoBundledAssembly **)bundle_array); } mono_wasm_register_bundled_satellite_assemblies (); mono_trace_init (); mono_trace_set_log_handler (wasm_trace_logger, NULL); root_domain = mono_jit_init_version ("mono", "v4.0.30319"); mono_initialize_internals(); mono_thread_set_main (mono_thread_current ()); } EMSCRIPTEN_KEEPALIVE MonoAssembly* mono_wasm_assembly_load (const char *name) { assert (name); MonoImageOpenStatus status; MonoAssemblyName* aname = mono_assembly_name_new (name); MonoAssembly *res = mono_assembly_load (aname, NULL, &status); mono_assembly_name_free (aname); return res; } EMSCRIPTEN_KEEPALIVE MonoAssembly* mono_wasm_get_corlib () { return mono_image_get_assembly (mono_get_corlib()); } EMSCRIPTEN_KEEPALIVE MonoClass* mono_wasm_assembly_find_class (MonoAssembly *assembly, const char *namespace, const char *name) { assert (assembly); return mono_class_from_name (mono_assembly_get_image (assembly), namespace, name); } EMSCRIPTEN_KEEPALIVE MonoMethod* mono_wasm_assembly_find_method (MonoClass *klass, const char *name, int arguments) { assert (klass); return mono_class_get_method_from_name (klass, name, arguments); } EMSCRIPTEN_KEEPALIVE MonoMethod* mono_wasm_get_delegate_invoke (MonoObject *delegate) { return mono_get_delegate_invoke(mono_object_get_class (delegate)); } EMSCRIPTEN_KEEPALIVE MonoObject* mono_wasm_box_primitive (MonoClass *klass, void *value, int value_size) { assert (klass); MonoType *type = mono_class_get_type (klass); int alignment; if (mono_type_size (type, &alignment) > value_size) return NULL; // TODO: use mono_value_box_checked and propagate error out return mono_value_box (root_domain, klass, value); } EMSCRIPTEN_KEEPALIVE MonoObject* mono_wasm_invoke_method (MonoMethod *method, MonoObject *this_arg, void *params[], MonoObject **out_exc) { MonoObject *exc = NULL; MonoObject *res; if (out_exc) *out_exc = NULL; res = mono_runtime_invoke (method, this_arg, params, &exc); if (exc) { if (out_exc) *out_exc = exc; MonoObject *exc2 = NULL; res = (MonoObject*)mono_object_to_string (exc, &exc2); if (exc2) res = (MonoObject*) mono_string_new (root_domain, "Exception Double Fault"); return res; } MonoMethodSignature *sig = mono_method_signature (method); MonoType *type = mono_signature_get_return_type (sig); // If the method return type is void return null // This gets around a memory access crash when the result return a value when // a void method is invoked. if (mono_type_get_type (type) == MONO_TYPE_VOID) return NULL; return res; } EMSCRIPTEN_KEEPALIVE MonoMethod* mono_wasm_assembly_get_entry_point (MonoAssembly *assembly) { MonoImage *image; MonoMethod *method; image = mono_assembly_get_image (assembly); uint32_t entry = mono_image_get_entry_point (image); if (!entry) return NULL; mono_domain_ensure_entry_assembly (root_domain, assembly); method = mono_get_method (image, entry, NULL); /* * If the entry point looks like a compiler generated wrapper around * an async method in the form "<Name>" then try to look up the async methods * "<Name>$" and "Name" it could be wrapping. We do this because the generated * sync wrapper will call task.GetAwaiter().GetResult() when we actually want * to yield to the host runtime. */ if (mono_method_get_flags (method, NULL) & 0x0800 /* METHOD_ATTRIBUTE_SPECIAL_NAME */) { const char *name = mono_method_get_name (method); int name_length = strlen (name); if ((*name != '<') || (name [name_length - 1] != '>')) return method; MonoClass *klass = mono_method_get_class (method); assert(klass); char *async_name = malloc (name_length + 2); snprintf (async_name, name_length + 2, "%s$", name); // look for "<Name>$" MonoMethodSignature *sig = mono_method_get_signature (method, image, mono_method_get_token (method)); MonoMethod *async_method = mono_class_get_method_from_name (klass, async_name, mono_signature_get_param_count (sig)); if (async_method != NULL) { free (async_name); return async_method; } // look for "Name" by trimming the first and last character of "<Name>" async_name [name_length - 1] = '\0'; async_method = mono_class_get_method_from_name (klass, async_name + 1, mono_signature_get_param_count (sig)); free (async_name); if (async_method != NULL) return async_method; } return method; } EMSCRIPTEN_KEEPALIVE char * mono_wasm_string_get_utf8 (MonoString *str) { return mono_string_to_utf8 (str); //XXX JS is responsible for freeing this } EMSCRIPTEN_KEEPALIVE MonoString * mono_wasm_string_from_js (const char *str) { if (str) return mono_string_new (root_domain, str); else return NULL; } EMSCRIPTEN_KEEPALIVE MonoString * mono_wasm_string_from_utf16 (const mono_unichar2 * chars, int length) { assert (length >= 0); if (chars) return mono_string_new_utf16 (root_domain, chars, length); else return NULL; } static int class_is_task (MonoClass *klass) { if (!klass) return 0; if (!task_class && !resolved_task_class) { task_class = mono_class_from_name (mono_get_corlib(), "System.Threading.Tasks", "Task"); resolved_task_class = 1; } if (task_class && (klass == task_class || mono_class_is_subclass_of(klass, task_class, 0))) return 1; return 0; } MonoClass* mono_get_uri_class(MonoException** exc) { MonoAssembly* assembly = mono_wasm_assembly_load ("System"); if (!assembly) return NULL; MonoClass* klass = mono_wasm_assembly_find_class(assembly, "System", "Uri"); return klass; } void mono_wasm_ensure_classes_resolved () { if (!datetime_class && !resolved_datetime_class) { datetime_class = mono_class_from_name (mono_get_corlib(), "System", "DateTime"); resolved_datetime_class = 1; } if (!datetimeoffset_class && !resolved_datetimeoffset_class) { datetimeoffset_class = mono_class_from_name (mono_get_corlib(), "System", "DateTimeOffset"); resolved_datetimeoffset_class = 1; } if (!uri_class && !resolved_uri_class) { MonoException** exc = NULL; uri_class = mono_get_uri_class(exc); resolved_uri_class = 1; } if (!safehandle_class && !resolved_safehandle_class) { safehandle_class = mono_class_from_name (mono_get_corlib(), "System.Runtime.InteropServices", "SafeHandle"); resolved_safehandle_class = 1; } if (!voidtaskresult_class && !resolved_voidtaskresult_class) { voidtaskresult_class = mono_class_from_name (mono_get_corlib(), "System.Threading.Tasks", "VoidTaskResult"); resolved_voidtaskresult_class = 1; } } int mono_wasm_marshal_type_from_mono_type (int mono_type, MonoClass *klass, MonoType *type) { switch (mono_type) { // case MONO_TYPE_CHAR: prob should be done not as a number? case MONO_TYPE_VOID: return MARSHAL_TYPE_VOID; case MONO_TYPE_BOOLEAN: return MARSHAL_TYPE_BOOL; case MONO_TYPE_I: // IntPtr case MONO_TYPE_U: // UIntPtr case MONO_TYPE_PTR: return MARSHAL_TYPE_POINTER; case MONO_TYPE_I1: case MONO_TYPE_U1: case MONO_TYPE_I2: case MONO_TYPE_U2: case MONO_TYPE_I4: return MARSHAL_TYPE_INT; case MONO_TYPE_CHAR: return MARSHAL_TYPE_CHAR; case MONO_TYPE_U4: // The distinction between this and signed int is // important due to how numbers work in JavaScript return MARSHAL_TYPE_UINT32; case MONO_TYPE_I8: return MARSHAL_TYPE_INT64; case MONO_TYPE_U8: return MARSHAL_TYPE_UINT64; case MONO_TYPE_R4: return MARSHAL_TYPE_FP32; case MONO_TYPE_R8: return MARSHAL_TYPE_FP64; case MONO_TYPE_STRING: return MARSHAL_TYPE_STRING; case MONO_TYPE_SZARRAY: { // simple zero based one-dim-array if (klass) { MonoClass *eklass = mono_class_get_element_class (klass); MonoType *etype = mono_class_get_type (eklass); switch (mono_type_get_type (etype)) { case MONO_TYPE_U1: return MARSHAL_ARRAY_UBYTE; case MONO_TYPE_I1: return MARSHAL_ARRAY_BYTE; case MONO_TYPE_U2: return MARSHAL_ARRAY_USHORT; case MONO_TYPE_I2: return MARSHAL_ARRAY_SHORT; case MONO_TYPE_U4: return MARSHAL_ARRAY_UINT; case MONO_TYPE_I4: return MARSHAL_ARRAY_INT; case MONO_TYPE_R4: return MARSHAL_ARRAY_FLOAT; case MONO_TYPE_R8: return MARSHAL_ARRAY_DOUBLE; default: return MARSHAL_TYPE_OBJECT; } } else { return MARSHAL_TYPE_OBJECT; } } default: mono_wasm_ensure_classes_resolved (); if (klass) { if (klass == datetime_class) return MARSHAL_TYPE_DATE; if (klass == datetimeoffset_class) return MARSHAL_TYPE_DATEOFFSET; if (uri_class && mono_class_is_assignable_from(uri_class, klass)) return MARSHAL_TYPE_URI; if (klass == voidtaskresult_class) return MARSHAL_TYPE_VOID; if (mono_class_is_enum (klass)) return MARSHAL_TYPE_ENUM; if (type && !mono_type_is_reference (type)) //vt return MARSHAL_TYPE_VT; if (mono_class_is_delegate (klass)) return MARSHAL_TYPE_DELEGATE; if (class_is_task(klass)) return MARSHAL_TYPE_TASK; if (safehandle_class && (klass == safehandle_class || mono_class_is_subclass_of(klass, safehandle_class, 0))) return MARSHAL_TYPE_SAFEHANDLE; } return MARSHAL_TYPE_OBJECT; } } EMSCRIPTEN_KEEPALIVE MonoClass * mono_wasm_get_obj_class (MonoObject *obj) { if (!obj) return NULL; return mono_object_get_class (obj); } EMSCRIPTEN_KEEPALIVE int mono_wasm_get_obj_type (MonoObject *obj) { if (!obj) return 0; /* Process obj before calling into the runtime, class_from_name () can invoke managed code */ MonoClass *klass = mono_object_get_class (obj); if (!klass) return MARSHAL_ERROR_NULL_CLASS_POINTER; if ((klass == mono_get_string_class ()) && mono_string_instance_is_interned ((MonoString *)obj)) return MARSHAL_TYPE_STRING_INTERNED; MonoType *type = mono_class_get_type (klass); if (!type) return MARSHAL_ERROR_NULL_TYPE_POINTER; obj = NULL; int mono_type = mono_type_get_type (type); return mono_wasm_marshal_type_from_mono_type (mono_type, klass, type); } EMSCRIPTEN_KEEPALIVE int mono_wasm_try_unbox_primitive_and_get_type (MonoObject *obj, void *result, int result_capacity) { void **resultP = result; int *resultI = result; int64_t *resultL = result; float *resultF = result; double *resultD = result; if (result_capacity >= sizeof (int64_t)) *resultL = 0; else if (result_capacity >= sizeof (int)) *resultI = 0; if (!result) return MARSHAL_ERROR_BUFFER_TOO_SMALL; if (result_capacity < 16) return MARSHAL_ERROR_BUFFER_TOO_SMALL; if (!obj) return MARSHAL_TYPE_NULL; /* Process obj before calling into the runtime, class_from_name () can invoke managed code */ MonoClass *klass = mono_object_get_class (obj); if (!klass) return MARSHAL_ERROR_NULL_CLASS_POINTER; MonoType *type = mono_class_get_type (klass), *original_type = type; if (!type) return MARSHAL_ERROR_NULL_TYPE_POINTER; if ((klass == mono_get_string_class ()) && mono_string_instance_is_interned ((MonoString *)obj)) { *resultL = 0; *resultP = type; return MARSHAL_TYPE_STRING_INTERNED; } if (mono_class_is_enum (klass)) type = mono_type_get_underlying_type (type); if (!type) return MARSHAL_ERROR_NULL_TYPE_POINTER; int mono_type = mono_type_get_type (type); if (mono_type == MONO_TYPE_GENERICINST) { // HACK: While the 'any other type' fallback is valid for classes, it will do the // wrong thing for structs, so we need to make sure the valuetype handler is used if (mono_type_generic_inst_is_valuetype (type)) mono_type = MONO_TYPE_VALUETYPE; } // FIXME: We would prefer to unbox once here but it will fail if the value isn't unboxable switch (mono_type) { case MONO_TYPE_I1: case MONO_TYPE_BOOLEAN: *resultI = *(signed char*)mono_object_unbox (obj); break; case MONO_TYPE_U1: *resultI = *(unsigned char*)mono_object_unbox (obj); break; case MONO_TYPE_I2: case MONO_TYPE_CHAR: *resultI = *(short*)mono_object_unbox (obj); break; case MONO_TYPE_U2: *resultI = *(unsigned short*)mono_object_unbox (obj); break; case MONO_TYPE_I4: case MONO_TYPE_I: *resultI = *(int*)mono_object_unbox (obj); break; case MONO_TYPE_U4: // FIXME: Will this behave the way we want for large unsigned values? *resultI = *(int*)mono_object_unbox (obj); break; case MONO_TYPE_R4: *resultF = *(float*)mono_object_unbox (obj); break; case MONO_TYPE_R8: *resultD = *(double*)mono_object_unbox (obj); break; case MONO_TYPE_PTR: *resultL = (int64_t)(*(void**)mono_object_unbox (obj)); break; case MONO_TYPE_I8: case MONO_TYPE_U8: // FIXME: At present the javascript side of things can't handle this, // but there's no reason not to future-proof this API *resultL = *(int64_t*)mono_object_unbox (obj); break; case MONO_TYPE_VALUETYPE: { int obj_size = mono_object_get_size (obj), required_size = (sizeof (int)) + (sizeof (MonoType *)) + obj_size; // Check whether this struct has special-case marshaling // FIXME: Do we need to null out obj before this? int marshal_type = mono_wasm_marshal_type_from_mono_type (mono_type, klass, original_type); if (marshal_type != MARSHAL_TYPE_VT) return marshal_type; // Check whether the result buffer is big enough for the struct and padding if (result_capacity < required_size) return MARSHAL_ERROR_BUFFER_TOO_SMALL; // Store a header before the struct data with the size of the data and its MonoType *resultP = type; int * resultSize = (int *)(resultP + 1); *resultSize = obj_size; void * resultVoid = (resultP + 2); void * unboxed = mono_object_unbox (obj); memcpy (resultVoid, unboxed, obj_size); return MARSHAL_TYPE_VT; } break; default: // If we failed to do a fast unboxing, return the original type information so // that the caller can do a proper, slow unboxing later // HACK: Store the class pointer into the result buffer so our caller doesn't // have to call back into the native runtime later to get it *resultP = type; obj = NULL; int fallbackResultType = mono_wasm_marshal_type_from_mono_type (mono_type, klass, original_type); assert (fallbackResultType != MARSHAL_TYPE_VT); return fallbackResultType; } // We successfully performed a fast unboxing here so use the type information // matching what we unboxed (i.e. an enum's underlying type instead of its type) obj = NULL; int resultType = mono_wasm_marshal_type_from_mono_type (mono_type, klass, type); assert (resultType != MARSHAL_TYPE_VT); return resultType; } EMSCRIPTEN_KEEPALIVE int mono_wasm_array_length (MonoArray *array) { return mono_array_length (array); } EMSCRIPTEN_KEEPALIVE MonoObject* mono_wasm_array_get (MonoArray *array, int idx) { return mono_array_get (array, MonoObject*, idx); } EMSCRIPTEN_KEEPALIVE MonoArray* mono_wasm_obj_array_new (int size) { return mono_array_new (root_domain, mono_get_object_class (), size); } EMSCRIPTEN_KEEPALIVE void mono_wasm_obj_array_set (MonoArray *array, int idx, MonoObject *obj) { mono_array_setref (array, idx, obj); } EMSCRIPTEN_KEEPALIVE MonoArray* mono_wasm_string_array_new (int size) { return mono_array_new (root_domain, mono_get_string_class (), size); } EMSCRIPTEN_KEEPALIVE int mono_wasm_exec_regression (int verbose_level, char *image) { return mono_regression_test_step (verbose_level, image, NULL) ? 0 : 1; } EMSCRIPTEN_KEEPALIVE int mono_wasm_exit (int exit_code) { exit (exit_code); } EMSCRIPTEN_KEEPALIVE void mono_wasm_set_main_args (int argc, char* argv[]) { mono_runtime_set_main_args (argc, argv); } EMSCRIPTEN_KEEPALIVE int mono_wasm_strdup (const char *s) { return (int)strdup (s); } EMSCRIPTEN_KEEPALIVE void mono_wasm_parse_runtime_options (int argc, char* argv[]) { mono_jit_parse_options (argc, argv); } EMSCRIPTEN_KEEPALIVE void mono_wasm_enable_on_demand_gc (int enable) { mono_wasm_enable_gc = enable ? 1 : 0; } EMSCRIPTEN_KEEPALIVE MonoString * mono_wasm_intern_string (MonoString *string) { return mono_string_intern (string); } EMSCRIPTEN_KEEPALIVE void mono_wasm_string_get_data ( MonoString *string, mono_unichar2 **outChars, int *outLengthBytes, int *outIsInterned ) { if (!string) { if (outChars) *outChars = 0; if (outLengthBytes) *outLengthBytes = 0; if (outIsInterned) *outIsInterned = 1; return; } if (outChars) *outChars = mono_string_chars (string); if (outLengthBytes) *outLengthBytes = mono_string_length (string) * 2; if (outIsInterned) *outIsInterned = mono_string_instance_is_interned (string); return; } EMSCRIPTEN_KEEPALIVE MonoType * mono_wasm_class_get_type (MonoClass *klass) { if (!klass) return NULL; return mono_class_get_type (klass); } EMSCRIPTEN_KEEPALIVE MonoClass * mono_wasm_type_get_class (MonoType *type) { if (!type) return NULL; return mono_type_get_class (type); } EMSCRIPTEN_KEEPALIVE void * mono_wasm_unbox_rooted (MonoObject *obj) { if (!obj) return NULL; return mono_object_unbox (obj); } EMSCRIPTEN_KEEPALIVE char * mono_wasm_get_type_name (MonoType * typePtr) { return mono_type_get_name_full (typePtr, MONO_TYPE_NAME_FORMAT_REFLECTION); } EMSCRIPTEN_KEEPALIVE char * mono_wasm_get_type_aqn (MonoType * typePtr) { return mono_type_get_name_full (typePtr, MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED); } #ifdef ENABLE_AOT_PROFILER void mono_profiler_init_aot (const char *desc); EMSCRIPTEN_KEEPALIVE void mono_wasm_load_profiler_aot (const char *desc) { mono_profiler_init_aot (desc); } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include <emscripten.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <assert.h> #include <dlfcn.h> #include <sys/stat.h> #include <mono/metadata/appdomain.h> #include <mono/metadata/assembly.h> #include <mono/metadata/class.h> #include <mono/metadata/tokentype.h> #include <mono/metadata/threads.h> #include <mono/metadata/image.h> #include <mono/metadata/loader.h> #include <mono/metadata/mono-gc.h> #include <mono/metadata/object.h> // FIXME: unavailable in emscripten // #include <mono/metadata/gc-internals.h> #include <mono/metadata/mono-private-unstable.h> #include <mono/utils/mono-logger.h> #include <mono/utils/mono-dl-fallback.h> #include <mono/jit/jit.h> #include <mono/jit/mono-private-unstable.h> #include "pinvoke.h" #ifdef CORE_BINDINGS void core_initialize_internals (); #endif extern MonoString* mono_wasm_invoke_js (MonoString *str, int *is_exception); // Blazor specific custom routines - see dotnet_support.js for backing code extern void* mono_wasm_invoke_js_blazor (MonoString **exceptionMessage, void *callInfo, void* arg0, void* arg1, void* arg2); void mono_wasm_enable_debugging (int); int mono_wasm_marshal_type_from_mono_type (int mono_type, MonoClass *klass, MonoType *type); int mono_wasm_register_root (char *start, size_t size, const char *name); void mono_wasm_deregister_root (char *addr); void mono_ee_interp_init (const char *opts); void mono_marshal_ilgen_init (void); void mono_method_builder_ilgen_init (void); void mono_sgen_mono_ilgen_init (void); void mono_icall_table_init (void); void mono_aot_register_module (void **aot_info); char *monoeg_g_getenv(const char *variable); int monoeg_g_setenv(const char *variable, const char *value, int overwrite); int32_t monoeg_g_hasenv(const char *variable); void mono_free (void*); int32_t mini_parse_debug_option (const char *option); char *mono_method_get_full_name (MonoMethod *method); #define MARSHAL_TYPE_NULL 0 #define MARSHAL_TYPE_INT 1 #define MARSHAL_TYPE_FP64 2 #define MARSHAL_TYPE_STRING 3 #define MARSHAL_TYPE_VT 4 #define MARSHAL_TYPE_DELEGATE 5 #define MARSHAL_TYPE_TASK 6 #define MARSHAL_TYPE_OBJECT 7 #define MARSHAL_TYPE_BOOL 8 #define MARSHAL_TYPE_ENUM 9 #define MARSHAL_TYPE_DATE 20 #define MARSHAL_TYPE_DATEOFFSET 21 #define MARSHAL_TYPE_URI 22 #define MARSHAL_TYPE_SAFEHANDLE 23 // typed array marshalling #define MARSHAL_ARRAY_BYTE 10 #define MARSHAL_ARRAY_UBYTE 11 #define MARSHAL_ARRAY_UBYTE_C 12 #define MARSHAL_ARRAY_SHORT 13 #define MARSHAL_ARRAY_USHORT 14 #define MARSHAL_ARRAY_INT 15 #define MARSHAL_ARRAY_UINT 16 #define MARSHAL_ARRAY_FLOAT 17 #define MARSHAL_ARRAY_DOUBLE 18 #define MARSHAL_TYPE_FP32 24 #define MARSHAL_TYPE_UINT32 25 #define MARSHAL_TYPE_INT64 26 #define MARSHAL_TYPE_UINT64 27 #define MARSHAL_TYPE_CHAR 28 #define MARSHAL_TYPE_STRING_INTERNED 29 #define MARSHAL_TYPE_VOID 30 #define MARSHAL_TYPE_POINTER 32 // errors #define MARSHAL_ERROR_BUFFER_TOO_SMALL 512 #define MARSHAL_ERROR_NULL_CLASS_POINTER 513 #define MARSHAL_ERROR_NULL_TYPE_POINTER 514 static MonoClass* datetime_class; static MonoClass* datetimeoffset_class; static MonoClass* uri_class; static MonoClass* task_class; static MonoClass* safehandle_class; static MonoClass* voidtaskresult_class; static int resolved_datetime_class = 0, resolved_datetimeoffset_class = 0, resolved_uri_class = 0, resolved_task_class = 0, resolved_safehandle_class = 0, resolved_voidtaskresult_class = 0; int mono_wasm_enable_gc = 1; /* Not part of public headers */ #define MONO_ICALL_TABLE_CALLBACKS_VERSION 2 typedef struct { int version; void* (*lookup) (MonoMethod *method, char *classname, char *methodname, char *sigstart, int32_t *uses_handles); const char* (*lookup_icall_symbol) (void* func); } MonoIcallTableCallbacks; int mono_string_instance_is_interned (MonoString *str_raw); void mono_install_icall_table_callbacks (const MonoIcallTableCallbacks *cb); int mono_regression_test_step (int verbose_level, char *image, char *method_name); void mono_trace_init (void); #define g_new(type, size) ((type *) malloc (sizeof (type) * (size))) #define g_new0(type, size) ((type *) calloc (sizeof (type), (size))) static MonoDomain *root_domain; #define RUNTIMECONFIG_BIN_FILE "runtimeconfig.bin" extern void mono_wasm_trace_logger (const char *log_domain, const char *log_level, const char *message, mono_bool fatal, void *user_data); static void wasm_trace_logger (const char *log_domain, const char *log_level, const char *message, mono_bool fatal, void *user_data) { mono_wasm_trace_logger(log_domain, log_level, message, fatal, user_data); if (fatal) exit (1); } typedef uint32_t target_mword; typedef target_mword SgenDescriptor; typedef SgenDescriptor MonoGCDescriptor; MONO_API int mono_gc_register_root (char *start, size_t size, MonoGCDescriptor descr, MonoGCRootSource source, void *key, const char *msg); void mono_gc_deregister_root (char* addr); EMSCRIPTEN_KEEPALIVE int mono_wasm_register_root (char *start, size_t size, const char *name) { return mono_gc_register_root (start, size, (MonoGCDescriptor)NULL, MONO_ROOT_SOURCE_EXTERNAL, NULL, name ? name : "mono_wasm_register_root"); } EMSCRIPTEN_KEEPALIVE void mono_wasm_deregister_root (char *addr) { mono_gc_deregister_root (addr); } #ifdef DRIVER_GEN #include "driver-gen.c" #endif typedef struct WasmAssembly_ WasmAssembly; struct WasmAssembly_ { MonoBundledAssembly assembly; WasmAssembly *next; }; static WasmAssembly *assemblies; static int assembly_count; EMSCRIPTEN_KEEPALIVE int mono_wasm_add_assembly (const char *name, const unsigned char *data, unsigned int size) { int len = strlen (name); if (!strcasecmp (".pdb", &name [len - 4])) { char *new_name = strdup (name); //FIXME handle debugging assemblies with .exe extension strcpy (&new_name [len - 3], "dll"); mono_register_symfile_for_assembly (new_name, data, size); return 1; } WasmAssembly *entry = g_new0 (WasmAssembly, 1); entry->assembly.name = strdup (name); entry->assembly.data = data; entry->assembly.size = size; entry->next = assemblies; assemblies = entry; ++assembly_count; return mono_has_pdb_checksum ((char*)data, size); } int mono_wasm_assembly_already_added (const char *assembly_name) { if (assembly_count == 0) return 0; WasmAssembly *entry = assemblies; while (entry != NULL) { int entry_name_minus_extn_len = strlen(entry->assembly.name) - 4; if (entry_name_minus_extn_len == strlen(assembly_name) && strncmp (entry->assembly.name, assembly_name, entry_name_minus_extn_len) == 0) return 1; entry = entry->next; } return 0; } typedef struct WasmSatelliteAssembly_ WasmSatelliteAssembly; struct WasmSatelliteAssembly_ { MonoBundledSatelliteAssembly *assembly; WasmSatelliteAssembly *next; }; static WasmSatelliteAssembly *satellite_assemblies; static int satellite_assembly_count; EMSCRIPTEN_KEEPALIVE void mono_wasm_add_satellite_assembly (const char *name, const char *culture, const unsigned char *data, unsigned int size) { WasmSatelliteAssembly *entry = g_new0 (WasmSatelliteAssembly, 1); entry->assembly = mono_create_new_bundled_satellite_assembly (name, culture, data, size); entry->next = satellite_assemblies; satellite_assemblies = entry; ++satellite_assembly_count; } EMSCRIPTEN_KEEPALIVE void mono_wasm_setenv (const char *name, const char *value) { monoeg_g_setenv (strdup (name), strdup (value), 1); } static void *sysglobal_native_handle; static void* wasm_dl_load (const char *name, int flags, char **err, void *user_data) { void* handle = wasm_dl_lookup_pinvoke_table (name); if (handle) return handle; if (!strcmp (name, "System.Globalization.Native")) return sysglobal_native_handle; #if WASM_SUPPORTS_DLOPEN return dlopen(name, flags); #endif return NULL; } static void* wasm_dl_symbol (void *handle, const char *name, char **err, void *user_data) { if (handle == sysglobal_native_handle) assert (0); #if WASM_SUPPORTS_DLOPEN if (!wasm_dl_is_pinvoke_tables (handle)) { return dlsym (handle, name); } #endif PinvokeImport *table = (PinvokeImport*)handle; for (int i = 0; table [i].name; ++i) { if (!strcmp (table [i].name, name)) return table [i].func; } return NULL; } #if !defined(ENABLE_AOT) || defined(EE_MODE_LLVMONLY_INTERP) #define NEED_INTERP 1 #ifndef LINK_ICALLS // FIXME: llvm+interp mode needs this to call icalls #define NEED_NORMAL_ICALL_TABLES 1 #endif #endif #ifdef LINK_ICALLS #include "icall-table.h" static int compare_int (const void *k1, const void *k2) { return *(int*)k1 - *(int*)k2; } static void* icall_table_lookup (MonoMethod *method, char *classname, char *methodname, char *sigstart, int32_t *uses_handles) { uint32_t token = mono_method_get_token (method); assert (token); assert ((token & MONO_TOKEN_METHOD_DEF) == MONO_TOKEN_METHOD_DEF); uint32_t token_idx = token - MONO_TOKEN_METHOD_DEF; int *indexes = NULL; int indexes_size = 0; uint8_t *handles = NULL; void **funcs = NULL; *uses_handles = 0; const char *image_name = mono_image_get_name (mono_class_get_image (mono_method_get_class (method))); #if defined(ICALL_TABLE_mscorlib) if (!strcmp (image_name, "mscorlib")) { indexes = mscorlib_icall_indexes; indexes_size = sizeof (mscorlib_icall_indexes) / 4; handles = mscorlib_icall_handles; funcs = mscorlib_icall_funcs; assert (sizeof (mscorlib_icall_indexes [0]) == 4); } #endif #if defined(ICALL_TABLE_corlib) if (!strcmp (image_name, "System.Private.CoreLib")) { indexes = corlib_icall_indexes; indexes_size = sizeof (corlib_icall_indexes) / 4; handles = corlib_icall_handles; funcs = corlib_icall_funcs; assert (sizeof (corlib_icall_indexes [0]) == 4); } #endif #ifdef ICALL_TABLE_System if (!strcmp (image_name, "System")) { indexes = System_icall_indexes; indexes_size = sizeof (System_icall_indexes) / 4; handles = System_icall_handles; funcs = System_icall_funcs; } #endif assert (indexes); void *p = bsearch (&token_idx, indexes, indexes_size, 4, compare_int); if (!p) { return NULL; printf ("wasm: Unable to lookup icall: %s\n", mono_method_get_name (method)); exit (1); } uint32_t idx = (int*)p - indexes; *uses_handles = handles [idx]; //printf ("ICALL: %s %x %d %d\n", methodname, token, idx, (int)(funcs [idx])); return funcs [idx]; } static const char* icall_table_lookup_symbol (void *func) { assert (0); return NULL; } #endif /* * get_native_to_interp: * * Return a pointer to a wasm function which can be used to enter the interpreter to * execute METHOD from native code. * EXTRA_ARG is the argument passed to the interp entry functions in the runtime. */ void* get_native_to_interp (MonoMethod *method, void *extra_arg) { MonoClass *klass = mono_method_get_class (method); MonoImage *image = mono_class_get_image (klass); MonoAssembly *assembly = mono_image_get_assembly (image); MonoAssemblyName *aname = mono_assembly_get_name (assembly); const char *name = mono_assembly_name_get_name (aname); const char *class_name = mono_class_get_name (klass); const char *method_name = mono_method_get_name (method); char key [128]; int len; assert (strlen (name) < 100); snprintf (key, sizeof(key), "%s_%s_%s", name, class_name, method_name); len = strlen (key); for (int i = 0; i < len; ++i) { if (key [i] == '.') key [i] = '_'; } void *addr = wasm_dl_get_native_to_interp (key, extra_arg); return addr; } void mono_initialize_internals () { mono_add_internal_call ("Interop/Runtime::InvokeJS", mono_wasm_invoke_js); // TODO: what happens when two types in different assemblies have the same FQN? // Blazor specific custom routines - see dotnet_support.js for backing code mono_add_internal_call ("WebAssembly.JSInterop.InternalCalls::InvokeJS", mono_wasm_invoke_js_blazor); #ifdef CORE_BINDINGS core_initialize_internals(); #endif } EMSCRIPTEN_KEEPALIVE void mono_wasm_register_bundled_satellite_assemblies () { /* In legacy satellite_assembly_count is always false */ if (satellite_assembly_count) { MonoBundledSatelliteAssembly **satellite_bundle_array = g_new0 (MonoBundledSatelliteAssembly *, satellite_assembly_count + 1); WasmSatelliteAssembly *cur = satellite_assemblies; int i = 0; while (cur) { satellite_bundle_array [i] = cur->assembly; cur = cur->next; ++i; } mono_register_bundled_satellite_assemblies ((const MonoBundledSatelliteAssembly **)satellite_bundle_array); } } void mono_wasm_link_icu_shim (void); void cleanup_runtime_config (MonovmRuntimeConfigArguments *args, void *user_data) { free (args); free (user_data); } EMSCRIPTEN_KEEPALIVE void mono_wasm_load_runtime (const char *unused, int debug_level) { const char *interp_opts = ""; #ifndef INVARIANT_GLOBALIZATION mono_wasm_link_icu_shim (); #endif #ifdef DEBUG // monoeg_g_setenv ("MONO_LOG_LEVEL", "debug", 0); // monoeg_g_setenv ("MONO_LOG_MASK", "gc", 0); // Setting this env var allows Diagnostic.Debug to write to stderr. In a browser environment this // output will be sent to the console. Right now this is the only way to emit debug logging from // corlib assemblies. // monoeg_g_setenv ("COMPlus_DebugWriteToStdErr", "1", 0); #endif // When the list of app context properties changes, please update RuntimeConfigReservedProperties for // target _WasmGenerateRuntimeConfig in WasmApp.targets file const char *appctx_keys[2]; appctx_keys [0] = "APP_CONTEXT_BASE_DIRECTORY"; appctx_keys [1] = "RUNTIME_IDENTIFIER"; const char *appctx_values[2]; appctx_values [0] = "/"; appctx_values [1] = "browser-wasm"; char *file_name = RUNTIMECONFIG_BIN_FILE; int str_len = strlen (file_name) + 1; // +1 is for the "/" char *file_path = (char *)malloc (sizeof (char) * (str_len +1)); // +1 is for the terminating null character int num_char = snprintf (file_path, (str_len + 1), "/%s", file_name); struct stat buffer; assert (num_char > 0 && num_char == str_len); if (stat (file_path, &buffer) == 0) { MonovmRuntimeConfigArguments *arg = (MonovmRuntimeConfigArguments *)malloc (sizeof (MonovmRuntimeConfigArguments)); arg->kind = 0; arg->runtimeconfig.name.path = file_path; monovm_runtimeconfig_initialize (arg, cleanup_runtime_config, file_path); } else { free (file_path); } monovm_initialize (2, appctx_keys, appctx_values); mini_parse_debug_option ("top-runtime-invoke-unhandled"); mono_dl_fallback_register (wasm_dl_load, wasm_dl_symbol, NULL, NULL); mono_wasm_install_get_native_to_interp_tramp (get_native_to_interp); #ifdef ENABLE_AOT monoeg_g_setenv ("MONO_AOT_MODE", "aot", 1); // Defined in driver-gen.c register_aot_modules (); #ifdef EE_MODE_LLVMONLY_INTERP mono_jit_set_aot_mode (MONO_AOT_MODE_LLVMONLY_INTERP); #else mono_jit_set_aot_mode (MONO_AOT_MODE_LLVMONLY); #endif #else mono_jit_set_aot_mode (MONO_AOT_MODE_INTERP_ONLY); /* * debug_level > 0 enables debugging and sets the debug log level to debug_level * debug_level == 0 disables debugging and enables interpreter optimizations * debug_level < 0 enabled debugging and disables debug logging. * * Note: when debugging is enabled interpreter optimizations are disabled. */ if (debug_level) { // Disable optimizations which interfere with debugging interp_opts = "-all"; mono_wasm_enable_debugging (debug_level); } #endif #ifdef LINK_ICALLS /* Link in our own linked icall table */ static const MonoIcallTableCallbacks mono_icall_table_callbacks = { MONO_ICALL_TABLE_CALLBACKS_VERSION, icall_table_lookup, icall_table_lookup_symbol }; mono_install_icall_table_callbacks (&mono_icall_table_callbacks); #endif #ifdef NEED_NORMAL_ICALL_TABLES mono_icall_table_init (); #endif #ifdef NEED_INTERP mono_ee_interp_init (interp_opts); mono_marshal_ilgen_init (); mono_method_builder_ilgen_init (); mono_sgen_mono_ilgen_init (); #endif if (assembly_count) { MonoBundledAssembly **bundle_array = g_new0 (MonoBundledAssembly*, assembly_count + 1); WasmAssembly *cur = assemblies; int i = 0; while (cur) { bundle_array [i] = &cur->assembly; cur = cur->next; ++i; } mono_register_bundled_assemblies ((const MonoBundledAssembly **)bundle_array); } mono_wasm_register_bundled_satellite_assemblies (); mono_trace_init (); mono_trace_set_log_handler (wasm_trace_logger, NULL); root_domain = mono_jit_init_version ("mono", "v4.0.30319"); mono_initialize_internals(); mono_thread_set_main (mono_thread_current ()); } EMSCRIPTEN_KEEPALIVE MonoAssembly* mono_wasm_assembly_load (const char *name) { assert (name); MonoImageOpenStatus status; MonoAssemblyName* aname = mono_assembly_name_new (name); MonoAssembly *res = mono_assembly_load (aname, NULL, &status); mono_assembly_name_free (aname); return res; } EMSCRIPTEN_KEEPALIVE MonoAssembly* mono_wasm_get_corlib () { return mono_image_get_assembly (mono_get_corlib()); } EMSCRIPTEN_KEEPALIVE MonoClass* mono_wasm_assembly_find_class (MonoAssembly *assembly, const char *namespace, const char *name) { assert (assembly); return mono_class_from_name (mono_assembly_get_image (assembly), namespace, name); } EMSCRIPTEN_KEEPALIVE MonoMethod* mono_wasm_assembly_find_method (MonoClass *klass, const char *name, int arguments) { assert (klass); return mono_class_get_method_from_name (klass, name, arguments); } EMSCRIPTEN_KEEPALIVE MonoMethod* mono_wasm_get_delegate_invoke (MonoObject *delegate) { return mono_get_delegate_invoke(mono_object_get_class (delegate)); } EMSCRIPTEN_KEEPALIVE MonoObject* mono_wasm_box_primitive (MonoClass *klass, void *value, int value_size) { assert (klass); MonoType *type = mono_class_get_type (klass); int alignment; if (mono_type_size (type, &alignment) > value_size) return NULL; // TODO: use mono_value_box_checked and propagate error out return mono_value_box (root_domain, klass, value); } EMSCRIPTEN_KEEPALIVE MonoObject* mono_wasm_invoke_method (MonoMethod *method, MonoObject *this_arg, void *params[], MonoObject **out_exc) { MonoObject *exc = NULL; MonoObject *res; if (out_exc) *out_exc = NULL; res = mono_runtime_invoke (method, this_arg, params, &exc); if (exc) { if (out_exc) *out_exc = exc; MonoObject *exc2 = NULL; res = (MonoObject*)mono_object_to_string (exc, &exc2); if (exc2) res = (MonoObject*) mono_string_new (root_domain, "Exception Double Fault"); return res; } MonoMethodSignature *sig = mono_method_signature (method); MonoType *type = mono_signature_get_return_type (sig); // If the method return type is void return null // This gets around a memory access crash when the result return a value when // a void method is invoked. if (mono_type_get_type (type) == MONO_TYPE_VOID) return NULL; return res; } EMSCRIPTEN_KEEPALIVE MonoMethod* mono_wasm_assembly_get_entry_point (MonoAssembly *assembly) { MonoImage *image; MonoMethod *method; image = mono_assembly_get_image (assembly); uint32_t entry = mono_image_get_entry_point (image); if (!entry) return NULL; mono_domain_ensure_entry_assembly (root_domain, assembly); method = mono_get_method (image, entry, NULL); /* * If the entry point looks like a compiler generated wrapper around * an async method in the form "<Name>" then try to look up the async methods * "<Name>$" and "Name" it could be wrapping. We do this because the generated * sync wrapper will call task.GetAwaiter().GetResult() when we actually want * to yield to the host runtime. */ if (mono_method_get_flags (method, NULL) & 0x0800 /* METHOD_ATTRIBUTE_SPECIAL_NAME */) { const char *name = mono_method_get_name (method); int name_length = strlen (name); if ((*name != '<') || (name [name_length - 1] != '>')) return method; MonoClass *klass = mono_method_get_class (method); assert(klass); char *async_name = malloc (name_length + 2); snprintf (async_name, name_length + 2, "%s$", name); // look for "<Name>$" MonoMethodSignature *sig = mono_method_get_signature (method, image, mono_method_get_token (method)); MonoMethod *async_method = mono_class_get_method_from_name (klass, async_name, mono_signature_get_param_count (sig)); if (async_method != NULL) { free (async_name); return async_method; } // look for "Name" by trimming the first and last character of "<Name>" async_name [name_length - 1] = '\0'; async_method = mono_class_get_method_from_name (klass, async_name + 1, mono_signature_get_param_count (sig)); free (async_name); if (async_method != NULL) return async_method; } return method; } EMSCRIPTEN_KEEPALIVE char * mono_wasm_string_get_utf8 (MonoString *str) { return mono_string_to_utf8 (str); //XXX JS is responsible for freeing this } EMSCRIPTEN_KEEPALIVE MonoString * mono_wasm_string_from_js (const char *str) { if (str) return mono_string_new (root_domain, str); else return NULL; } EMSCRIPTEN_KEEPALIVE MonoString * mono_wasm_string_from_utf16 (const mono_unichar2 * chars, int length) { assert (length >= 0); if (chars) return mono_string_new_utf16 (root_domain, chars, length); else return NULL; } static int class_is_task (MonoClass *klass) { if (!klass) return 0; if (!task_class && !resolved_task_class) { task_class = mono_class_from_name (mono_get_corlib(), "System.Threading.Tasks", "Task"); resolved_task_class = 1; } if (task_class && (klass == task_class || mono_class_is_subclass_of(klass, task_class, 0))) return 1; return 0; } MonoClass* mono_get_uri_class(MonoException** exc) { MonoAssembly* assembly = mono_wasm_assembly_load ("System"); if (!assembly) return NULL; MonoClass* klass = mono_wasm_assembly_find_class(assembly, "System", "Uri"); return klass; } void mono_wasm_ensure_classes_resolved () { if (!datetime_class && !resolved_datetime_class) { datetime_class = mono_class_from_name (mono_get_corlib(), "System", "DateTime"); resolved_datetime_class = 1; } if (!datetimeoffset_class && !resolved_datetimeoffset_class) { datetimeoffset_class = mono_class_from_name (mono_get_corlib(), "System", "DateTimeOffset"); resolved_datetimeoffset_class = 1; } if (!uri_class && !resolved_uri_class) { MonoException** exc = NULL; uri_class = mono_get_uri_class(exc); resolved_uri_class = 1; } if (!safehandle_class && !resolved_safehandle_class) { safehandle_class = mono_class_from_name (mono_get_corlib(), "System.Runtime.InteropServices", "SafeHandle"); resolved_safehandle_class = 1; } if (!voidtaskresult_class && !resolved_voidtaskresult_class) { voidtaskresult_class = mono_class_from_name (mono_get_corlib(), "System.Threading.Tasks", "VoidTaskResult"); resolved_voidtaskresult_class = 1; } } int mono_wasm_marshal_type_from_mono_type (int mono_type, MonoClass *klass, MonoType *type) { switch (mono_type) { // case MONO_TYPE_CHAR: prob should be done not as a number? case MONO_TYPE_VOID: return MARSHAL_TYPE_VOID; case MONO_TYPE_BOOLEAN: return MARSHAL_TYPE_BOOL; case MONO_TYPE_I: // IntPtr case MONO_TYPE_U: // UIntPtr case MONO_TYPE_PTR: return MARSHAL_TYPE_POINTER; case MONO_TYPE_I1: case MONO_TYPE_U1: case MONO_TYPE_I2: case MONO_TYPE_U2: case MONO_TYPE_I4: return MARSHAL_TYPE_INT; case MONO_TYPE_CHAR: return MARSHAL_TYPE_CHAR; case MONO_TYPE_U4: // The distinction between this and signed int is // important due to how numbers work in JavaScript return MARSHAL_TYPE_UINT32; case MONO_TYPE_I8: return MARSHAL_TYPE_INT64; case MONO_TYPE_U8: return MARSHAL_TYPE_UINT64; case MONO_TYPE_R4: return MARSHAL_TYPE_FP32; case MONO_TYPE_R8: return MARSHAL_TYPE_FP64; case MONO_TYPE_STRING: return MARSHAL_TYPE_STRING; case MONO_TYPE_SZARRAY: { // simple zero based one-dim-array if (klass) { MonoClass *eklass = mono_class_get_element_class (klass); MonoType *etype = mono_class_get_type (eklass); switch (mono_type_get_type (etype)) { case MONO_TYPE_U1: return MARSHAL_ARRAY_UBYTE; case MONO_TYPE_I1: return MARSHAL_ARRAY_BYTE; case MONO_TYPE_U2: return MARSHAL_ARRAY_USHORT; case MONO_TYPE_I2: return MARSHAL_ARRAY_SHORT; case MONO_TYPE_U4: return MARSHAL_ARRAY_UINT; case MONO_TYPE_I4: return MARSHAL_ARRAY_INT; case MONO_TYPE_R4: return MARSHAL_ARRAY_FLOAT; case MONO_TYPE_R8: return MARSHAL_ARRAY_DOUBLE; default: return MARSHAL_TYPE_OBJECT; } } else { return MARSHAL_TYPE_OBJECT; } } default: mono_wasm_ensure_classes_resolved (); if (klass) { if (klass == datetime_class) return MARSHAL_TYPE_DATE; if (klass == datetimeoffset_class) return MARSHAL_TYPE_DATEOFFSET; if (uri_class && mono_class_is_assignable_from(uri_class, klass)) return MARSHAL_TYPE_URI; if (klass == voidtaskresult_class) return MARSHAL_TYPE_VOID; if (mono_class_is_enum (klass)) return MARSHAL_TYPE_ENUM; if (type && !mono_type_is_reference (type)) //vt return MARSHAL_TYPE_VT; if (mono_class_is_delegate (klass)) return MARSHAL_TYPE_DELEGATE; if (class_is_task(klass)) return MARSHAL_TYPE_TASK; if (safehandle_class && (klass == safehandle_class || mono_class_is_subclass_of(klass, safehandle_class, 0))) return MARSHAL_TYPE_SAFEHANDLE; } return MARSHAL_TYPE_OBJECT; } } EMSCRIPTEN_KEEPALIVE MonoClass * mono_wasm_get_obj_class (MonoObject *obj) { if (!obj) return NULL; return mono_object_get_class (obj); } EMSCRIPTEN_KEEPALIVE int mono_wasm_get_obj_type (MonoObject *obj) { if (!obj) return 0; /* Process obj before calling into the runtime, class_from_name () can invoke managed code */ MonoClass *klass = mono_object_get_class (obj); if (!klass) return MARSHAL_ERROR_NULL_CLASS_POINTER; if ((klass == mono_get_string_class ()) && mono_string_instance_is_interned ((MonoString *)obj)) return MARSHAL_TYPE_STRING_INTERNED; MonoType *type = mono_class_get_type (klass); if (!type) return MARSHAL_ERROR_NULL_TYPE_POINTER; obj = NULL; int mono_type = mono_type_get_type (type); return mono_wasm_marshal_type_from_mono_type (mono_type, klass, type); } EMSCRIPTEN_KEEPALIVE int mono_wasm_try_unbox_primitive_and_get_type (MonoObject *obj, void *result, int result_capacity) { void **resultP = result; int *resultI = result; int64_t *resultL = result; float *resultF = result; double *resultD = result; if (result_capacity >= sizeof (int64_t)) *resultL = 0; else if (result_capacity >= sizeof (int)) *resultI = 0; if (!result) return MARSHAL_ERROR_BUFFER_TOO_SMALL; if (result_capacity < 16) return MARSHAL_ERROR_BUFFER_TOO_SMALL; if (!obj) return MARSHAL_TYPE_NULL; /* Process obj before calling into the runtime, class_from_name () can invoke managed code */ MonoClass *klass = mono_object_get_class (obj); if (!klass) return MARSHAL_ERROR_NULL_CLASS_POINTER; MonoType *type = mono_class_get_type (klass), *original_type = type; if (!type) return MARSHAL_ERROR_NULL_TYPE_POINTER; if ((klass == mono_get_string_class ()) && mono_string_instance_is_interned ((MonoString *)obj)) { *resultL = 0; *resultP = type; return MARSHAL_TYPE_STRING_INTERNED; } if (mono_class_is_enum (klass)) type = mono_type_get_underlying_type (type); if (!type) return MARSHAL_ERROR_NULL_TYPE_POINTER; int mono_type = mono_type_get_type (type); if (mono_type == MONO_TYPE_GENERICINST) { // HACK: While the 'any other type' fallback is valid for classes, it will do the // wrong thing for structs, so we need to make sure the valuetype handler is used if (mono_type_generic_inst_is_valuetype (type)) mono_type = MONO_TYPE_VALUETYPE; } // FIXME: We would prefer to unbox once here but it will fail if the value isn't unboxable switch (mono_type) { case MONO_TYPE_I1: case MONO_TYPE_BOOLEAN: *resultI = *(signed char*)mono_object_unbox (obj); break; case MONO_TYPE_U1: *resultI = *(unsigned char*)mono_object_unbox (obj); break; case MONO_TYPE_I2: case MONO_TYPE_CHAR: *resultI = *(short*)mono_object_unbox (obj); break; case MONO_TYPE_U2: *resultI = *(unsigned short*)mono_object_unbox (obj); break; case MONO_TYPE_I4: case MONO_TYPE_I: *resultI = *(int*)mono_object_unbox (obj); break; case MONO_TYPE_U4: // FIXME: Will this behave the way we want for large unsigned values? *resultI = *(int*)mono_object_unbox (obj); break; case MONO_TYPE_R4: *resultF = *(float*)mono_object_unbox (obj); break; case MONO_TYPE_R8: *resultD = *(double*)mono_object_unbox (obj); break; case MONO_TYPE_PTR: *resultL = (int64_t)(*(void**)mono_object_unbox (obj)); break; case MONO_TYPE_I8: case MONO_TYPE_U8: // FIXME: At present the javascript side of things can't handle this, // but there's no reason not to future-proof this API *resultL = *(int64_t*)mono_object_unbox (obj); break; case MONO_TYPE_VALUETYPE: { int obj_size = mono_object_get_size (obj), required_size = (sizeof (int)) + (sizeof (MonoType *)) + obj_size; // Check whether this struct has special-case marshaling // FIXME: Do we need to null out obj before this? int marshal_type = mono_wasm_marshal_type_from_mono_type (mono_type, klass, original_type); if (marshal_type != MARSHAL_TYPE_VT) return marshal_type; // Check whether the result buffer is big enough for the struct and padding if (result_capacity < required_size) return MARSHAL_ERROR_BUFFER_TOO_SMALL; // Store a header before the struct data with the size of the data and its MonoType *resultP = type; int * resultSize = (int *)(resultP + 1); *resultSize = obj_size; void * resultVoid = (resultP + 2); void * unboxed = mono_object_unbox (obj); memcpy (resultVoid, unboxed, obj_size); return MARSHAL_TYPE_VT; } break; default: // If we failed to do a fast unboxing, return the original type information so // that the caller can do a proper, slow unboxing later // HACK: Store the class pointer into the result buffer so our caller doesn't // have to call back into the native runtime later to get it *resultP = type; obj = NULL; int fallbackResultType = mono_wasm_marshal_type_from_mono_type (mono_type, klass, original_type); assert (fallbackResultType != MARSHAL_TYPE_VT); return fallbackResultType; } // We successfully performed a fast unboxing here so use the type information // matching what we unboxed (i.e. an enum's underlying type instead of its type) obj = NULL; int resultType = mono_wasm_marshal_type_from_mono_type (mono_type, klass, type); assert (resultType != MARSHAL_TYPE_VT); return resultType; } EMSCRIPTEN_KEEPALIVE int mono_wasm_array_length (MonoArray *array) { return mono_array_length (array); } EMSCRIPTEN_KEEPALIVE MonoObject* mono_wasm_array_get (MonoArray *array, int idx) { return mono_array_get (array, MonoObject*, idx); } EMSCRIPTEN_KEEPALIVE MonoArray* mono_wasm_obj_array_new (int size) { return mono_array_new (root_domain, mono_get_object_class (), size); } EMSCRIPTEN_KEEPALIVE void mono_wasm_obj_array_set (MonoArray *array, int idx, MonoObject *obj) { mono_array_setref (array, idx, obj); } EMSCRIPTEN_KEEPALIVE MonoArray* mono_wasm_string_array_new (int size) { return mono_array_new (root_domain, mono_get_string_class (), size); } EMSCRIPTEN_KEEPALIVE int mono_wasm_exec_regression (int verbose_level, char *image) { return mono_regression_test_step (verbose_level, image, NULL) ? 0 : 1; } EMSCRIPTEN_KEEPALIVE int mono_wasm_exit (int exit_code) { exit (exit_code); } EMSCRIPTEN_KEEPALIVE void mono_wasm_set_main_args (int argc, char* argv[]) { mono_runtime_set_main_args (argc, argv); } EMSCRIPTEN_KEEPALIVE int mono_wasm_strdup (const char *s) { return (int)strdup (s); } EMSCRIPTEN_KEEPALIVE void mono_wasm_parse_runtime_options (int argc, char* argv[]) { mono_jit_parse_options (argc, argv); } EMSCRIPTEN_KEEPALIVE void mono_wasm_enable_on_demand_gc (int enable) { mono_wasm_enable_gc = enable ? 1 : 0; } EMSCRIPTEN_KEEPALIVE MonoString * mono_wasm_intern_string (MonoString *string) { return mono_string_intern (string); } EMSCRIPTEN_KEEPALIVE void mono_wasm_string_get_data ( MonoString *string, mono_unichar2 **outChars, int *outLengthBytes, int *outIsInterned ) { if (!string) { if (outChars) *outChars = 0; if (outLengthBytes) *outLengthBytes = 0; if (outIsInterned) *outIsInterned = 1; return; } if (outChars) *outChars = mono_string_chars (string); if (outLengthBytes) *outLengthBytes = mono_string_length (string) * 2; if (outIsInterned) *outIsInterned = mono_string_instance_is_interned (string); return; } EMSCRIPTEN_KEEPALIVE MonoType * mono_wasm_class_get_type (MonoClass *klass) { if (!klass) return NULL; return mono_class_get_type (klass); } EMSCRIPTEN_KEEPALIVE MonoClass * mono_wasm_type_get_class (MonoType *type) { if (!type) return NULL; return mono_type_get_class (type); } EMSCRIPTEN_KEEPALIVE void * mono_wasm_unbox_rooted (MonoObject *obj) { if (!obj) return NULL; return mono_object_unbox (obj); } EMSCRIPTEN_KEEPALIVE char * mono_wasm_get_type_name (MonoType * typePtr) { return mono_type_get_name_full (typePtr, MONO_TYPE_NAME_FORMAT_REFLECTION); } EMSCRIPTEN_KEEPALIVE char * mono_wasm_get_type_aqn (MonoType * typePtr) { return mono_type_get_name_full (typePtr, MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED); } #ifdef ENABLE_AOT_PROFILER void mono_profiler_init_aot (const char *desc); EMSCRIPTEN_KEEPALIVE void mono_wasm_load_profiler_aot (const char *desc) { mono_profiler_init_aot (desc); } #endif
-1
dotnet/runtime
66,462
Support using the system version of brotli
This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
omajid
2022-03-10T17:19:11Z
2022-03-23T03:49:50Z
c3e1d21c2fb30436ae24ef7ef4f458e3270bb7e3
5ca9223639700750ff12bb1fed9fa6e397062b78
Support using the system version of brotli . This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
./src/tests/Interop/UnmanagedCallersOnly/CMakeLists.txt
project (UnmanagedCallersOnlyDll) include ("${CLR_INTEROP_TEST_ROOT}/Interop.cmake") set(SOURCES UnmanagedCallersOnlyDll.cpp ) # add the executable add_library (UnmanagedCallersOnlyDll SHARED ${SOURCES}) target_link_libraries(UnmanagedCallersOnlyDll ${LINK_LIBRARIES_ADDITIONAL}) # add the install targets install (TARGETS UnmanagedCallersOnlyDll DESTINATION bin)
project (UnmanagedCallersOnlyDll) include ("${CLR_INTEROP_TEST_ROOT}/Interop.cmake") set(SOURCES UnmanagedCallersOnlyDll.cpp ) # add the executable add_library (UnmanagedCallersOnlyDll SHARED ${SOURCES}) target_link_libraries(UnmanagedCallersOnlyDll ${LINK_LIBRARIES_ADDITIONAL}) # add the install targets install (TARGETS UnmanagedCallersOnlyDll DESTINATION bin)
-1
dotnet/runtime
66,462
Support using the system version of brotli
This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
omajid
2022-03-10T17:19:11Z
2022-03-23T03:49:50Z
c3e1d21c2fb30436ae24ef7ef4f458e3270bb7e3
5ca9223639700750ff12bb1fed9fa6e397062b78
Support using the system version of brotli . This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
./src/native/external/libunwind/src/mi/backtrace.c
/* libunwind - a platform-independent unwind library Copyright (C) 2001-2002 Hewlett-Packard Co Contributed by David Mosberger-Tang <[email protected]> This file is part of libunwind. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #if !defined(UNW_REMOTE_ONLY) && !defined(UNW_LOCAL_ONLY) #define UNW_LOCAL_ONLY #include <libunwind.h> #include <libunwind_i.h> #include <string.h> /* See glibc manual for a description of this function. */ static ALWAYS_INLINE int slow_backtrace (void **buffer, int size, unw_context_t *uc) { unw_cursor_t cursor; unw_word_t ip; int n = 0; if (unlikely (unw_init_local (&cursor, uc) < 0)) return 0; while (unw_step (&cursor) > 0) { if (n >= size) return n; if (unw_get_reg (&cursor, UNW_REG_IP, &ip) < 0) return n; buffer[n++] = (void *) (uintptr_t) ip; } return n; } int unw_backtrace (void **buffer, int size) { unw_cursor_t cursor; unw_context_t uc; int n = size; tdep_getcontext_trace (&uc); if (unlikely (unw_init_local (&cursor, &uc) < 0)) return 0; if (unlikely (tdep_trace (&cursor, buffer, &n) < 0)) { unw_getcontext (&uc); return slow_backtrace (buffer, size, &uc); } return n; } #ifdef CONFIG_WEAK_BACKTRACE extern int backtrace (void **buffer, int size) WEAK ALIAS(unw_backtrace); #endif #endif /* !UNW_REMOTE_ONLY */
/* libunwind - a platform-independent unwind library Copyright (C) 2001-2002 Hewlett-Packard Co Contributed by David Mosberger-Tang <[email protected]> This file is part of libunwind. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #if !defined(UNW_REMOTE_ONLY) && !defined(UNW_LOCAL_ONLY) #define UNW_LOCAL_ONLY #include <libunwind.h> #include <libunwind_i.h> #include <string.h> /* See glibc manual for a description of this function. */ static ALWAYS_INLINE int slow_backtrace (void **buffer, int size, unw_context_t *uc) { unw_cursor_t cursor; unw_word_t ip; int n = 0; if (unlikely (unw_init_local (&cursor, uc) < 0)) return 0; while (unw_step (&cursor) > 0) { if (n >= size) return n; if (unw_get_reg (&cursor, UNW_REG_IP, &ip) < 0) return n; buffer[n++] = (void *) (uintptr_t) ip; } return n; } int unw_backtrace (void **buffer, int size) { unw_cursor_t cursor; unw_context_t uc; int n = size; tdep_getcontext_trace (&uc); if (unlikely (unw_init_local (&cursor, &uc) < 0)) return 0; if (unlikely (tdep_trace (&cursor, buffer, &n) < 0)) { unw_getcontext (&uc); return slow_backtrace (buffer, size, &uc); } return n; } #ifdef CONFIG_WEAK_BACKTRACE extern int backtrace (void **buffer, int size) WEAK ALIAS(unw_backtrace); #endif #endif /* !UNW_REMOTE_ONLY */
-1
dotnet/runtime
66,462
Support using the system version of brotli
This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
omajid
2022-03-10T17:19:11Z
2022-03-23T03:49:50Z
c3e1d21c2fb30436ae24ef7ef4f458e3270bb7e3
5ca9223639700750ff12bb1fed9fa6e397062b78
Support using the system version of brotli . This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
./src/mono/mono/mini/helpers.c
/** * \file * Assorted routines * * (C) 2003 Ximian, Inc. */ #include <config.h> #include "mini.h" #include <ctype.h> #include <mono/metadata/opcodes.h> #ifndef HOST_WIN32 #include <unistd.h> #endif #ifndef DISABLE_JIT #ifndef DISABLE_LOGGING #ifdef MINI_OP #undef MINI_OP #endif #ifdef MINI_OP3 #undef MINI_OP3 #endif // This, instead of an array of pointers, to optimize away a pointer and a relocation per string. #define MSGSTRFIELD(line) MSGSTRFIELD1(line) #define MSGSTRFIELD1(line) str##line static const struct msgstr_t { #define MINI_OP(a,b,dest,src1,src2) char MSGSTRFIELD(__LINE__) [sizeof (b)]; #define MINI_OP3(a,b,dest,src1,src2,src3) char MSGSTRFIELD(__LINE__) [sizeof (b)]; #include "mini-ops.h" #undef MINI_OP #undef MINI_OP3 } opstr = { #define MINI_OP(a,b,dest,src1,src2) b, #define MINI_OP3(a,b,dest,src1,src2,src3) b, #include "mini-ops.h" #undef MINI_OP #undef MINI_OP3 }; static const gint16 opidx [] = { #define MINI_OP(a,b,dest,src1,src2) offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)), #define MINI_OP3(a,b,dest,src1,src2,src3) offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)), #include "mini-ops.h" #undef MINI_OP #undef MINI_OP3 }; #endif /* DISABLE_LOGGING */ #if defined(__i386__) || defined(_M_IX86) || defined(__x86_64__) || defined(_M_X64) #if !defined(TARGET_ARM64) && !defined(__APPLE__) #define emit_debug_info TRUE #else #define emit_debug_info FALSE #endif #else #define emit_debug_info FALSE #endif /*This enables us to use the right tooling when building the cross compiler for iOS.*/ #if defined (__APPLE__) && defined (TARGET_ARM) && (defined(__i386__) || defined(__x86_64__)) //#define ARCH_PREFIX "/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/" #endif #define ARCH_PREFIX "" //#define ARCH_PREFIX "powerpc64-linux-gnu-" const char* mono_inst_name (int op) { #ifndef DISABLE_LOGGING if (op >= OP_LOAD && op <= OP_LAST) return (const char*)&opstr + opidx [op - OP_LOAD]; if (op < OP_LOAD) return mono_opcode_name (op); g_error ("unknown opcode name for %d", op); return NULL; #else g_error ("unknown opcode name for %d", op); g_assert_not_reached (); #endif } void mono_blockset_print (MonoCompile *cfg, MonoBitSet *set, const char *name, guint idom) { #ifndef DISABLE_LOGGING int i; if (name) g_print ("%s:", name); mono_bitset_foreach_bit (set, i, cfg->num_bblocks) { if (idom == i) g_print (" [BB%d]", cfg->bblocks [i]->block_num); else g_print (" BB%d", cfg->bblocks [i]->block_num); } g_print ("\n"); #endif } /** * \param cfg compilation context * \param code a pointer to the code * \param size the code size in bytes * * Disassemble to code to stdout. */ void mono_disassemble_code (MonoCompile *cfg, guint8 *code, int size, char *id) { #ifndef DISABLE_LOGGING GHashTable *offset_to_bb_hash = NULL; int i, cindex, bb_num; FILE *ofd; #ifdef HOST_WIN32 const char *tmp = g_get_tmp_dir (); #endif char *as_file; char *o_file; int unused G_GNUC_UNUSED; #ifdef HOST_WIN32 as_file = g_strdup_printf ("%s/test.s", tmp); if (!(ofd = fopen (as_file, "w"))) g_assert_not_reached (); #else i = g_file_open_tmp (NULL, &as_file, NULL); ofd = fdopen (i, "w"); g_assert (ofd); #endif for (i = 0; id [i]; ++i) { if (i == 0 && isdigit (id [i])) fprintf (ofd, "_"); else if (!isalnum (id [i])) fprintf (ofd, "_"); else fprintf (ofd, "%c", id [i]); } fprintf (ofd, ":\n"); if (emit_debug_info && cfg != NULL) { MonoBasicBlock *bb; fprintf (ofd, ".stabs \"\",100,0,0,.Ltext0\n"); fprintf (ofd, ".stabs \"<BB>\",100,0,0,.Ltext0\n"); fprintf (ofd, ".Ltext0:\n"); offset_to_bb_hash = g_hash_table_new (NULL, NULL); for (bb = cfg->bb_entry; bb; bb = bb->next_bb) { g_hash_table_insert (offset_to_bb_hash, GINT_TO_POINTER (bb->native_offset), GINT_TO_POINTER (bb->block_num + 1)); } } cindex = 0; for (i = 0; i < size; ++i) { if (emit_debug_info && cfg != NULL) { bb_num = GPOINTER_TO_INT (g_hash_table_lookup (offset_to_bb_hash, GINT_TO_POINTER (i))); if (bb_num) { fprintf (ofd, "\n.stabd 68,0,%d\n", bb_num - 1); cindex = 0; } } if (cindex == 0) { fprintf (ofd, "\n.byte %u", (unsigned int) code [i]); } else { fprintf (ofd, ",%u", (unsigned int) code [i]); } cindex++; if (cindex == 64) cindex = 0; } fprintf (ofd, "\n"); fclose (ofd); #ifdef __APPLE__ #ifdef __ppc64__ #define DIS_CMD "otool64 -v -t" #else #define DIS_CMD "otool -v -t" #endif #else #if defined(sparc) && !defined(__GNUC__) #define DIS_CMD "dis" #elif defined(TARGET_X86) #define DIS_CMD "objdump -l -d" #elif defined(TARGET_AMD64) #if defined(HOST_WIN32) #define DIS_CMD "x86_64-w64-mingw32-objdump.exe -M x86-64 -d" #else #define DIS_CMD "objdump -l -d" #endif #else #define DIS_CMD "objdump -d" #endif #endif #if defined(sparc) #define AS_CMD "as -xarch=v9" #elif defined (TARGET_X86) # if defined(__APPLE__) # define AS_CMD "as -arch i386" # else # define AS_CMD "as -gstabs" # endif #elif defined (TARGET_AMD64) # if defined (__APPLE__) # define AS_CMD "as -arch x86_64" # else # define AS_CMD "as -gstabs" # endif #elif defined (TARGET_ARM) # if defined (__APPLE__) # define AS_CMD "as -arch arm" # else # define AS_CMD "as -gstabs" # endif #elif defined (TARGET_ARM64) # if defined (__APPLE__) # define AS_CMD "clang -c -arch arm64 -g -x assembler" # else # define AS_CMD "as -gstabs" # endif #elif defined(__mips__) && (_MIPS_SIM == _ABIO32) #define AS_CMD "as -mips32" #elif defined(__ppc64__) #define AS_CMD "as -arch ppc64" #elif defined(__powerpc64__) #define AS_CMD "as -mppc64" #elif defined (TARGET_RISCV64) #define AS_CMD "as -march=rv64ima" #elif defined (TARGET_RISCV32) #define AS_CMD "as -march=rv32ima" #else #define AS_CMD "as" #endif #ifdef HOST_WIN32 o_file = g_strdup_printf ("%s/test.o", tmp); #else i = g_file_open_tmp (NULL, &o_file, NULL); close (i); #endif #ifdef HAVE_SYSTEM char *cmd = g_strdup_printf (ARCH_PREFIX AS_CMD " %s -o %s", as_file, o_file); unused = system (cmd); g_free (cmd); char *objdump_args = g_getenv ("MONO_OBJDUMP_ARGS"); if (!objdump_args) objdump_args = g_strdup (""); fflush (stdout); #if (defined(__arm__) || defined(__aarch64__)) && !defined(TARGET_OSX) /* * The arm assembler inserts ELF directives instructing objdump to display * everything as data. */ cmd = g_strdup_printf (ARCH_PREFIX "strip -s %s", o_file); unused = system (cmd); g_free (cmd); #endif cmd = g_strdup_printf (ARCH_PREFIX DIS_CMD " %s %s", objdump_args, o_file); unused = system (cmd); g_free (cmd); g_free (objdump_args); #else g_assert_not_reached (); #endif /* HAVE_SYSTEM */ #ifndef HOST_WIN32 unlink (o_file); unlink (as_file); #endif g_free (o_file); g_free (as_file); #endif } #else /* DISABLE_JIT */ void mono_blockset_print (MonoCompile *cfg, MonoBitSet *set, const char *name, guint idom) { } #endif /* DISABLE_JIT */
/** * \file * Assorted routines * * (C) 2003 Ximian, Inc. */ #include <config.h> #include "mini.h" #include <ctype.h> #include <mono/metadata/opcodes.h> #ifndef HOST_WIN32 #include <unistd.h> #endif #ifndef DISABLE_JIT #ifndef DISABLE_LOGGING #ifdef MINI_OP #undef MINI_OP #endif #ifdef MINI_OP3 #undef MINI_OP3 #endif // This, instead of an array of pointers, to optimize away a pointer and a relocation per string. #define MSGSTRFIELD(line) MSGSTRFIELD1(line) #define MSGSTRFIELD1(line) str##line static const struct msgstr_t { #define MINI_OP(a,b,dest,src1,src2) char MSGSTRFIELD(__LINE__) [sizeof (b)]; #define MINI_OP3(a,b,dest,src1,src2,src3) char MSGSTRFIELD(__LINE__) [sizeof (b)]; #include "mini-ops.h" #undef MINI_OP #undef MINI_OP3 } opstr = { #define MINI_OP(a,b,dest,src1,src2) b, #define MINI_OP3(a,b,dest,src1,src2,src3) b, #include "mini-ops.h" #undef MINI_OP #undef MINI_OP3 }; static const gint16 opidx [] = { #define MINI_OP(a,b,dest,src1,src2) offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)), #define MINI_OP3(a,b,dest,src1,src2,src3) offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)), #include "mini-ops.h" #undef MINI_OP #undef MINI_OP3 }; #endif /* DISABLE_LOGGING */ #if defined(__i386__) || defined(_M_IX86) || defined(__x86_64__) || defined(_M_X64) #if !defined(TARGET_ARM64) && !defined(__APPLE__) #define emit_debug_info TRUE #else #define emit_debug_info FALSE #endif #else #define emit_debug_info FALSE #endif /*This enables us to use the right tooling when building the cross compiler for iOS.*/ #if defined (__APPLE__) && defined (TARGET_ARM) && (defined(__i386__) || defined(__x86_64__)) //#define ARCH_PREFIX "/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/" #endif #define ARCH_PREFIX "" //#define ARCH_PREFIX "powerpc64-linux-gnu-" const char* mono_inst_name (int op) { #ifndef DISABLE_LOGGING if (op >= OP_LOAD && op <= OP_LAST) return (const char*)&opstr + opidx [op - OP_LOAD]; if (op < OP_LOAD) return mono_opcode_name (op); g_error ("unknown opcode name for %d", op); return NULL; #else g_error ("unknown opcode name for %d", op); g_assert_not_reached (); #endif } void mono_blockset_print (MonoCompile *cfg, MonoBitSet *set, const char *name, guint idom) { #ifndef DISABLE_LOGGING int i; if (name) g_print ("%s:", name); mono_bitset_foreach_bit (set, i, cfg->num_bblocks) { if (idom == i) g_print (" [BB%d]", cfg->bblocks [i]->block_num); else g_print (" BB%d", cfg->bblocks [i]->block_num); } g_print ("\n"); #endif } /** * \param cfg compilation context * \param code a pointer to the code * \param size the code size in bytes * * Disassemble to code to stdout. */ void mono_disassemble_code (MonoCompile *cfg, guint8 *code, int size, char *id) { #ifndef DISABLE_LOGGING GHashTable *offset_to_bb_hash = NULL; int i, cindex, bb_num; FILE *ofd; #ifdef HOST_WIN32 const char *tmp = g_get_tmp_dir (); #endif char *as_file; char *o_file; int unused G_GNUC_UNUSED; #ifdef HOST_WIN32 as_file = g_strdup_printf ("%s/test.s", tmp); if (!(ofd = fopen (as_file, "w"))) g_assert_not_reached (); #else i = g_file_open_tmp (NULL, &as_file, NULL); ofd = fdopen (i, "w"); g_assert (ofd); #endif for (i = 0; id [i]; ++i) { if (i == 0 && isdigit (id [i])) fprintf (ofd, "_"); else if (!isalnum (id [i])) fprintf (ofd, "_"); else fprintf (ofd, "%c", id [i]); } fprintf (ofd, ":\n"); if (emit_debug_info && cfg != NULL) { MonoBasicBlock *bb; fprintf (ofd, ".stabs \"\",100,0,0,.Ltext0\n"); fprintf (ofd, ".stabs \"<BB>\",100,0,0,.Ltext0\n"); fprintf (ofd, ".Ltext0:\n"); offset_to_bb_hash = g_hash_table_new (NULL, NULL); for (bb = cfg->bb_entry; bb; bb = bb->next_bb) { g_hash_table_insert (offset_to_bb_hash, GINT_TO_POINTER (bb->native_offset), GINT_TO_POINTER (bb->block_num + 1)); } } cindex = 0; for (i = 0; i < size; ++i) { if (emit_debug_info && cfg != NULL) { bb_num = GPOINTER_TO_INT (g_hash_table_lookup (offset_to_bb_hash, GINT_TO_POINTER (i))); if (bb_num) { fprintf (ofd, "\n.stabd 68,0,%d\n", bb_num - 1); cindex = 0; } } if (cindex == 0) { fprintf (ofd, "\n.byte %u", (unsigned int) code [i]); } else { fprintf (ofd, ",%u", (unsigned int) code [i]); } cindex++; if (cindex == 64) cindex = 0; } fprintf (ofd, "\n"); fclose (ofd); #ifdef __APPLE__ #ifdef __ppc64__ #define DIS_CMD "otool64 -v -t" #else #define DIS_CMD "otool -v -t" #endif #else #if defined(sparc) && !defined(__GNUC__) #define DIS_CMD "dis" #elif defined(TARGET_X86) #define DIS_CMD "objdump -l -d" #elif defined(TARGET_AMD64) #if defined(HOST_WIN32) #define DIS_CMD "x86_64-w64-mingw32-objdump.exe -M x86-64 -d" #else #define DIS_CMD "objdump -l -d" #endif #else #define DIS_CMD "objdump -d" #endif #endif #if defined(sparc) #define AS_CMD "as -xarch=v9" #elif defined (TARGET_X86) # if defined(__APPLE__) # define AS_CMD "as -arch i386" # else # define AS_CMD "as -gstabs" # endif #elif defined (TARGET_AMD64) # if defined (__APPLE__) # define AS_CMD "as -arch x86_64" # else # define AS_CMD "as -gstabs" # endif #elif defined (TARGET_ARM) # if defined (__APPLE__) # define AS_CMD "as -arch arm" # else # define AS_CMD "as -gstabs" # endif #elif defined (TARGET_ARM64) # if defined (__APPLE__) # define AS_CMD "clang -c -arch arm64 -g -x assembler" # else # define AS_CMD "as -gstabs" # endif #elif defined(__mips__) && (_MIPS_SIM == _ABIO32) #define AS_CMD "as -mips32" #elif defined(__ppc64__) #define AS_CMD "as -arch ppc64" #elif defined(__powerpc64__) #define AS_CMD "as -mppc64" #elif defined (TARGET_RISCV64) #define AS_CMD "as -march=rv64ima" #elif defined (TARGET_RISCV32) #define AS_CMD "as -march=rv32ima" #else #define AS_CMD "as" #endif #ifdef HOST_WIN32 o_file = g_strdup_printf ("%s/test.o", tmp); #else i = g_file_open_tmp (NULL, &o_file, NULL); close (i); #endif #ifdef HAVE_SYSTEM char *cmd = g_strdup_printf (ARCH_PREFIX AS_CMD " %s -o %s", as_file, o_file); unused = system (cmd); g_free (cmd); char *objdump_args = g_getenv ("MONO_OBJDUMP_ARGS"); if (!objdump_args) objdump_args = g_strdup (""); fflush (stdout); #if (defined(__arm__) || defined(__aarch64__)) && !defined(TARGET_OSX) /* * The arm assembler inserts ELF directives instructing objdump to display * everything as data. */ cmd = g_strdup_printf (ARCH_PREFIX "strip -s %s", o_file); unused = system (cmd); g_free (cmd); #endif cmd = g_strdup_printf (ARCH_PREFIX DIS_CMD " %s %s", objdump_args, o_file); unused = system (cmd); g_free (cmd); g_free (objdump_args); #else g_assert_not_reached (); #endif /* HAVE_SYSTEM */ #ifndef HOST_WIN32 unlink (o_file); unlink (as_file); #endif g_free (o_file); g_free (as_file); #endif } #else /* DISABLE_JIT */ void mono_blockset_print (MonoCompile *cfg, MonoBitSet *set, const char *name, guint idom) { } #endif /* DISABLE_JIT */
-1
dotnet/runtime
66,462
Support using the system version of brotli
This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
omajid
2022-03-10T17:19:11Z
2022-03-23T03:49:50Z
c3e1d21c2fb30436ae24ef7ef4f458e3270bb7e3
5ca9223639700750ff12bb1fed9fa6e397062b78
Support using the system version of brotli . This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
./src/libraries/System.Private.Xml/tests/Xslt/TestFiles/TestData/xsltc/baseline/pft2.txt
Microsoft (R) XSLT Compiler version 2.0.61009 for Microsoft (R) Windows (R) 2005 Framework version 2.0.50727 Copyright (C) Microsoft Corporation 2007. All rights reserved. error : Invalid value '' for option /platform; must be x86, Itanium, x64, or anycpu.
Microsoft (R) XSLT Compiler version 2.0.61009 for Microsoft (R) Windows (R) 2005 Framework version 2.0.50727 Copyright (C) Microsoft Corporation 2007. All rights reserved. error : Invalid value '' for option /platform; must be x86, Itanium, x64, or anycpu.
-1
dotnet/runtime
66,462
Support using the system version of brotli
This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
omajid
2022-03-10T17:19:11Z
2022-03-23T03:49:50Z
c3e1d21c2fb30436ae24ef7ef4f458e3270bb7e3
5ca9223639700750ff12bb1fed9fa6e397062b78
Support using the system version of brotli . This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
./src/mono/mono/metadata/reflection.c
/** * \file * System.Type icalls and related reflection queries. * * Author: * Paolo Molaro ([email protected]) * * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com) * Copyright 2004-2009 Novell, Inc (http://www.novell.com) * Copyright 2011 Rodrigo Kumpera * Copyright 2016 Microsoft * * Licensed under the MIT license. See LICENSE file in the project root for full license information. */ #include <config.h> #include "mono/utils/mono-membar.h" #include "mono/metadata/assembly-internals.h" #include "mono/metadata/reflection-internals.h" #include "mono/metadata/tabledefs.h" #include "mono/metadata/metadata-internals.h" #include <mono/metadata/profiler-private.h> #include "mono/metadata/class-internals.h" #include "mono/metadata/class-init.h" #include "mono/metadata/gc-internals.h" #include "mono/metadata/domain-internals.h" #include "mono/metadata/opcodes.h" #include "mono/metadata/assembly.h" #include "mono/metadata/object-internals.h" #include <mono/metadata/exception.h> #include <mono/metadata/tokentype.h> #include <mono/metadata/marshal.h> #include <mono/metadata/reflection-cache.h> #include <mono/metadata/sre-internals.h> #include <stdio.h> #include <glib.h> #include <errno.h> #include <time.h> #include <string.h> #include <ctype.h> #include <mono/metadata/image.h> #include "cil-coff.h" #include "mono-endian.h" #include <mono/metadata/gc-internals.h> #include <mono/metadata/mempool-internals.h> #include <mono/metadata/debug-helpers.h> #include <mono/metadata/verify-internals.h> #include <mono/metadata/mono-ptr-array.h> #include <mono/metadata/mono-hash-internals.h> #include <mono/utils/mono-string.h> #include <mono/utils/mono-error-internals.h> #include <mono/utils/checked-build.h> #include <mono/utils/mono-counters.h> #include "icall-decl.h" static void get_default_param_value_blobs (MonoMethod *method, char **blobs, guint32 *types); static MonoType* mono_reflection_get_type_with_rootimage (MonoAssemblyLoadContext *alc, MonoImage *rootimage, MonoImage* image, MonoTypeNameParse *info, gboolean ignorecase, gboolean search_mscorlib, gboolean *type_resolve, MonoError *error); /* Class lazy loading functions */ static GENERATE_GET_CLASS_WITH_CACHE (mono_assembly, "System.Reflection", "RuntimeAssembly") static GENERATE_GET_CLASS_WITH_CACHE (mono_module, "System.Reflection", "RuntimeModule") static GENERATE_GET_CLASS_WITH_CACHE (mono_method, "System.Reflection", "RuntimeMethodInfo"); static GENERATE_GET_CLASS_WITH_CACHE (mono_cmethod, "System.Reflection", "RuntimeConstructorInfo"); static GENERATE_GET_CLASS_WITH_CACHE (mono_field, "System.Reflection", "RuntimeFieldInfo"); static GENERATE_GET_CLASS_WITH_CACHE (mono_event, "System.Reflection", "RuntimeEventInfo"); static GENERATE_GET_CLASS_WITH_CACHE (mono_property, "System.Reflection", "RuntimePropertyInfo"); static GENERATE_GET_CLASS_WITH_CACHE (mono_parameter_info, "System.Reflection", "RuntimeParameterInfo"); static GENERATE_GET_CLASS_WITH_CACHE (missing, "System.Reflection", "Missing"); static GENERATE_GET_CLASS_WITH_CACHE (method_body, "System.Reflection", "RuntimeMethodBody"); static GENERATE_GET_CLASS_WITH_CACHE (local_variable_info, "System.Reflection", "RuntimeLocalVariableInfo"); static GENERATE_GET_CLASS_WITH_CACHE (exception_handling_clause, "System.Reflection", "RuntimeExceptionHandlingClause"); static GENERATE_GET_CLASS_WITH_CACHE (type_builder, "System.Reflection.Emit", "TypeBuilder"); static GENERATE_GET_CLASS_WITH_CACHE (dbnull, "System", "DBNull"); static int class_ref_info_handle_count; void mono_reflection_init (void) { mono_reflection_emit_init (); mono_counters_register ("MonoClass::ref_info_handle count", MONO_COUNTER_METADATA | MONO_COUNTER_INT, &class_ref_info_handle_count); } /* * mono_class_get_ref_info: * * Return the type builder corresponding to KLASS, if it exists. */ MonoReflectionTypeBuilderHandle mono_class_get_ref_info (MonoClass *klass) { MONO_REQ_GC_UNSAFE_MODE; MonoGCHandle ref_info_handle = mono_class_get_ref_info_handle (klass); if (ref_info_handle == 0) return MONO_HANDLE_NEW (MonoReflectionTypeBuilder, NULL); return MONO_HANDLE_CAST (MonoReflectionTypeBuilder, mono_gchandle_get_target_handle (ref_info_handle)); } gboolean mono_class_has_ref_info (MonoClass *klass) { MONO_REQ_GC_UNSAFE_MODE; return 0 != mono_class_get_ref_info_handle (klass); } MonoReflectionTypeBuilder* mono_class_get_ref_info_raw (MonoClass *klass) { /* FIXME callers of mono_class_get_ref_info_raw should use handles */ MONO_REQ_GC_UNSAFE_MODE; MonoGCHandle ref_info_handle = mono_class_get_ref_info_handle (klass); if (ref_info_handle == 0) return NULL; return (MonoReflectionTypeBuilder*)mono_gchandle_get_target_internal (ref_info_handle); } void mono_class_set_ref_info (MonoClass *klass, MonoObjectHandle obj) { MONO_REQ_GC_UNSAFE_MODE; MonoGCHandle candidate = mono_gchandle_from_handle (obj, FALSE); MonoGCHandle handle = mono_class_set_ref_info_handle (klass, candidate); ++class_ref_info_handle_count; if (handle != candidate) mono_gchandle_free_internal (candidate); } void mono_class_free_ref_info (MonoClass *klass) { MONO_REQ_GC_NEUTRAL_MODE; MonoGCHandle handle = mono_class_get_ref_info_handle (klass); if (handle) { mono_gchandle_free_internal (handle); mono_class_set_ref_info_handle (klass, 0); } } /** * mono_custom_attrs_free: */ void mono_custom_attrs_free (MonoCustomAttrInfo *ainfo) { MONO_REQ_GC_NEUTRAL_MODE; if (ainfo && !ainfo->cached) g_free (ainfo); } gboolean mono_reflected_equal (gconstpointer a, gconstpointer b) { const ReflectedEntry *ea = (const ReflectedEntry *)a; const ReflectedEntry *eb = (const ReflectedEntry *)b; return (ea->item == eb->item) && (ea->refclass == eb->refclass); } guint mono_reflected_hash (gconstpointer a) { const ReflectedEntry *ea = (const ReflectedEntry *)a; /* Combine hashes for item and refclass. Identical to boost's hash_combine */ guint seed = mono_aligned_addr_hash (ea->item) + 0x9e3779b9; seed ^= mono_aligned_addr_hash (ea->refclass) + 0x9e3779b9 + (seed << 6) + (seed >> 2); return seed; } static void clear_cached_object (MonoMemoryManager *mem_manager, gpointer o, MonoClass *klass) { gpointer orig_pe, orig_value; ReflectedEntry pe; pe.item = o; pe.refclass = klass; mono_mem_manager_lock (mem_manager); if (mono_conc_g_hash_table_lookup_extended (mem_manager->refobject_hash, &pe, &orig_pe, &orig_value)) { mono_conc_g_hash_table_remove (mem_manager->refobject_hash, &pe); free_reflected_entry ((ReflectedEntry *)orig_pe); } mono_mem_manager_unlock (mem_manager); } /** * mono_assembly_get_object: * \param domain an app domain * \param assembly an assembly * \returns a \c System.Reflection.Assembly object representing the \c MonoAssembly \p assembly. */ MonoReflectionAssembly* mono_assembly_get_object (MonoDomain *domain, MonoAssembly *assembly) { HANDLE_FUNCTION_ENTER (); MonoReflectionAssemblyHandle result; MONO_ENTER_GC_UNSAFE; ERROR_DECL (error); result = mono_assembly_get_object_handle (assembly, error); mono_error_cleanup (error); /* FIXME new API that doesn't swallow the error */ MONO_EXIT_GC_UNSAFE; HANDLE_FUNCTION_RETURN_OBJ (result); } static MonoReflectionAssemblyHandle assembly_object_construct (MonoClass *unused_klass, MonoAssembly *assembly, gpointer user_data, MonoError *error) { error_init (error); MonoReflectionAssemblyHandle res = MONO_HANDLE_CAST (MonoReflectionAssembly, mono_object_new_handle (mono_class_get_mono_assembly_class (), error)); return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionAssembly, NULL_HANDLE)); MONO_HANDLE_SETVAL (res, assembly, MonoAssembly*, assembly); return res; } /* * mono_assembly_get_object_handle: * @assembly: an assembly * * Return an System.Reflection.Assembly object representing the MonoAssembly @assembly. */ MonoReflectionAssemblyHandle mono_assembly_get_object_handle (MonoAssembly *assembly, MonoError *error) { error_init (error); return CHECK_OR_CONSTRUCT_HANDLE (MonoReflectionAssembly, m_image_get_mem_manager (assembly->image), assembly, NULL, assembly_object_construct, NULL); } /** * mono_module_get_object: */ MonoReflectionModule* mono_module_get_object (MonoDomain *domain, MonoImage *image) { MonoReflectionModuleHandle result; HANDLE_FUNCTION_ENTER (); MONO_ENTER_GC_UNSAFE; ERROR_DECL (error); result = mono_module_get_object_handle (image, error); mono_error_cleanup (error); MONO_EXIT_GC_UNSAFE; HANDLE_FUNCTION_RETURN_OBJ (result); } static MonoReflectionModuleHandle module_object_construct (MonoClass *unused_klass, MonoImage *image, gpointer user_data, MonoError *error) { char* basename; error_init (error); MonoReflectionModuleHandle res = MONO_HANDLE_CAST (MonoReflectionModule, mono_object_new_handle (mono_class_get_mono_module_class (), error)); goto_if_nok (error, fail); MONO_HANDLE_SETVAL (res, image, MonoImage *, image); MonoReflectionAssemblyHandle assm_obj; assm_obj = mono_assembly_get_object_handle (image->assembly, error); goto_if_nok (error, fail); MONO_HANDLE_SET (res, assembly, assm_obj); MONO_HANDLE_SET (res, fqname, mono_string_new_handle (image->name, error)); goto_if_nok (error, fail); basename = g_path_get_basename (image->name); MONO_HANDLE_SET (res, name, mono_string_new_handle (basename, error)); goto_if_nok (error, fail); MONO_HANDLE_SET (res, scopename, mono_string_new_handle (image->module_name, error)); goto_if_nok (error, fail); g_free (basename); guint32 token; token = 0; if (image->assembly->image == image) { token = mono_metadata_make_token (MONO_TABLE_MODULE, 1); } else { int i; if (image->assembly->image->modules) { for (i = 0; i < image->assembly->image->module_count; i++) { if (image->assembly->image->modules [i] == image) token = mono_metadata_make_token (MONO_TABLE_MODULEREF, i + 1); } g_assert (token != 0); } } MONO_HANDLE_SETVAL (res, token, guint32, token); return res; fail: return MONO_HANDLE_CAST (MonoReflectionModule, NULL_HANDLE); } MonoReflectionModuleHandle mono_module_get_object_handle (MonoImage *image, MonoError *error) { error_init (error); return CHECK_OR_CONSTRUCT_HANDLE (MonoReflectionModule, m_image_get_mem_manager (image), image, NULL, module_object_construct, NULL); } /** * mono_module_file_get_object: */ MonoReflectionModule* mono_module_file_get_object (MonoDomain *domain, MonoImage *image, int table_index) { MonoReflectionModuleHandle result; HANDLE_FUNCTION_ENTER (); MONO_ENTER_GC_UNSAFE; ERROR_DECL (error); result = mono_module_file_get_object_handle (image, table_index, error); mono_error_cleanup (error); MONO_EXIT_GC_UNSAFE; HANDLE_FUNCTION_RETURN_OBJ (result); } MonoReflectionModuleHandle mono_module_file_get_object_handle (MonoImage *image, int table_index, MonoError *error) { MonoTableInfo *table; guint32 cols [MONO_FILE_SIZE]; const char *name; guint32 i, name_idx; const char *val; error_init (error); MonoReflectionModuleHandle res = MONO_HANDLE_CAST (MonoReflectionModule, mono_object_new_handle (mono_class_get_mono_module_class (), error)); goto_if_nok (error, fail); table = &image->tables [MONO_TABLE_FILE]; g_assert (table_index < table_info_get_rows (table)); mono_metadata_decode_row (table, table_index, cols, MONO_FILE_SIZE); MONO_HANDLE_SETVAL (res, image, MonoImage*, NULL); MonoReflectionAssemblyHandle assm_obj; assm_obj = mono_assembly_get_object_handle (image->assembly, error); goto_if_nok (error, fail); MONO_HANDLE_SET (res, assembly, assm_obj); name = mono_metadata_string_heap (image, cols [MONO_FILE_NAME]); /* Check whenever the row has a corresponding row in the moduleref table */ table = &image->tables [MONO_TABLE_MODULEREF]; int rows = table_info_get_rows (table); for (i = 0; i < rows; ++i) { name_idx = mono_metadata_decode_row_col (table, i, MONO_MODULEREF_NAME); val = mono_metadata_string_heap (image, name_idx); if (strcmp (val, name) == 0) MONO_HANDLE_SETVAL (res, image, MonoImage*, image->modules [i]); } MONO_HANDLE_SET (res, fqname, mono_string_new_handle (name, error)); goto_if_nok (error, fail); MONO_HANDLE_SET (res, name, mono_string_new_handle (name, error)); goto_if_nok (error, fail); MONO_HANDLE_SET (res, scopename, mono_string_new_handle (name, error)); goto_if_nok (error, fail); MONO_HANDLE_SETVAL (res, is_resource, MonoBoolean, cols [MONO_FILE_FLAGS] & FILE_CONTAINS_NO_METADATA); MONO_HANDLE_SETVAL (res, token, guint32, mono_metadata_make_token (MONO_TABLE_FILE, table_index + 1)); return res; fail: return MONO_HANDLE_CAST (MonoReflectionModule, NULL_HANDLE); } static MonoType* mono_type_normalize (MonoType *type) { int i; MonoGenericClass *gclass; MonoGenericInst *ginst; MonoClass *gtd; MonoGenericContainer *gcontainer; MonoType **argv = NULL; gboolean is_denorm_gtd = TRUE, requires_rebind = FALSE; if (type->type != MONO_TYPE_GENERICINST) return type; gclass = type->data.generic_class; ginst = gclass->context.class_inst; if (!ginst->is_open) return type; gtd = gclass->container_class; gcontainer = mono_class_get_generic_container (gtd); argv = g_newa (MonoType*, ginst->type_argc); for (i = 0; i < ginst->type_argc; ++i) { MonoType *t = ginst->type_argv [i], *norm; if (t->type != MONO_TYPE_VAR || t->data.generic_param->num != i || t->data.generic_param->owner != gcontainer) is_denorm_gtd = FALSE; norm = mono_type_normalize (t); argv [i] = norm; if (norm != t) requires_rebind = TRUE; } if (is_denorm_gtd) return m_type_is_byref (type) == m_type_is_byref (m_class_get_byval_arg (gtd)) ? m_class_get_byval_arg (gtd) : m_class_get_this_arg (gtd); if (requires_rebind) { MonoClass *klass = mono_class_bind_generic_parameters (gtd, ginst->type_argc, argv, gclass->is_dynamic); return m_type_is_byref (type) == m_type_is_byref (m_class_get_byval_arg (klass)) ? m_class_get_byval_arg (klass) : m_class_get_this_arg (klass); } return type; } /** * mono_type_get_object: * \param domain an app domain * \param type a type * \returns A \c System.MonoType object representing the type \p type. */ MonoReflectionType* mono_type_get_object (MonoDomain *domain, MonoType *type) { MonoReflectionType *ret; MONO_ENTER_GC_UNSAFE; ERROR_DECL (error); ret = mono_type_get_object_checked (type, error); mono_error_cleanup (error); MONO_EXIT_GC_UNSAFE; return ret; } MonoReflectionType* mono_type_get_object_checked (MonoType *type, MonoError *error) { MonoType *norm_type; MonoReflectionType *res, *cached; MonoClass *klass; MonoDomain *domain = mono_get_root_domain (); error_init (error); g_assert (type != NULL); klass = mono_class_from_mono_type_internal (type); MonoMemoryManager *memory_manager = m_class_get_mem_manager (klass); /*we must avoid using @type as it might have come * from a mono_metadata_type_dup and the caller * expects that is can be freed. * Using the right type from */ type = m_type_is_byref (m_class_get_byval_arg (klass)) == m_type_is_byref (type) ? m_class_get_byval_arg (klass) : m_class_get_this_arg (klass); /* We don't want to return types with custom modifiers to the managed * world since they're hard to distinguish from plain types using the * reflection APIs, but they are not ReferenceEqual to the unadorned * types. * * If we ever see cmods here, it's a bug: MonoClass:byval_arg and * MonoClass:this_arg shouldn't have cmods by construction. */ g_assert (!type->has_cmods); /* void is very common */ if (!m_type_is_byref (type) && type->type == MONO_TYPE_VOID && domain->typeof_void) return (MonoReflectionType*)domain->typeof_void; /* * If the vtable of the given class was already created, we can use * the MonoType from there and avoid all locking and hash table lookups. * * We cannot do this for TypeBuilders as mono_reflection_create_runtime_class expects * that the resulting object is different. */ if (type == m_class_get_byval_arg (klass) && !image_is_dynamic (m_class_get_image (klass))) { MonoVTable *vtable = mono_class_try_get_vtable (klass); if (vtable && vtable->type) return (MonoReflectionType *)vtable->type; } mono_loader_lock (); /*FIXME mono_class_init_internal and mono_class_vtable acquire it*/ mono_mem_manager_lock (memory_manager); res = (MonoReflectionType *)mono_g_hash_table_lookup (memory_manager->type_hash, type); mono_mem_manager_unlock (memory_manager); if (res) goto leave; /*Types must be normalized so a generic instance of the GTD get's the same inner type. * For example in: Foo<A,B>; Bar<A> : Foo<A, Bar<A>> * The second Bar will be encoded a generic instance of Bar with <A> as parameter. * On all other places, Bar<A> will be encoded as the GTD itself. This is an implementation * artifact of how generics are encoded and should be transparent to managed code so we * need to weed out this diference when retrieving managed System.Type objects. */ norm_type = mono_type_normalize (type); if (norm_type != type) { res = mono_type_get_object_checked (norm_type, error); goto_if_nok (error, leave); mono_mem_manager_lock (memory_manager); cached = (MonoReflectionType *)mono_g_hash_table_lookup (memory_manager->type_hash, type); if (cached) { res = cached; } else { mono_g_hash_table_insert_internal (memory_manager->type_hash, type, res); } mono_mem_manager_unlock (memory_manager); goto leave; } if ((type->type == MONO_TYPE_GENERICINST) && type->data.generic_class->is_dynamic && !m_class_was_typebuilder (type->data.generic_class->container_class)) { /* This can happen if a TypeBuilder for a generic class K<T,U> * had reflection_create_generic_class) called on it, but not * ves_icall_TypeBuilder_create_runtime_class. This can happen * if the K`2 is refernced from a generic instantiation * (e.g. K<int,string>) that appears as type argument * (e.g. Dict<string,K<int,string>>), field (e.g. K<int,string> * Foo) or method signature, parent class or any of the above * in a nested class of some other TypeBuilder. Such an * occurrence caused mono_reflection_type_get_handle to be * called on the sre generic instance (K<int,string>) which * required the container_class for the generic class K`2 to be * set up, but the remainder of class construction for K`2 has * not been done. */ char * full_name = mono_type_get_full_name (klass); /* I would have expected ReflectionTypeLoadException, but evidently .NET throws TLE in this case. */ mono_error_set_type_load_class (error, klass, "TypeBuilder.CreateType() not called for generic class %s", full_name); g_free (full_name); res = NULL; goto leave; } if (mono_class_has_ref_info (klass) && !m_class_was_typebuilder (klass) && !m_type_is_byref (type)) { res = &mono_class_get_ref_info_raw (klass)->type; /* FIXME use handles */ goto leave; } /* This is stored in vtables/JITted code so it has to be pinned */ res = (MonoReflectionType *)mono_object_new_pinned (mono_defaults.runtimetype_class, error); goto_if_nok (error, leave); res->type = type; mono_mem_manager_lock (memory_manager); cached = (MonoReflectionType *)mono_g_hash_table_lookup (memory_manager->type_hash, type); if (cached) { res = cached; } else { mono_g_hash_table_insert_internal (memory_manager->type_hash, type, res); if (type->type == MONO_TYPE_VOID && !m_type_is_byref (type)) domain->typeof_void = (MonoObject*)res; } mono_mem_manager_unlock (memory_manager); leave: mono_loader_unlock (); return res; } MonoReflectionTypeHandle mono_type_get_object_handle (MonoType *type, MonoError *error) { /* NOTE: We happen to know that mono_type_get_object_checked returns * pinned objects, so we can just wrap its return value in a handle for * uniformity. If it ever starts returning unpinned, objects, this * implementation would need to change! */ return MONO_HANDLE_NEW (MonoReflectionType, mono_type_get_object_checked (type, error)); } /** * mono_method_get_object: * \param domain an app domain * \param method a method * \param refclass the reflected type (can be NULL) * \returns A \c System.Reflection.MonoMethod object representing the method \p method. */ MonoReflectionMethod* mono_method_get_object (MonoDomain *domain, MonoMethod *method, MonoClass *refclass) { HANDLE_FUNCTION_ENTER (); MonoReflectionMethodHandle ret; MONO_ENTER_GC_UNSAFE; ERROR_DECL (error); ret = mono_method_get_object_handle (method, refclass, error); mono_error_cleanup (error); MONO_EXIT_GC_UNSAFE; HANDLE_FUNCTION_RETURN_OBJ (ret); } static MonoReflectionMethodHandle method_object_construct (MonoClass *refclass, MonoMethod *method, gpointer user_data, MonoError *error) { error_init (error); g_assert (refclass != NULL); /* * We use the same C representation for methods and constructors, but the type * name in C# is different. */ MonoClass *klass; error_init (error); if (*method->name == '.' && (strcmp (method->name, ".ctor") == 0 || strcmp (method->name, ".cctor") == 0)) { klass = mono_class_get_mono_cmethod_class (); } else { klass = mono_class_get_mono_method_class (); } MonoReflectionMethodHandle ret = MONO_HANDLE_CAST (MonoReflectionMethod, mono_object_new_handle (klass, error)); goto_if_nok (error, fail); MONO_HANDLE_SETVAL (ret, method, MonoMethod*, method); MonoReflectionTypeHandle rt; rt = mono_type_get_object_handle (m_class_get_byval_arg (refclass), error); goto_if_nok (error, fail); MONO_HANDLE_SET (ret, reftype, rt); return ret; fail: return MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE); } /* * mono_method_get_object_handle: * @method: a method * @refclass: the reflected type (can be NULL) * @error: set on error. * * Return an System.Reflection.MonoMethod object representing the method @method. * Returns NULL and sets @error on error. */ MonoReflectionMethodHandle mono_method_get_object_handle (MonoMethod *method, MonoClass *refclass, MonoError *error) { error_init (error); if (!refclass) refclass = method->klass; // FIXME: For methods/params etc., use the mem manager for refclass or a merged one ? return CHECK_OR_CONSTRUCT_HANDLE (MonoReflectionMethod, m_method_get_mem_manager (method), method, refclass, method_object_construct, NULL); } /* * mono_method_get_object_checked: * @method: a method * @refclass: the reflected type (can be NULL) * @error: set on error. * * Return an System.Reflection.MonoMethod object representing the method @method. * Returns NULL and sets @error on error. */ MonoReflectionMethod* mono_method_get_object_checked (MonoMethod *method, MonoClass *refclass, MonoError *error) { HANDLE_FUNCTION_ENTER (); MonoReflectionMethodHandle result = mono_method_get_object_handle (method, refclass, error); HANDLE_FUNCTION_RETURN_OBJ (result); } /* * mono_method_clear_object: * * Clear the cached reflection objects for the dynamic method METHOD. */ void mono_method_clear_object (MonoMethod *method) { MonoClass *klass; g_assert (method_is_dynamic (method)); MonoMemoryManager *mem_manager = m_method_get_mem_manager (method); klass = method->klass; while (klass) { clear_cached_object (mem_manager, method, klass); klass = m_class_get_parent (klass); } /* Added by mono_param_get_objects () */ clear_cached_object (mem_manager, &(method->signature), NULL); klass = method->klass; while (klass) { clear_cached_object (mem_manager, &(method->signature), klass); klass = m_class_get_parent (klass); } } /** * mono_field_get_object: * \param domain an app domain * \param klass a type * \param field a field * \returns A \c System.Reflection.MonoField object representing the field \p field * in class \p klass. */ MonoReflectionField* mono_field_get_object (MonoDomain *domain, MonoClass *klass, MonoClassField *field) { MonoReflectionFieldHandle result; HANDLE_FUNCTION_ENTER (); MONO_ENTER_GC_UNSAFE; ERROR_DECL (error); result = mono_field_get_object_handle (klass, field, error); mono_error_cleanup (error); MONO_EXIT_GC_UNSAFE; HANDLE_FUNCTION_RETURN_OBJ (result); } static MonoReflectionFieldHandle field_object_construct (MonoClass *klass, MonoClassField *field, gpointer user_data, MonoError *error) { error_init (error); MonoReflectionFieldHandle res = MONO_HANDLE_CAST (MonoReflectionField, mono_object_new_handle (mono_class_get_mono_field_class (), error)); goto_if_nok (error, fail); MONO_HANDLE_SETVAL (res, klass, MonoClass *, klass); MONO_HANDLE_SETVAL (res, field, MonoClassField *, field); MonoStringHandle name; name = mono_string_new_handle (mono_field_get_name (field), error); goto_if_nok (error, fail); MONO_HANDLE_SET (res, name, name); if (field->type) { MonoReflectionTypeHandle rt = mono_type_get_object_handle (field->type, error); goto_if_nok (error, fail); MONO_HANDLE_SET (res, type, rt); } MONO_HANDLE_SETVAL (res, attrs, guint32, mono_field_get_flags (field)); return res; fail: return MONO_HANDLE_CAST (MonoReflectionField, NULL_HANDLE); } /* * mono_field_get_object_handle: * @klass: a type * @field: a field * @error: set on error * * Return an System.Reflection.MonoField object representing the field @field * in class @klass. On error, returns NULL and sets @error. */ MonoReflectionFieldHandle mono_field_get_object_handle (MonoClass *klass, MonoClassField *field, MonoError *error) { error_init (error); return CHECK_OR_CONSTRUCT_HANDLE (MonoReflectionField, m_class_get_mem_manager (m_field_get_parent (field)), field, klass, field_object_construct, NULL); } /* * mono_field_get_object_checked: * @klass: a type * @field: a field * @error: set on error * * Return an System.Reflection.MonoField object representing the field @field * in class @klass. On error, returns NULL and sets @error. */ MonoReflectionField* mono_field_get_object_checked (MonoClass *klass, MonoClassField *field, MonoError *error) { HANDLE_FUNCTION_ENTER (); MonoReflectionFieldHandle result = mono_field_get_object_handle (klass, field, error); HANDLE_FUNCTION_RETURN_OBJ (result); } /* * mono_property_get_object: * @domain: an app domain * @klass: a type * @property: a property * * Return an System.Reflection.MonoProperty object representing the property @property * in class @klass. */ MonoReflectionProperty* mono_property_get_object (MonoDomain *domain, MonoClass *klass, MonoProperty *property) { MonoReflectionPropertyHandle result; HANDLE_FUNCTION_ENTER (); MONO_ENTER_GC_UNSAFE; ERROR_DECL (error); result = mono_property_get_object_handle (klass, property, error); mono_error_cleanup (error); MONO_EXIT_GC_UNSAFE; HANDLE_FUNCTION_RETURN_OBJ (result); } static MonoReflectionPropertyHandle property_object_construct (MonoClass *klass, MonoProperty *property, gpointer user_data, MonoError *error) { error_init (error); MonoReflectionPropertyHandle res = MONO_HANDLE_CAST (MonoReflectionProperty, mono_object_new_handle (mono_class_get_mono_property_class (), error)); goto_if_nok (error, fail); MONO_HANDLE_SETVAL (res, klass, MonoClass *, klass); MONO_HANDLE_SETVAL (res, property, MonoProperty *, property); return res; fail: return MONO_HANDLE_CAST (MonoReflectionProperty, NULL_HANDLE); } /** * mono_property_get_object_handle: * \param klass a type * \param property a property * \param error set on error * * \returns A \c System.Reflection.MonoProperty object representing the property \p property * in class \p klass. On error returns NULL and sets \p error. */ MonoReflectionPropertyHandle mono_property_get_object_handle (MonoClass *klass, MonoProperty *property, MonoError *error) { return CHECK_OR_CONSTRUCT_HANDLE (MonoReflectionProperty, m_class_get_mem_manager (property->parent), property, klass, property_object_construct, NULL); } /** * mono_property_get_object: * \param domain an app domain * \param klass a type * \param property a property * \param error set on error * \returns a \c System.Reflection.MonoProperty object representing the property \p property * in class \p klass. On error returns NULL and sets \p error. */ MonoReflectionProperty* mono_property_get_object_checked (MonoClass *klass, MonoProperty *property, MonoError *error) { HANDLE_FUNCTION_ENTER (); MonoReflectionPropertyHandle res = mono_property_get_object_handle (klass, property, error); HANDLE_FUNCTION_RETURN_OBJ (res); } /** * mono_event_get_object: * \param domain an app domain * \param klass a type * \param event a event * \returns A \c System.Reflection.MonoEvent object representing the event \p event * in class \p klass. */ MonoReflectionEvent* mono_event_get_object (MonoDomain *domain, MonoClass *klass, MonoEvent *event) { MonoReflectionEventHandle result; HANDLE_FUNCTION_ENTER (); MONO_ENTER_GC_UNSAFE; ERROR_DECL (error); result = mono_event_get_object_handle (klass, event, error); mono_error_cleanup (error); MONO_EXIT_GC_UNSAFE; HANDLE_FUNCTION_RETURN_OBJ (result); } static MonoReflectionEventHandle event_object_construct (MonoClass *klass, MonoEvent *event, gpointer user_data, MonoError *error) { error_init (error); MonoReflectionMonoEventHandle mono_event = MONO_HANDLE_CAST (MonoReflectionMonoEvent, mono_object_new_handle (mono_class_get_mono_event_class (), error)); if (!is_ok (error)) return MONO_HANDLE_CAST (MonoReflectionEvent, NULL_HANDLE); MONO_HANDLE_SETVAL (mono_event, klass, MonoClass* , klass); MONO_HANDLE_SETVAL (mono_event, event, MonoEvent* , event); return MONO_HANDLE_CAST (MonoReflectionEvent, mono_event); } /** * mono_event_get_object_handle: * \param klass a type * \param event a event * \param error set on error * \returns a \c System.Reflection.MonoEvent object representing the event \p event * in class \p klass. On failure sets \p error and returns NULL */ MonoReflectionEventHandle mono_event_get_object_handle (MonoClass *klass, MonoEvent *event, MonoError *error) { error_init (error); return CHECK_OR_CONSTRUCT_HANDLE (MonoReflectionEvent, m_class_get_mem_manager (event->parent), event, klass, event_object_construct, NULL); } /** * mono_get_reflection_missing_object: * * \returns the \c System.Reflection.Missing.Value singleton object * (of type \c System.Reflection.Missing). * * Used as the value for \c ParameterInfo.DefaultValue when Optional * is present */ static MonoObjectHandle mono_get_reflection_missing_object (void) { ERROR_DECL (error); MONO_STATIC_POINTER_INIT (MonoClassField, missing_value_field) MonoClass *missing_klass = mono_class_get_missing_class (); mono_class_init_internal (missing_klass); missing_value_field = mono_class_get_field_from_name_full (missing_klass, "Value", NULL); g_assert (missing_value_field); MONO_STATIC_POINTER_INIT_END (MonoClassField, missing_value_field) /* FIXME change mono_field_get_value_object_checked to return a handle */ MonoObjectHandle obj = MONO_HANDLE_NEW (MonoObject, mono_field_get_value_object_checked (missing_value_field, NULL, error)); mono_error_assert_ok (error); return obj; } static MonoObjectHandle get_dbnull_object (MonoError *error) { error_init (error); MONO_STATIC_POINTER_INIT (MonoClassField, dbnull_value_field) MonoClass *dbnull_klass = mono_class_get_dbnull_class (); dbnull_value_field = mono_class_get_field_from_name_full (dbnull_klass, "Value", NULL); g_assert (dbnull_value_field); MONO_STATIC_POINTER_INIT_END (MonoClassField, dbnull_value_field) /* FIXME change mono_field_get_value_object_checked to return a handle */ MonoObjectHandle obj = MONO_HANDLE_NEW (MonoObject, mono_field_get_value_object_checked (dbnull_value_field, NULL, error)); return obj; } static MonoObjectHandle get_dbnull (MonoObjectHandle dbnull, MonoError *error) { error_init (error); if (MONO_HANDLE_IS_NULL (dbnull)) MONO_HANDLE_ASSIGN (dbnull, get_dbnull_object (error)); return dbnull; } static MonoObjectHandle get_reflection_missing (MonoObjectHandleOut reflection_missing) { if (MONO_HANDLE_IS_NULL (reflection_missing)) MONO_HANDLE_ASSIGN (reflection_missing, mono_get_reflection_missing_object ()); return reflection_missing; } static gboolean add_parameter_object_to_array (MonoMethod *method, MonoObjectHandle member, int idx, const char *name, MonoType *sig_param, guint32 blob_type_enum, const char *blob, MonoMarshalSpec *mspec, MonoObjectHandle missing, MonoObjectHandle dbnull, MonoArrayHandle dest, MonoError *error) { HANDLE_FUNCTION_ENTER (); error_init (error); MonoReflectionParameterHandle param = MONO_HANDLE_CAST (MonoReflectionParameter, mono_object_new_handle (mono_class_get_mono_parameter_info_class (), error)); goto_if_nok (error, leave); static MonoMethod *ctor; if (!ctor) { MonoMethod *m = mono_class_get_method_from_name_checked (mono_class_get_mono_parameter_info_class (), ".ctor", 7, 0, error); g_assert (m); mono_memory_barrier (); ctor = m; } MonoReflectionTypeHandle rt; rt = mono_type_get_object_handle (sig_param, error); goto_if_nok (error, leave); MonoStringHandle name_str; name_str = mono_string_new_handle (name, error); goto_if_nok (error, leave); MonoObjectHandle def_value; if (!(sig_param->attrs & PARAM_ATTRIBUTE_HAS_DEFAULT) || (method->wrapper_type != MONO_WRAPPER_NONE && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)) { if (sig_param->attrs & PARAM_ATTRIBUTE_OPTIONAL) def_value = get_reflection_missing (missing); else def_value = get_dbnull (dbnull, error); goto_if_nok (error, leave); } else { MonoType blob_type; blob_type.type = (MonoTypeEnum)blob_type_enum; blob_type.data.klass = NULL; if (blob_type_enum == MONO_TYPE_CLASS) blob_type.data.klass = mono_defaults.object_class; else if ((sig_param->type == MONO_TYPE_VALUETYPE) && m_class_is_enumtype (sig_param->data.klass)) { /* For enums, types [i] contains the base type */ blob_type.type = MONO_TYPE_VALUETYPE; blob_type.data.klass = mono_class_from_mono_type_internal (sig_param); } else blob_type.data.klass = mono_class_from_mono_type_internal (&blob_type); def_value = mono_get_object_from_blob (&blob_type, blob, MONO_HANDLE_NEW (MonoString, NULL), error); goto_if_nok (error, leave); /* Type in the Constant table is MONO_TYPE_CLASS for nulls */ if (blob_type_enum != MONO_TYPE_CLASS && MONO_HANDLE_IS_NULL(def_value)) { if (sig_param->attrs & PARAM_ATTRIBUTE_OPTIONAL) def_value = get_reflection_missing (missing); else def_value = get_dbnull (dbnull, error); goto_if_nok (error, leave); } } MonoReflectionMarshalAsAttributeHandle mobj; mobj = MONO_HANDLE_NEW (MonoReflectionMarshalAsAttribute, NULL); if (mspec) { mobj = mono_reflection_marshal_as_attribute_from_marshal_spec (method->klass, mspec, error); goto_if_nok (error, leave); } /* internal RuntimeParameterInfo (string name, Type type, int position, int attrs, object defaultValue, MemberInfo member, MarshalAsAttribute marshalAs) */ { int attrs = sig_param->attrs; void *args [ ] = { MONO_HANDLE_RAW (name_str), MONO_HANDLE_RAW (rt), &idx, &attrs, MONO_HANDLE_RAW (def_value), MONO_HANDLE_RAW (member), MONO_HANDLE_RAW (mobj) }; mono_runtime_invoke_handle_void (ctor, MONO_HANDLE_CAST (MonoObject, param), args, error); } goto_if_nok (error, leave); MONO_HANDLE_ARRAY_SETREF (dest, idx, param); leave: HANDLE_FUNCTION_RETURN_VAL (is_ok (error)); } static MonoArrayHandle param_objects_construct (MonoClass *refclass, MonoMethodSignature **addr_of_sig, gpointer user_data, MonoError *error) { MonoMethod *method = (MonoMethod*)user_data; MonoMethodSignature *sig = *addr_of_sig; /* see note in mono_param_get_objects_internal */ MonoArrayHandle res = MONO_HANDLE_NEW (MonoArray, NULL); char **names = NULL, **blobs = NULL; guint32 *types = NULL; MonoMarshalSpec **mspecs = NULL; int i; error_init (error); MonoReflectionMethodHandle member = mono_method_get_object_handle (method, refclass, error); goto_if_nok (error, leave); names = g_new (char *, sig->param_count); mono_method_get_param_names (method, (const char **) names); mspecs = g_new (MonoMarshalSpec*, sig->param_count + 1); mono_method_get_marshal_info (method, mspecs); res = mono_array_new_handle (mono_class_get_mono_parameter_info_class (), sig->param_count, error); if (MONO_HANDLE_IS_NULL (res)) goto leave; gboolean any_default_value; any_default_value = FALSE; if (method->wrapper_type == MONO_WRAPPER_NONE || method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD ) { for (i = 0; i < sig->param_count; ++i) { if ((sig->params [i]->attrs & PARAM_ATTRIBUTE_HAS_DEFAULT) != 0) { any_default_value = TRUE; break; } } } if (any_default_value) { blobs = g_new0 (char *, sig->param_count); types = g_new0 (guint32, sig->param_count); get_default_param_value_blobs (method, blobs, types); } /* Handles missing and dbnull are assigned in add_parameter_object_to_array when needed */ MonoObjectHandle missing; missing = MONO_HANDLE_NEW (MonoObject, NULL); MonoObjectHandle dbnull; dbnull = MONO_HANDLE_NEW (MonoObject, NULL); for (i = 0; i < sig->param_count; ++i) { if (!add_parameter_object_to_array (method, MONO_HANDLE_CAST(MonoObject, member), i, names[i], sig->params[i], types ? types[i] : 0, blobs ? blobs[i] : NULL, mspecs [i + 1], missing, dbnull, res, error)) goto leave; } leave: g_free (names); g_free (blobs); g_free (types); if (sig && mspecs) { for (i = sig->param_count; i >= 0; i--) { if (mspecs [i]) mono_metadata_free_marshal_spec (mspecs [i]); } } g_free (mspecs); if (!is_ok (error)) return NULL_HANDLE_ARRAY; return res; } /* * mono_param_get_objects: * @method: a method * * Return an System.Reflection.ParameterInfo array object representing the parameters * in the method @method. */ MonoArrayHandle mono_param_get_objects_internal (MonoMethod *method, MonoClass *refclass, MonoError *error) { error_init (error); /* side-effect: sets method->signature non-NULL on success */ MonoMethodSignature *sig = mono_method_signature_checked (method, error); goto_if_nok (error, fail); if (!sig->param_count) { MonoArrayHandle res = mono_array_new_handle (mono_class_get_mono_parameter_info_class (), 0, error); goto_if_nok (error, fail); return res; } /* Note: the cache is based on the address of the signature into the method * since we already cache MethodInfos with the method as keys. */ return CHECK_OR_CONSTRUCT_HANDLE (MonoArray, m_method_get_mem_manager (method), &method->signature, refclass, param_objects_construct, method); fail: return MONO_HANDLE_NEW (MonoArray, NULL); } /** * mono_param_get_objects: */ MonoArray* mono_param_get_objects (MonoDomain *domain, MonoMethod *method) { MonoArrayHandle result; HANDLE_FUNCTION_ENTER (); MONO_ENTER_GC_UNSAFE; ERROR_DECL (error); result = mono_param_get_objects_internal (method, NULL, error); mono_error_assert_ok (error); MONO_EXIT_GC_UNSAFE; HANDLE_FUNCTION_RETURN_OBJ (result); } static gboolean add_local_var_info_to_array (MonoMethodHeader *header, int idx, MonoArrayHandle dest, MonoError *error) { HANDLE_FUNCTION_ENTER (); error_init (error); MonoReflectionLocalVariableInfoHandle info = MONO_HANDLE_CAST (MonoReflectionLocalVariableInfo, mono_object_new_handle (mono_class_get_local_variable_info_class (), error)); goto_if_nok (error, leave); MonoReflectionTypeHandle rt; rt = mono_type_get_object_handle (header->locals [idx], error); goto_if_nok (error, leave); MONO_HANDLE_SET (info, local_type, rt); MONO_HANDLE_SETVAL (info, is_pinned, MonoBoolean, header->locals [idx]->pinned); MONO_HANDLE_SETVAL (info, local_index, guint16, idx); MONO_HANDLE_ARRAY_SETREF (dest, idx, info); leave: HANDLE_FUNCTION_RETURN_VAL (is_ok (error)); } static gboolean add_exception_handling_clause_to_array (MonoMethodHeader *header, int idx, MonoArrayHandle dest, MonoError *error) { HANDLE_FUNCTION_ENTER (); error_init (error); MonoReflectionExceptionHandlingClauseHandle info = MONO_HANDLE_CAST (MonoReflectionExceptionHandlingClause, mono_object_new_handle (mono_class_get_exception_handling_clause_class (), error)); goto_if_nok (error, leave); MonoExceptionClause *clause; clause = &header->clauses [idx]; MONO_HANDLE_SETVAL (info, flags, gint32, clause->flags); MONO_HANDLE_SETVAL (info, try_offset, gint32, clause->try_offset); MONO_HANDLE_SETVAL (info, try_length, gint32, clause->try_len); MONO_HANDLE_SETVAL (info, handler_offset, gint32, clause->handler_offset); MONO_HANDLE_SETVAL (info, handler_length, gint32, clause->handler_len); if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) MONO_HANDLE_SETVAL (info, filter_offset, gint32, clause->data.filter_offset); else if (clause->data.catch_class) { MonoReflectionTypeHandle rt = mono_type_get_object_handle (m_class_get_byval_arg (clause->data.catch_class), error); goto_if_nok (error, leave); MONO_HANDLE_SET (info, catch_type, rt); } MONO_HANDLE_ARRAY_SETREF (dest, idx, info); leave: HANDLE_FUNCTION_RETURN_VAL (is_ok (error)); } /** * mono_method_body_get_object: * \param domain an app domain * \param method a method * \return A \c System.Reflection.MethodBody/RuntimeMethodBody object representing the method \p method. */ MonoReflectionMethodBody* mono_method_body_get_object (MonoDomain *domain, MonoMethod *method) { MonoReflectionMethodBodyHandle result; HANDLE_FUNCTION_ENTER (); MONO_ENTER_GC_UNSAFE; ERROR_DECL (error); result = mono_method_body_get_object_handle (method, error); mono_error_cleanup (error); MONO_EXIT_GC_UNSAFE; HANDLE_FUNCTION_RETURN_OBJ (result); } /* WARNING: This method can return NULL on success */ static MonoReflectionMethodBodyHandle method_body_object_construct (MonoClass *unused_class, MonoMethod *method, gpointer user_data, MonoError *error) { MonoMethodHeader *header = NULL; MonoImage *image; guint32 method_rva, local_var_sig_token; char *ptr; unsigned char format, flags; int i; gpointer params [6]; MonoBoolean init_locals_param; gint32 sig_token_param; gint32 max_stack_param; error_init (error); /* for compatibility with .net */ if (method_is_dynamic (method)) { mono_error_set_generic_error (error, "System", "InvalidOperationException", ""); goto fail; } image = m_class_get_image (method->klass); if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) || (method->flags & METHOD_ATTRIBUTE_ABSTRACT) || (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) || (image->raw_data && image->raw_data [1] != 'Z') || (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME)) return MONO_HANDLE_CAST (MonoReflectionMethodBody, NULL_HANDLE); header = mono_method_get_header_checked (method, error); goto_if_nok (error, fail); if (!image_is_dynamic (image)) { /* Obtain local vars signature token */ method_rva = mono_metadata_decode_row_col (&image->tables [MONO_TABLE_METHOD], mono_metadata_token_index (method->token) - 1, MONO_METHOD_RVA); ptr = mono_image_rva_map (image, method_rva); flags = *(const unsigned char *) ptr; format = flags & METHOD_HEADER_FORMAT_MASK; switch (format){ case METHOD_HEADER_TINY_FORMAT: local_var_sig_token = 0; break; case METHOD_HEADER_FAT_FORMAT: ptr += 2; ptr += 2; ptr += 4; local_var_sig_token = read32 (ptr); break; default: g_assert_not_reached (); } } else local_var_sig_token = 0; //FIXME static MonoMethod *ctor; if (!ctor) { MonoMethod *tmp = mono_class_get_method_from_name_checked (mono_class_get_method_body_class (), ".ctor", 6, 0, error); mono_error_assert_ok (error); g_assert (tmp); mono_memory_barrier (); ctor = tmp; } MonoReflectionMethodBodyHandle ret; ret = MONO_HANDLE_CAST (MonoReflectionMethodBody, mono_object_new_handle (mono_class_get_method_body_class (), error)); goto_if_nok (error, fail); MonoArrayHandle il_arr; il_arr = mono_array_new_handle (mono_defaults.byte_class, header->code_size, error); goto_if_nok (error, fail); MonoGCHandle il_gchandle; guint8* il_data; il_data = MONO_ARRAY_HANDLE_PIN (il_arr, guint8, 0, &il_gchandle); memcpy (il_data, header->code, header->code_size); mono_gchandle_free_internal (il_gchandle); /* Locals */ MonoArrayHandle locals_arr; locals_arr = mono_array_new_handle (mono_class_get_local_variable_info_class (), header->num_locals, error); goto_if_nok (error, fail); for (i = 0; i < header->num_locals; ++i) { if (!add_local_var_info_to_array (header, i, locals_arr, error)) goto fail; } /* Exceptions */ MonoArrayHandle exn_clauses; exn_clauses = mono_array_new_handle (mono_class_get_exception_handling_clause_class (), header->num_clauses, error); goto_if_nok (error, fail); for (i = 0; i < header->num_clauses; ++i) { if (!add_exception_handling_clause_to_array (header, i, exn_clauses, error)) goto fail; } /* MethodBody (ExceptionHandlingClause[] clauses, LocalVariableInfo[] locals, byte[] il, bool init_locals, int sig_token, int max_stack) */ init_locals_param = header->init_locals; sig_token_param = local_var_sig_token; max_stack_param = header->max_stack; mono_metadata_free_mh (header); header = NULL; params [0] = MONO_HANDLE_RAW (exn_clauses); params [1] = MONO_HANDLE_RAW (locals_arr); params [2] = MONO_HANDLE_RAW (il_arr); params [3] = &init_locals_param; params [4] = &sig_token_param; params [5] = &max_stack_param; mono_runtime_invoke_handle_void (ctor, MONO_HANDLE_CAST (MonoObject, ret), params, error); mono_error_assert_ok (error); return ret; fail: if (header) mono_metadata_free_mh (header); return MONO_HANDLE_CAST (MonoReflectionMethodBody, NULL_HANDLE); } /** * mono_method_body_get_object_handle: * \param method a method * \param error set on error * \returns a \c System.Reflection.MethodBody object representing the * method \p method. On failure, returns NULL and sets \p error. */ MonoReflectionMethodBodyHandle mono_method_body_get_object_handle (MonoMethod *method, MonoError *error) { error_init (error); return CHECK_OR_CONSTRUCT_HANDLE (MonoReflectionMethodBody, m_method_get_mem_manager (method), method, NULL, method_body_object_construct, NULL); } /** * mono_get_dbnull_object: * \param domain Domain where the object lives * Used as the value for \c ParameterInfo.DefaultValue * \returns the \c System.DBNull.Value singleton object */ MonoObject * mono_get_dbnull_object (MonoDomain *domain) { HANDLE_FUNCTION_ENTER (); ERROR_DECL (error); MonoObjectHandle obj = get_dbnull_object (error); mono_error_assert_ok (error); HANDLE_FUNCTION_RETURN_OBJ (obj); } static void get_default_param_value_blobs (MonoMethod *method, char **blobs, guint32 *types) { guint32 param_index, i, lastp, crow = 0; guint32 param_cols [MONO_PARAM_SIZE], const_cols [MONO_CONSTANT_SIZE]; gint32 idx; MonoClass *klass = method->klass; MonoImage *image = m_class_get_image (klass); MonoMethodSignature *methodsig = mono_method_signature_internal (method); MonoTableInfo *constt; MonoTableInfo *methodt; MonoTableInfo *paramt; if (!methodsig->param_count) return; mono_class_init_internal (klass); if (image_is_dynamic (image)) { MonoReflectionMethodAux *aux; if (method->is_inflated) method = ((MonoMethodInflated*)method)->declaring; aux = (MonoReflectionMethodAux *)g_hash_table_lookup (((MonoDynamicImage*)m_class_get_image (method->klass))->method_aux_hash, method); if (aux && aux->param_defaults) { memcpy (blobs, &(aux->param_defaults [1]), methodsig->param_count * sizeof (char*)); memcpy (types, &(aux->param_default_types [1]), methodsig->param_count * sizeof (guint32)); } return; } methodt = &image->tables [MONO_TABLE_METHOD]; paramt = &image->tables [MONO_TABLE_PARAM]; constt = &image->tables [MONO_TABLE_CONSTANT]; idx = mono_method_get_index (method); g_assert (idx != 0); /* lastp is the starting param index for the next method in the table, or * one past the last row if this is the last method */ /* FIXME: metadata-update : will this work with added methods ? */ param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST); if (!mono_metadata_table_bounds_check (image, MONO_TABLE_METHOD, idx + 1)) lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST); else lastp = table_info_get_rows (paramt) + 1; for (i = param_index; i < lastp; ++i) { guint32 paramseq; mono_metadata_decode_row (paramt, i - 1, param_cols, MONO_PARAM_SIZE); paramseq = param_cols [MONO_PARAM_SEQUENCE]; if (!(param_cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_DEFAULT)) continue; crow = mono_metadata_get_constant_index (image, MONO_TOKEN_PARAM_DEF | i, crow + 1); if (!crow) { continue; } mono_metadata_decode_row (constt, crow - 1, const_cols, MONO_CONSTANT_SIZE); blobs [paramseq - 1] = (char *)mono_metadata_blob_heap (image, const_cols [MONO_CONSTANT_VALUE]); types [paramseq - 1] = const_cols [MONO_CONSTANT_TYPE]; } return; } MonoObjectHandle mono_get_object_from_blob (MonoType *type, const char *blob, MonoStringHandleOut string_handle, MonoError *error) { error_init (error); if (!blob) return NULL_HANDLE; HANDLE_FUNCTION_ENTER (); MonoObject *object; void *retval = &object; MonoType *basetype = type; MonoObjectHandle object_handle = MONO_HANDLE_NEW (MonoObject, NULL); MonoClass* const klass = mono_class_from_mono_type_internal (type); if (m_class_is_valuetype (klass)) { object = mono_object_new_checked (klass, error); MONO_HANDLE_ASSIGN_RAW (object_handle, object); return_val_if_nok (error, NULL_HANDLE); retval = mono_object_get_data (object); if (m_class_is_enumtype (klass)) basetype = mono_class_enum_basetype_internal (klass); } if (mono_get_constant_value_from_blob (basetype->type, blob, retval, string_handle, error)) MONO_HANDLE_ASSIGN_RAW (object_handle, object); else object_handle = NULL_HANDLE; HANDLE_FUNCTION_RETURN_REF (MonoObject, object_handle); } static int assembly_name_to_aname (MonoAssemblyName *assembly, char *p) { int found_sep; char *s; gboolean quoted = FALSE; memset (assembly, 0, sizeof (MonoAssemblyName)); assembly->without_version = TRUE; assembly->without_culture = TRUE; assembly->without_public_key_token = TRUE; assembly->culture = ""; memset (assembly->public_key_token, 0, MONO_PUBLIC_KEY_TOKEN_LENGTH); if (*p == '"') { quoted = TRUE; p++; } assembly->name = p; s = p; while (*p && (isalnum (*p) || *p == '.' || *p == '-' || *p == '_' || *p == '$' || *p == '@' || g_ascii_isspace (*p))) p++; if (quoted) { if (*p != '"') return 1; *p = 0; p++; } g_strchomp (s); assembly->name = s; if (*p != ',') { g_strchomp (s); assembly->name = s; return 1; } *p = 0; /* Remove trailing whitespace */ s = p - 1; while (*s && g_ascii_isspace (*s)) *s-- = 0; p ++; while (g_ascii_isspace (*p)) p++; while (*p) { if ((*p == 'V' || *p == 'v') && g_ascii_strncasecmp (p, "Version", 7) == 0) { assembly->without_version = FALSE; p += 7; while (*p && *p != '=') p++; p++; while (*p && g_ascii_isspace (*p)) p++; assembly->major = strtoul (p, &s, 10); if (s == p || *s != '.') return 1; p = ++s; assembly->minor = strtoul (p, &s, 10); if (s == p || *s != '.') return 1; p = ++s; assembly->build = strtoul (p, &s, 10); if (s == p || *s != '.') return 1; p = ++s; assembly->revision = strtoul (p, &s, 10); if (s == p) return 1; p = s; } else if ((*p == 'C' || *p == 'c') && g_ascii_strncasecmp (p, "Culture", 7) == 0) { assembly->without_culture = FALSE; p += 7; while (*p && *p != '=') p++; p++; while (*p && g_ascii_isspace (*p)) p++; if ((g_ascii_strncasecmp (p, "neutral", 7) == 0) && (p [7] == ' ' || p [7] == ',')) { assembly->culture = ""; p += 7; } else { assembly->culture = p; while (*p && *p != ',') { if (*p == ' ') *p = 0; p++; } } } else if ((*p == 'P' || *p == 'p') && g_ascii_strncasecmp (p, "PublicKeyToken", 14) == 0) { assembly->without_public_key_token = FALSE; p += 14; while (*p && *p != '=') p++; p++; while (*p && g_ascii_isspace (*p)) p++; if (strncmp (p, "null", 4) == 0) { p += 4; } else { int len; gchar *start = p; while (*p && *p != ',') { p++; } len = (p - start + 1); if (len > MONO_PUBLIC_KEY_TOKEN_LENGTH) len = MONO_PUBLIC_KEY_TOKEN_LENGTH; char* pkt_lower = g_ascii_strdown (start, len); g_strlcpy ((char*) assembly->public_key_token, pkt_lower, len); g_free (pkt_lower); } } else { while (*p && *p != ',') p++; } found_sep = 0; while (g_ascii_isspace (*p) || *p == ',') { *p++ = 0; found_sep = 1; continue; } /* failed */ if (!found_sep) return 1; } return 0; } /* * mono_reflection_parse_type: * @name: type name * * Parse a type name as accepted by the GetType () method and output the info * extracted in the info structure. * the name param will be mangled, so, make a copy before passing it to this function. * The fields in info will be valid until the memory pointed to by name is valid. * * See also mono_type_get_name () below. * * Returns: 0 on parse error. */ static int _mono_reflection_parse_type (char *name, char **endptr, gboolean is_recursed, MonoTypeNameParse *info) { char *start, *p, *w, *last_point, *startn; int in_modifiers = 0; int isbyref = 0, rank = 0, isptr = 0; start = p = w = name; memset (info, 0, sizeof (MonoTypeNameParse)); /* last_point separates the namespace from the name */ last_point = NULL; /* Skips spaces */ while (*p == ' ') p++, start++, w++, name++; while (*p) { switch (*p) { case '+': *p = 0; /* NULL terminate the name */ startn = p + 1; info->nested = g_list_append (info->nested, startn); /* we have parsed the nesting namespace + name */ if (info->name) break; if (last_point) { info->name_space = start; *last_point = 0; info->name = last_point + 1; } else { info->name_space = (char *)""; info->name = start; } break; case '.': last_point = p; break; case '\\': ++p; break; case '&': case '*': case '[': case ',': case ']': in_modifiers = 1; break; default: break; } if (in_modifiers) break; // *w++ = *p++; p++; } if (!info->name) { if (last_point) { info->name_space = start; *last_point = 0; info->name = last_point + 1; } else { info->name_space = (char *)""; info->name = start; } } while (*p) { switch (*p) { case '&': if (isbyref) /* only one level allowed by the spec */ return 0; isbyref = 1; isptr = 0; info->modifiers = g_list_append (info->modifiers, GUINT_TO_POINTER (0)); *p++ = 0; break; case '*': if (isbyref) /* pointer to ref not okay */ return 0; info->modifiers = g_list_append (info->modifiers, GUINT_TO_POINTER (-1)); isptr = 1; *p++ = 0; break; case '[': if (isbyref) /* array of ref and generic ref are not okay */ return 0; //Decide if it's an array of a generic argument list *p++ = 0; if (!*p) //XXX test return 0; if (*p == ',' || *p == '*' || *p == ']') { //array gboolean bounded = FALSE; isptr = 0; rank = 1; while (*p) { if (*p == ']') break; if (*p == ',') rank++; else if (*p == '*') /* '*' means unknown lower bound */ bounded = TRUE; else return 0; ++p; } if (*p++ != ']') return 0; /* bounded only allowed when rank == 1 */ if (bounded && rank > 1) return 0; /* n.b. bounded needs both modifiers: -2 == bounded, 1 == rank 1 array */ if (bounded) info->modifiers = g_list_append (info->modifiers, GUINT_TO_POINTER (-2)); info->modifiers = g_list_append (info->modifiers, GUINT_TO_POINTER (rank)); } else { if (rank || isptr) /* generic args after array spec or ptr*/ //XXX test return 0; isptr = 0; info->type_arguments = g_ptr_array_new (); while (*p) { MonoTypeNameParse *subinfo = g_new0 (MonoTypeNameParse, 1); gboolean fqname = FALSE; g_ptr_array_add (info->type_arguments, subinfo); while (*p == ' ') p++; if (*p == '[') { p++; fqname = TRUE; } if (!_mono_reflection_parse_type (p, &p, TRUE, subinfo)) return 0; /*MS is lenient on [] delimited parameters that aren't fqn - and F# uses them.*/ if (fqname && (*p != ']')) { char *aname; if (*p != ',') return 0; *p++ = 0; aname = p; while (*p && (*p != ']')) p++; if (*p != ']') return 0; *p++ = 0; while (*aname) { if (g_ascii_isspace (*aname)) { ++aname; continue; } break; } if (!*aname || !assembly_name_to_aname (&subinfo->assembly, aname)) return 0; } else if (fqname && (*p == ']')) { *p++ = 0; } if (*p == ']') { *p++ = 0; break; } else if (!*p) { return 0; } *p++ = 0; } } break; case ']': if (is_recursed) goto end; return 0; case ',': if (is_recursed) goto end; *p++ = 0; while (*p) { if (g_ascii_isspace (*p)) { ++p; continue; } break; } if (!*p) return 0; /* missing assembly name */ if (!assembly_name_to_aname (&info->assembly, p)) return 0; break; default: return 0; } if (info->assembly.name) break; } // *w = 0; /* terminate class name */ end: if (!info->name || !*info->name) return 0; if (endptr) *endptr = p; /* add other consistency checks */ return 1; } /** * mono_identifier_unescape_type_name_chars: * \param identifier the display name of a mono type * * \returns The name in internal form, that is without escaping backslashes. * * The string is modified in place! */ char* mono_identifier_unescape_type_name_chars(char* identifier) { char *w, *r; if (!identifier) return NULL; for (w = r = identifier; *r != 0; r++) { char c = *r; if (c == '\\') { r++; if (*r == 0) break; c = *r; } *w = c; w++; } if (w != r) *w = 0; return identifier; } void mono_identifier_unescape_info (MonoTypeNameParse* info); static void unescape_each_type_argument(void* data, void* user_data) { MonoTypeNameParse* info = (MonoTypeNameParse*)data; mono_identifier_unescape_info (info); } static void unescape_each_nested_name (void* data, void* user_data) { char* nested_name = (char*) data; mono_identifier_unescape_type_name_chars(nested_name); } /** * mono_identifier_unescape_info: * * \param info a parsed display form of an (optionally assembly qualified) full type name. * * Destructively updates the info by unescaping the identifiers that * comprise the type namespace, name, nested types (if any) and * generic type arguments (if any). * * The resulting info has the names in internal form. * */ void mono_identifier_unescape_info (MonoTypeNameParse *info) { if (!info) return; mono_identifier_unescape_type_name_chars(info->name_space); mono_identifier_unescape_type_name_chars(info->name); // but don't escape info->assembly if (info->type_arguments) g_ptr_array_foreach(info->type_arguments, &unescape_each_type_argument, NULL); if (info->nested) g_list_foreach(info->nested, &unescape_each_nested_name, NULL); } /** * mono_reflection_parse_type: */ int mono_reflection_parse_type (char *name, MonoTypeNameParse *info) { gboolean result; MONO_ENTER_GC_UNSAFE; ERROR_DECL (error); result = mono_reflection_parse_type_checked (name, info, error); mono_error_cleanup (error); MONO_EXIT_GC_UNSAFE; return result ? 1 : 0; } /** * mono_reflection_parse_type_checked: * \param name the string to parse * \param info the parsed name components * \param error set on error * * Parse the given \p name and write the results to \p info, setting \p error * on error. The string \p name is modified in place and \p info points into * its memory and into allocated memory. * * \returns TRUE if parsing succeeded, otherwise returns FALSE and sets \p error. * */ gboolean mono_reflection_parse_type_checked (char *name, MonoTypeNameParse *info, MonoError *error) { error_init (error); int ok = _mono_reflection_parse_type (name, NULL, FALSE, info); if (ok) { mono_identifier_unescape_info (info); } else { mono_error_set_argument_format (error, "typeName@0", "failed parse: %s", name); } return (ok != 0); } static MonoType* _mono_reflection_get_type_from_info (MonoAssemblyLoadContext *alc, MonoTypeNameParse *info, MonoImage *image, gboolean ignorecase, gboolean search_mscorlib, MonoError *error) { gboolean type_resolve = FALSE; MonoType *type; MonoImage *rootimage = image; error_init (error); if (info->assembly.name) { MonoAssembly *assembly = mono_assembly_loaded_internal (alc, &info->assembly); if (!assembly && image && image->assembly && mono_assembly_check_name_match (&info->assembly, &image->assembly->aname)) /* * This could happen in the AOT compiler case when the search hook is not * installed. */ assembly = image->assembly; if (!assembly) { /* then we must load the assembly ourselve - see #60439 */ MonoAssemblyByNameRequest req; mono_assembly_request_prepare_byname (&req, alc); req.requesting_assembly = NULL; req.basedir = image ? image->assembly->basedir : NULL; assembly = mono_assembly_request_byname (&info->assembly, &req, NULL); if (!assembly) return NULL; } image = assembly->image; } else if (!image && search_mscorlib) { image = mono_defaults.corlib; } type = mono_reflection_get_type_with_rootimage (alc, rootimage, image, info, ignorecase, search_mscorlib, &type_resolve, error); if (type == NULL && !info->assembly.name && image != mono_defaults.corlib && search_mscorlib) { /* ignore the error and try again */ mono_error_cleanup (error); error_init (error); image = mono_defaults.corlib; type = mono_reflection_get_type_with_rootimage (alc, rootimage, image, info, ignorecase, search_mscorlib, &type_resolve, error); } return type; } /** * mono_reflection_get_type_internal: * * Returns: may return NULL on success, sets error on failure. */ static MonoType* mono_reflection_get_type_internal (MonoAssemblyLoadContext *alc, MonoImage *rootimage, MonoImage* image, MonoTypeNameParse *info, gboolean ignorecase, gboolean search_mscorlib, MonoError *error) { HANDLE_FUNCTION_ENTER (); MonoClass *klass; GList *mod; int modval; gboolean bounded = FALSE; MonoType* type = NULL; error_init (error); if (!image) image = mono_defaults.corlib; if (!rootimage) rootimage = mono_defaults.corlib; if (ignorecase) klass = mono_class_from_name_case_checked (image, info->name_space, info->name, error); else klass = mono_class_from_name_checked (image, info->name_space, info->name, error); if (!klass) goto leave; for (mod = info->nested; mod; mod = mod->next) { gpointer iter = NULL; MonoClass *parent; parent = klass; mono_class_init_internal (parent); while ((klass = mono_class_get_nested_types (parent, &iter))) { const char *lastp; char *nested_name, *nested_nspace; gboolean match = TRUE; lastp = strrchr ((const char *)mod->data, '.'); if (lastp) { /* Nested classes can have namespaces */ int nspace_len; nested_name = g_strdup (lastp + 1); nspace_len = lastp - (char*)mod->data; nested_nspace = (char *)g_malloc (nspace_len + 1); memcpy (nested_nspace, mod->data, nspace_len); nested_nspace [nspace_len] = '\0'; } else { nested_name = (char *)mod->data; nested_nspace = NULL; } if (nested_nspace) { const char *klass_name_space = m_class_get_name_space (klass); if (ignorecase) { if (!(klass_name_space && mono_utf8_strcasecmp (klass_name_space, nested_nspace) == 0)) match = FALSE; } else { if (!(klass_name_space && strcmp (klass_name_space, nested_nspace) == 0)) match = FALSE; } } if (match) { const char *klass_name = m_class_get_name (klass); if (ignorecase) { if (mono_utf8_strcasecmp (klass_name, nested_name) != 0) match = FALSE; } else { if (strcmp (klass_name, nested_name) != 0) match = FALSE; } } if (lastp) { g_free (nested_name); g_free (nested_nspace); } if (match) break; } if (!klass) break; } if (!klass) goto leave; if (info->type_arguments) { MonoType **type_args = g_new0 (MonoType *, info->type_arguments->len); MonoReflectionTypeHandle the_type; MonoType *instance; int i; for (i = 0; i < info->type_arguments->len; i++) { MonoTypeNameParse *subinfo = (MonoTypeNameParse *)g_ptr_array_index (info->type_arguments, i); type_args [i] = _mono_reflection_get_type_from_info (alc, subinfo, rootimage, ignorecase, search_mscorlib, error); if (!type_args [i]) { g_free (type_args); goto leave; } } the_type = mono_type_get_object_handle (m_class_get_byval_arg (klass), error); if (!is_ok (error) || MONO_HANDLE_IS_NULL (the_type)) goto leave; instance = mono_reflection_bind_generic_parameters ( the_type, info->type_arguments->len, type_args, error); g_free (type_args); if (!instance) goto leave; klass = mono_class_from_mono_type_internal (instance); } for (mod = info->modifiers; mod; mod = mod->next) { modval = GPOINTER_TO_UINT (mod->data); if (!modval) { /* byref: must be last modifier */ type = mono_class_get_byref_type (klass); goto leave; } else if (modval == -1) { klass = mono_class_create_ptr (m_class_get_byval_arg (klass)); } else if (modval == -2) { bounded = TRUE; } else { /* array rank */ klass = mono_class_create_bounded_array (klass, modval, bounded); } } type = m_class_get_byval_arg (klass); leave: HANDLE_FUNCTION_RETURN_VAL (type); } /** * mono_reflection_get_type: * \param image a metadata context * \param info type description structure * \param ignorecase flag for case-insensitive string compares * \param type_resolve whenever type resolve was already tried * * Build a MonoType from the type description in \p info. * */ MonoType* mono_reflection_get_type (MonoImage* image, MonoTypeNameParse *info, gboolean ignorecase, gboolean *type_resolve) { MonoType *result; MONO_ENTER_GC_UNSAFE; ERROR_DECL (error); result = mono_reflection_get_type_with_rootimage (mono_alc_get_default (), image, image, info, ignorecase, TRUE, type_resolve, error); mono_error_cleanup (error); MONO_EXIT_GC_UNSAFE; return result; } /** * mono_reflection_get_type_checked: * \param alc the AssemblyLoadContext to check/load into * \param rootimage the image of the currently active managed caller * \param image a metadata context * \param info type description structure * \param ignorecase flag for case-insensitive string compares * \param type_resolve whenever type resolve was already tried * \param * \param error set on error. * Build a \c MonoType from the type description in \p info. On failure returns NULL and sets \p error. */ MonoType* mono_reflection_get_type_checked (MonoAssemblyLoadContext *alc, MonoImage *rootimage, MonoImage* image, MonoTypeNameParse *info, gboolean ignorecase, gboolean search_mscorlib, gboolean *type_resolve, MonoError *error) { error_init (error); return mono_reflection_get_type_with_rootimage (alc, rootimage, image, info, ignorecase, search_mscorlib, type_resolve, error); } static MonoType* module_builder_array_get_type (MonoAssemblyLoadContext *alc, MonoArrayHandle module_builders, int i, MonoImage *rootimage, MonoTypeNameParse *info, gboolean ignorecase, gboolean search_mscorlib, MonoError *error) { HANDLE_FUNCTION_ENTER (); error_init (error); MonoType *type = NULL; MonoReflectionModuleBuilderHandle mb = MONO_HANDLE_NEW (MonoReflectionModuleBuilder, NULL); MONO_HANDLE_ARRAY_GETREF (mb, module_builders, i); MonoDynamicImage *dynamic_image = MONO_HANDLE_GETVAL (mb, dynamic_image); type = mono_reflection_get_type_internal (alc, rootimage, &dynamic_image->image, info, ignorecase, search_mscorlib, error); HANDLE_FUNCTION_RETURN_VAL (type); } static MonoType* module_array_get_type (MonoAssemblyLoadContext *alc, MonoArrayHandle modules, int i, MonoImage *rootimage, MonoTypeNameParse *info, gboolean ignorecase, gboolean search_mscorlib, MonoError *error) { HANDLE_FUNCTION_ENTER (); error_init (error); MonoType *type = NULL; MonoReflectionModuleHandle mod = MONO_HANDLE_NEW (MonoReflectionModule, NULL); MONO_HANDLE_ARRAY_GETREF (mod, modules, i); MonoImage *image = MONO_HANDLE_GETVAL (mod, image); type = mono_reflection_get_type_internal (alc, rootimage, image, info, ignorecase, search_mscorlib, error); HANDLE_FUNCTION_RETURN_VAL (type); } static MonoType* mono_reflection_get_type_internal_dynamic (MonoAssemblyLoadContext *alc, MonoImage *rootimage, MonoAssembly *assembly, MonoTypeNameParse *info, gboolean ignorecase, gboolean search_mscorlib, MonoError *error) { HANDLE_FUNCTION_ENTER (); MonoType *type = NULL; int i; error_init (error); g_assert (assembly_is_dynamic (assembly)); MonoReflectionAssemblyBuilderHandle abuilder = MONO_HANDLE_CAST (MonoReflectionAssemblyBuilder, mono_assembly_get_object_handle (assembly, error)); goto_if_nok (error, leave); /* Enumerate all modules */ MonoArrayHandle modules; modules = MONO_HANDLE_NEW (MonoArray, NULL); MONO_HANDLE_GET (modules, abuilder, modules); if (!MONO_HANDLE_IS_NULL (modules)) { int n = mono_array_handle_length (modules); for (i = 0; i < n; ++i) { type = module_builder_array_get_type (alc, modules, i, rootimage, info, ignorecase, search_mscorlib, error); if (type) break; goto_if_nok (error, leave); } } MonoArrayHandle loaded_modules; loaded_modules = MONO_HANDLE_NEW (MonoArray, NULL); MONO_HANDLE_GET (loaded_modules, abuilder, loaded_modules); if (!type && !MONO_HANDLE_IS_NULL(loaded_modules)) { int n = mono_array_handle_length (loaded_modules); for (i = 0; i < n; ++i) { type = module_array_get_type (alc, loaded_modules, i, rootimage, info, ignorecase, search_mscorlib, error); if (type) break; goto_if_nok (error, leave); } } leave: HANDLE_FUNCTION_RETURN_VAL (type); } MonoType* mono_reflection_get_type_with_rootimage (MonoAssemblyLoadContext *alc, MonoImage *rootimage, MonoImage* image, MonoTypeNameParse *info, gboolean ignorecase, gboolean search_mscorlib, gboolean *type_resolve, MonoError *error) { HANDLE_FUNCTION_ENTER (); MonoType *type; MonoReflectionAssemblyHandle reflection_assembly; MonoDomain *domain = mono_get_root_domain (); GString *fullName = NULL; GList *mod; error_init (error); if (image && image_is_dynamic (image)) type = mono_reflection_get_type_internal_dynamic (alc, rootimage, image->assembly, info, ignorecase, search_mscorlib, error); else type = mono_reflection_get_type_internal (alc, rootimage, image, info, ignorecase, search_mscorlib, error); goto_if_nok (error, return_null); if (type) goto exit; if (!mono_domain_has_type_resolve (domain)) goto return_null; if (type_resolve) { if (*type_resolve) goto return_null; *type_resolve = TRUE; } /* Reconstruct the type name */ fullName = g_string_new (""); if (info->name_space && (info->name_space [0] != '\0')) g_string_printf (fullName, "%s.%s", info->name_space, info->name); else g_string_printf (fullName, "%s", info->name); for (mod = info->nested; mod; mod = mod->next) g_string_append_printf (fullName, "+%s", (char*)mod->data); MonoStringHandle name_handle; name_handle = mono_string_new_handle (fullName->str, error); goto_if_nok (error, return_null); reflection_assembly = mono_domain_try_type_resolve_name (image->assembly, name_handle, error); goto_if_nok (error, return_null); if (MONO_HANDLE_BOOL (reflection_assembly)) { MonoAssembly *assembly = MONO_HANDLE_GETVAL (reflection_assembly, assembly); if (assembly_is_dynamic (assembly)) type = mono_reflection_get_type_internal_dynamic (alc, rootimage, assembly, info, ignorecase, search_mscorlib, error); else type = mono_reflection_get_type_internal (alc, rootimage, assembly->image, info, ignorecase, search_mscorlib, error); } goto_if_nok (error, return_null); goto exit; return_null: type = NULL; goto exit; exit: if (fullName) g_string_free (fullName, TRUE); HANDLE_FUNCTION_RETURN_VAL (type); } /** * mono_reflection_free_type_info: */ void mono_reflection_free_type_info (MonoTypeNameParse *info) { g_list_free (info->modifiers); g_list_free (info->nested); if (info->type_arguments) { int i; for (i = 0; i < info->type_arguments->len; i++) { MonoTypeNameParse *subinfo = (MonoTypeNameParse *)g_ptr_array_index (info->type_arguments, i); mono_reflection_free_type_info (subinfo); /*We free the subinfo since it is allocated by _mono_reflection_parse_type*/ g_free (subinfo); } g_ptr_array_free (info->type_arguments, TRUE); } } /** * mono_reflection_type_from_name: * \param name type name. * \param image a metadata context (can be NULL). * * Retrieves a \c MonoType from its \p name. If the name is not fully qualified, * it defaults to get the type from \p image or, if \p image is NULL or loading * from it fails, uses corlib. * */ MonoType* mono_reflection_type_from_name (char *name, MonoImage *image) { MonoType *result; MONO_ENTER_GC_UNSAFE; ERROR_DECL (error); MonoAssemblyLoadContext *alc = mono_alc_get_default (); result = mono_reflection_type_from_name_checked (name, alc, image, error); mono_error_cleanup (error); MONO_EXIT_GC_UNSAFE; return result; } /** * mono_reflection_type_from_name_checked: * \param name type name. * \param alc the AssemblyLoadContext to check/load into * \param image a metadata context (can be NULL). * \param error set on errror. * Retrieves a MonoType from its \p name. If the name is not fully qualified, * it defaults to get the type from \p image or, if \p image is NULL or loading * from it fails, uses corlib. On failure returns NULL and sets \p error. */ MonoType* mono_reflection_type_from_name_checked (char *name, MonoAssemblyLoadContext *alc, MonoImage *image, MonoError *error) { MonoType *type = NULL; MonoTypeNameParse info; char *tmp; error_init (error); /* Make a copy since parse_type modifies its argument */ tmp = g_strdup (name); /*g_print ("requested type %s\n", str);*/ ERROR_DECL (parse_error); if (!mono_reflection_parse_type_checked (tmp, &info, parse_error)) { mono_error_cleanup (parse_error); goto leave; } type = _mono_reflection_get_type_from_info (alc, &info, image, FALSE, TRUE, error); leave: g_free (tmp); mono_reflection_free_type_info (&info); return type; } /** * mono_reflection_get_token: * \returns the metadata token of \p obj which should be an object * representing a metadata element. */ guint32 mono_reflection_get_token (MonoObject *obj_raw) { guint32 result; HANDLE_FUNCTION_ENTER (); MONO_ENTER_GC_UNSAFE; MONO_HANDLE_DCL (MonoObject, obj); ERROR_DECL (error); result = mono_reflection_get_token_checked (obj, error); mono_error_assert_ok (error); MONO_EXIT_GC_UNSAFE; HANDLE_FUNCTION_RETURN_VAL (result); } /** * mono_reflection_get_param_info_member_and_pos: * * Return the MemberImpl and PositionImpl fields of P. */ void mono_reflection_get_param_info_member_and_pos (MonoReflectionParameterHandle p, MonoObjectHandle member_impl, int *out_position) { MonoClass *klass = mono_class_get_mono_parameter_info_class (); /* These two fields are part of ParameterInfo instead of RuntimeParameterInfo, and they cannot be moved */ static MonoClassField *member_field; if (!member_field) { MonoClassField *f = mono_class_get_field_from_name_full (klass, "MemberImpl", NULL); g_assert (f); member_field = f; } MonoObject *member; mono_field_get_value_internal (MONO_HANDLE_RAW (MONO_HANDLE_CAST (MonoObject, p)), member_field, &member); MONO_HANDLE_ASSIGN_RAW (member_impl, member); static MonoClassField *pos_field; if (!pos_field) { MonoClassField *f = mono_class_get_field_from_name_full (klass, "PositionImpl", NULL); g_assert (f); pos_field = f; } mono_field_get_value_internal (MONO_HANDLE_RAW (MONO_HANDLE_CAST (MonoObject, p)), pos_field, out_position); } /** * mono_reflection_get_token_checked: * \param obj the object * \param error set on error * \returns the metadata token of \p obj which should be an object * representing a metadata element. On failure sets \p error. */ guint32 mono_reflection_get_token_checked (MonoObjectHandle obj, MonoError *error) { guint32 token = 0; error_init (error); MonoClass *klass = mono_handle_class (obj); const char *klass_name = m_class_get_name (klass); if (strcmp (klass_name, "MethodBuilder") == 0) { MonoReflectionMethodBuilderHandle mb = MONO_HANDLE_CAST (MonoReflectionMethodBuilder, obj); token = MONO_HANDLE_GETVAL (mb, table_idx) | MONO_TOKEN_METHOD_DEF; } else if (strcmp (klass_name, "ConstructorBuilder") == 0) { MonoReflectionCtorBuilderHandle mb = MONO_HANDLE_CAST (MonoReflectionCtorBuilder, obj); token = MONO_HANDLE_GETVAL (mb, table_idx) | MONO_TOKEN_METHOD_DEF; } else if (strcmp (klass_name, "FieldBuilder") == 0) { g_assert_not_reached (); } else if (strcmp (klass_name, "TypeBuilder") == 0) { MonoReflectionTypeBuilderHandle tb = MONO_HANDLE_CAST (MonoReflectionTypeBuilder, obj); token = MONO_HANDLE_GETVAL (tb, table_idx) | MONO_TOKEN_TYPE_DEF; } else if (strcmp (klass_name, "RuntimeType") == 0) { MonoType *type = mono_reflection_type_handle_mono_type (MONO_HANDLE_CAST (MonoReflectionType, obj), error); return_val_if_nok (error, 0); MonoClass *mc = mono_class_from_mono_type_internal (type); if (!mono_class_init_internal (mc)) { mono_error_set_for_class_failure (error, mc); return 0; } token = m_class_get_type_token (mc); } else if (strcmp (klass_name, "RuntimeMethodInfo") == 0 || strcmp (klass_name, "RuntimeConstructorInfo") == 0) { MonoReflectionMethodHandle m = MONO_HANDLE_CAST (MonoReflectionMethod, obj); MonoMethod *method = MONO_HANDLE_GETVAL (m, method); if (method->is_inflated) { MonoMethodInflated *inflated = (MonoMethodInflated *) method; return inflated->declaring->token; } else { token = method->token; } } else if (strcmp (klass_name, "RuntimeFieldInfo") == 0) { MonoReflectionFieldHandle f = MONO_HANDLE_CAST (MonoReflectionField, obj); token = mono_class_get_field_token (MONO_HANDLE_GETVAL (f, field)); } else if (strcmp (klass_name, "RuntimePropertyInfo") == 0) { MonoReflectionPropertyHandle p = MONO_HANDLE_CAST (MonoReflectionProperty, obj); token = mono_class_get_property_token (MONO_HANDLE_GETVAL (p, property)); } else if (strcmp (klass_name, "RuntimeEventInfo") == 0) { MonoReflectionMonoEventHandle p = MONO_HANDLE_CAST (MonoReflectionMonoEvent, obj); token = mono_class_get_event_token (MONO_HANDLE_GETVAL (p, event)); } else if (strcmp (klass_name, "ParameterInfo") == 0 || strcmp (klass_name, "RuntimeParameterInfo") == 0) { MonoReflectionParameterHandle p = MONO_HANDLE_CAST (MonoReflectionParameter, obj); MonoObjectHandle member_impl = MONO_HANDLE_NEW (MonoObject, NULL); int position; mono_reflection_get_param_info_member_and_pos (p, member_impl, &position); MonoClass *member_class = mono_handle_class (member_impl); g_assert (mono_class_is_reflection_method_or_constructor (member_class)); MonoMethod *method = MONO_HANDLE_GETVAL (MONO_HANDLE_CAST (MonoReflectionMethod, member_impl), method); token = mono_method_get_param_token (method, position); } else if (strcmp (klass_name, "RuntimeModule") == 0 || strcmp (klass_name, "ModuleBuilder") == 0) { MonoReflectionModuleHandle m = MONO_HANDLE_CAST (MonoReflectionModule, obj); token = MONO_HANDLE_GETVAL (m, token); } else if (strcmp (klass_name, "RuntimeAssembly") == 0) { token = mono_metadata_make_token (MONO_TABLE_ASSEMBLY, 1); } else { mono_error_set_not_implemented (error, "MetadataToken is not supported for type '%s.%s'", m_class_get_name_space (klass), klass_name); return 0; } return token; } gboolean mono_reflection_is_usertype (MonoReflectionTypeHandle ref) { MonoClass *klass = mono_handle_class (ref); return m_class_get_image (klass) != mono_defaults.corlib || strcmp ("TypeDelegator", m_class_get_name (klass)) == 0; } /** * mono_reflection_bind_generic_parameters: * \param type a managed type object (which should be some kind of generic (instance? definition?)) * \param type_args the number of type arguments to bind * \param types array of type arguments * \param error set on error * Given a managed type object for a generic type instance, binds each of its arguments to the specified types. * \returns the \c MonoType* for the resulting type instantiation. On failure returns NULL and sets \p error. */ MonoType* mono_reflection_bind_generic_parameters (MonoReflectionTypeHandle reftype, int type_argc, MonoType **types, MonoError *error) { gboolean is_dynamic = FALSE; MonoClass *geninst; error_init (error); mono_loader_lock (); MonoClass *klass = mono_handle_class (reftype); if (mono_is_sre_type_builder (klass)) { is_dynamic = TRUE; } else if (mono_is_sre_generic_instance (klass)) { /* Does this ever make sense? what does instantiating a generic instance even mean? */ g_assert_not_reached (); MonoReflectionGenericClassHandle rgi = MONO_HANDLE_CAST (MonoReflectionGenericClass, reftype); MonoReflectionTypeHandle gtd = MONO_HANDLE_NEW_GET (MonoReflectionType, rgi, generic_type); if (mono_is_sre_type_builder (mono_handle_class (gtd))) is_dynamic = TRUE; } MonoType *t = mono_reflection_type_handle_mono_type (reftype, error); if (!is_ok (error)) { mono_loader_unlock (); return NULL; } klass = mono_class_from_mono_type_internal (t); if (!mono_class_is_gtd (klass)) { mono_loader_unlock (); mono_error_set_type_load_class (error, klass, "Cannot bind generic parameters of a non-generic type"); return NULL; } guint gtd_type_argc = mono_class_get_generic_container (klass)->type_argc; if (gtd_type_argc != type_argc) { mono_loader_unlock (); mono_error_set_argument_format (error, "types", "The generic type definition needs %d type arguments, but was instantiated with %d ", gtd_type_argc, type_argc); return NULL; } if (m_class_was_typebuilder (klass)) is_dynamic = TRUE; mono_loader_unlock (); geninst = mono_class_bind_generic_parameters (klass, type_argc, types, is_dynamic); return m_class_get_byval_arg (geninst); } MonoClass* mono_class_bind_generic_parameters (MonoClass *klass, int type_argc, MonoType **types, gboolean is_dynamic) { MonoGenericClass *gclass; MonoGenericInst *inst; g_assert (mono_class_is_gtd (klass)); inst = mono_metadata_get_generic_inst (type_argc, types); gclass = mono_metadata_lookup_generic_class (klass, inst, is_dynamic); return mono_class_create_generic_inst (gclass); } static MonoGenericInst* generic_inst_from_type_array_handle (MonoArrayHandle types, MonoError *error) { HANDLE_FUNCTION_ENTER (); error_init (error); MonoGenericInst *ginst = NULL; int count = mono_array_handle_length (types); MonoType **type_argv = g_new0 (MonoType *, count); MonoReflectionTypeHandle garg = MONO_HANDLE_NEW (MonoReflectionType, NULL); for (int i = 0; i < count; i++) { MONO_HANDLE_ARRAY_GETREF (garg, types, i); type_argv [i] = mono_reflection_type_handle_mono_type (garg, error); goto_if_nok (error, leave); } ginst = mono_metadata_get_generic_inst (count, type_argv); leave: g_free (type_argv); HANDLE_FUNCTION_RETURN_VAL (ginst); } static MonoMethod* reflection_bind_generic_method_parameters (MonoMethod *method, MonoArrayHandle types, MonoError *error) { MonoClass *klass; MonoMethod *inflated; MonoGenericContext tmp_context; error_init (error); klass = method->klass; if (method->is_inflated) method = ((MonoMethodInflated *) method)->declaring; int count = mono_method_signature_internal (method)->generic_param_count; if (count != mono_array_handle_length (types)) { mono_error_set_argument (error, "typeArguments", "Incorrect number of generic arguments"); return NULL; } MonoGenericInst *ginst = generic_inst_from_type_array_handle (types, error); return_val_if_nok (error, NULL); tmp_context.class_inst = mono_class_is_ginst (klass) ? mono_class_get_generic_class (klass)->context.class_inst : NULL; tmp_context.method_inst = ginst; inflated = mono_class_inflate_generic_method_checked (method, &tmp_context, error); mono_error_assert_ok (error); if (!mono_verifier_is_method_valid_generic_instantiation (inflated)) { mono_error_set_argument (error, NULL, "Invalid generic arguments"); return NULL; } return inflated; } MonoReflectionMethodHandle ves_icall_RuntimeMethodInfo_MakeGenericMethod_impl (MonoReflectionMethodHandle rmethod, MonoArrayHandle types, MonoError *error) { error_init (error); g_assert (0 != strcmp (m_class_get_name (mono_handle_class (rmethod)), "MethodBuilder")); MonoMethod *method = MONO_HANDLE_GETVAL (rmethod, method); MonoMethod *imethod = reflection_bind_generic_method_parameters (method, types, error); return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE)); MonoReflectionType *reftype = MONO_HANDLE_GETVAL (rmethod, reftype); MonoClass *refclass = mono_class_from_mono_type_internal (reftype->type); /*FIXME but I think this is no longer necessary*/ if (image_is_dynamic (m_class_get_image (method->klass))) { MonoDynamicImage *image = (MonoDynamicImage*)m_class_get_image (method->klass); /* * This table maps metadata structures representing inflated methods/fields * to the reflection objects representing their generic definitions. */ mono_image_lock ((MonoImage*)image); mono_g_hash_table_insert_internal (image->generic_def_objects, imethod, MONO_HANDLE_RAW (rmethod)); mono_image_unlock ((MonoImage*)image); } return mono_method_get_object_handle (imethod, refclass, error); } /* SECURITY_ACTION_* are defined in mono/metadata/tabledefs.h */ const static guint32 declsec_flags_map[] = { 0x00000000, /* empty */ MONO_DECLSEC_FLAG_REQUEST, /* SECURITY_ACTION_REQUEST (x01) */ MONO_DECLSEC_FLAG_DEMAND, /* SECURITY_ACTION_DEMAND (x02) */ MONO_DECLSEC_FLAG_ASSERT, /* SECURITY_ACTION_ASSERT (x03) */ MONO_DECLSEC_FLAG_DENY, /* SECURITY_ACTION_DENY (x04) */ MONO_DECLSEC_FLAG_PERMITONLY, /* SECURITY_ACTION_PERMITONLY (x05) */ MONO_DECLSEC_FLAG_LINKDEMAND, /* SECURITY_ACTION_LINKDEMAND (x06) */ MONO_DECLSEC_FLAG_INHERITANCEDEMAND, /* SECURITY_ACTION_INHERITANCEDEMAND (x07) */ MONO_DECLSEC_FLAG_REQUEST_MINIMUM, /* SECURITY_ACTION_REQUEST_MINIMUM (x08) */ MONO_DECLSEC_FLAG_REQUEST_OPTIONAL, /* SECURITY_ACTION_REQUEST_OPTIONAL (x09) */ MONO_DECLSEC_FLAG_REQUEST_REFUSE, /* SECURITY_ACTION_REQUEST_REFUSE (x0A) */ MONO_DECLSEC_FLAG_PREJIT_GRANT, /* SECURITY_ACTION_PREJIT_GRANT (x0B) */ MONO_DECLSEC_FLAG_PREJIT_DENY, /* SECURITY_ACTION_PREJIT_DENY (x0C) */ MONO_DECLSEC_FLAG_NONCAS_DEMAND, /* SECURITY_ACTION_NONCAS_DEMAND (x0D) */ MONO_DECLSEC_FLAG_NONCAS_LINKDEMAND, /* SECURITY_ACTION_NONCAS_LINKDEMAND (x0E) */ MONO_DECLSEC_FLAG_NONCAS_INHERITANCEDEMAND, /* SECURITY_ACTION_NONCAS_INHERITANCEDEMAND (x0F) */ MONO_DECLSEC_FLAG_LINKDEMAND_CHOICE, /* SECURITY_ACTION_LINKDEMAND_CHOICE (x10) */ MONO_DECLSEC_FLAG_INHERITANCEDEMAND_CHOICE, /* SECURITY_ACTION_INHERITANCEDEMAND_CHOICE (x11) */ MONO_DECLSEC_FLAG_DEMAND_CHOICE, /* SECURITY_ACTION_DEMAND_CHOICE (x12) */ }; /* * Returns flags that includes all available security action associated to the handle. * @token: metadata token (either for a class or a method) * @image: image where resides the metadata. */ static guint32 mono_declsec_get_flags (MonoImage *image, guint32 token) { int index = mono_metadata_declsec_from_index (image, token); MonoTableInfo *t = &image->tables [MONO_TABLE_DECLSECURITY]; guint32 result = 0; guint32 action; int i; /* HasSecurity can be present for other, not specially encoded, attributes, e.g. SuppressUnmanagedCodeSecurityAttribute */ if (index < 0) return 0; int rows = table_info_get_rows (t); for (i = index; i < rows; i++) { guint32 cols [MONO_DECL_SECURITY_SIZE]; mono_metadata_decode_row (t, i, cols, MONO_DECL_SECURITY_SIZE); if (cols [MONO_DECL_SECURITY_PARENT] != token) break; action = cols [MONO_DECL_SECURITY_ACTION]; if ((action >= MONO_DECLSEC_ACTION_MIN) && (action <= MONO_DECLSEC_ACTION_MAX)) { result |= declsec_flags_map [action]; } else { g_assert_not_reached (); } } return result; } /** * mono_declsec_flags_from_method: * \param method The method for which we want the declarative security flags. * Get the security actions (in the form of flags) associated with the specified method. * To keep \c MonoMethod size down we do not cache the declarative security flags * (except for the stack modifiers which are kept in the MonoJitInfo structure) * \returns the declarative security flags for the method (only). */ guint32 mono_declsec_flags_from_method (MonoMethod *method) { if (method->flags & METHOD_ATTRIBUTE_HAS_SECURITY) { /* FIXME: No cache (for the moment) */ guint32 idx = mono_method_get_index (method); idx <<= MONO_HAS_DECL_SECURITY_BITS; idx |= MONO_HAS_DECL_SECURITY_METHODDEF; return mono_declsec_get_flags (m_class_get_image (method->klass), idx); } return 0; } /** * mono_declsec_flags_from_class: * \param klass The class for which we want the declarative security flags. * Get the security actions (in the form of flags) associated with the specified class. * We cache the flags inside the \c MonoClass structure as this will get * called very often (at least for each method). * \returns the declarative security flags for the class. */ guint32 mono_declsec_flags_from_class (MonoClass *klass) { if (mono_class_get_flags (klass) & TYPE_ATTRIBUTE_HAS_SECURITY) { guint32 flags = mono_class_get_declsec_flags (klass); if (!flags) { guint32 idx; idx = mono_metadata_token_index (m_class_get_type_token (klass)); idx <<= MONO_HAS_DECL_SECURITY_BITS; idx |= MONO_HAS_DECL_SECURITY_TYPEDEF; flags = mono_declsec_get_flags (m_class_get_image (klass), idx); /* we cache the flags on classes */ mono_class_set_declsec_flags (klass, flags); } return flags; } return 0; } /** * mono_declsec_flags_from_assembly: * \param assembly The assembly for which we want the declarative security flags. * Get the security actions (in the form of flags) associated with the specified assembly. * \returns the declarative security flags for the assembly. */ guint32 mono_declsec_flags_from_assembly (MonoAssembly *assembly) { guint32 idx = 1; /* there is only one assembly */ idx <<= MONO_HAS_DECL_SECURITY_BITS; idx |= MONO_HAS_DECL_SECURITY_ASSEMBLY; return mono_declsec_get_flags (assembly->image, idx); } /* * Fill actions for the specific index (which may either be an encoded class token or * an encoded method token) from the metadata image. * Returns TRUE if some actions requiring code generation are present, FALSE otherwise. */ static MonoBoolean fill_actions_from_index (MonoImage *image, guint32 token, MonoDeclSecurityActions* actions, guint32 id_std, guint32 id_noncas, guint32 id_choice) { MonoBoolean result = FALSE; MonoTableInfo *t; guint32 cols [MONO_DECL_SECURITY_SIZE]; int index = mono_metadata_declsec_from_index (image, token); int i; t = &image->tables [MONO_TABLE_DECLSECURITY]; int rows = table_info_get_rows (t); for (i = index; i < rows; i++) { mono_metadata_decode_row (t, i, cols, MONO_DECL_SECURITY_SIZE); if (cols [MONO_DECL_SECURITY_PARENT] != token) return result; /* if present only replace (class) permissions with method permissions */ /* if empty accept either class or method permissions */ if (cols [MONO_DECL_SECURITY_ACTION] == id_std) { if (!actions->demand.blob) { const char *blob = mono_metadata_blob_heap (image, cols [MONO_DECL_SECURITY_PERMISSIONSET]); actions->demand.index = cols [MONO_DECL_SECURITY_PERMISSIONSET]; actions->demand.blob = (char*) (blob + 2); actions->demand.size = mono_metadata_decode_blob_size (blob, &blob); result = TRUE; } } else if (cols [MONO_DECL_SECURITY_ACTION] == id_noncas) { if (!actions->noncasdemand.blob) { const char *blob = mono_metadata_blob_heap (image, cols [MONO_DECL_SECURITY_PERMISSIONSET]); actions->noncasdemand.index = cols [MONO_DECL_SECURITY_PERMISSIONSET]; actions->noncasdemand.blob = (char*) (blob + 2); actions->noncasdemand.size = mono_metadata_decode_blob_size (blob, &blob); result = TRUE; } } else if (cols [MONO_DECL_SECURITY_ACTION] == id_choice) { if (!actions->demandchoice.blob) { const char *blob = mono_metadata_blob_heap (image, cols [MONO_DECL_SECURITY_PERMISSIONSET]); actions->demandchoice.index = cols [MONO_DECL_SECURITY_PERMISSIONSET]; actions->demandchoice.blob = (char*) (blob + 2); actions->demandchoice.size = mono_metadata_decode_blob_size (blob, &blob); result = TRUE; } } } return result; } static MonoBoolean mono_declsec_get_class_demands_params (MonoClass *klass, MonoDeclSecurityActions* demands, guint32 id_std, guint32 id_noncas, guint32 id_choice) { guint32 idx = mono_metadata_token_index (m_class_get_type_token (klass)); idx <<= MONO_HAS_DECL_SECURITY_BITS; idx |= MONO_HAS_DECL_SECURITY_TYPEDEF; return fill_actions_from_index (m_class_get_image (klass), idx, demands, id_std, id_noncas, id_choice); } static MonoBoolean mono_declsec_get_method_demands_params (MonoMethod *method, MonoDeclSecurityActions* demands, guint32 id_std, guint32 id_noncas, guint32 id_choice) { guint32 idx = mono_method_get_index (method); idx <<= MONO_HAS_DECL_SECURITY_BITS; idx |= MONO_HAS_DECL_SECURITY_METHODDEF; return fill_actions_from_index (m_class_get_image (method->klass), idx, demands, id_std, id_noncas, id_choice); } /** * mono_declsec_get_demands: * Collect all actions (that requires to generate code in mini) assigned for * the specified method. * Don't use the content of actions if the function return FALSE. */ MonoBoolean mono_declsec_get_demands (MonoMethod *method, MonoDeclSecurityActions* demands) { guint32 mask = MONO_DECLSEC_FLAG_DEMAND | MONO_DECLSEC_FLAG_NONCAS_DEMAND | MONO_DECLSEC_FLAG_DEMAND_CHOICE; MonoBoolean result = FALSE; guint32 flags; /* quick exit if no declarative security is present in the metadata */ if (!table_info_get_rows (&m_class_get_image (method->klass)->tables [MONO_TABLE_DECLSECURITY])) return FALSE; /* we want the original as the wrapper is "free" of the security informations */ if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE || method->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) { method = mono_marshal_method_from_wrapper (method); if (!method) return FALSE; } /* First we look for method-level attributes */ if (method->flags & METHOD_ATTRIBUTE_HAS_SECURITY) { mono_class_init_internal (method->klass); memset (demands, 0, sizeof (MonoDeclSecurityActions)); result = mono_declsec_get_method_demands_params (method, demands, SECURITY_ACTION_DEMAND, SECURITY_ACTION_NONCASDEMAND, SECURITY_ACTION_DEMANDCHOICE); } /* Here we use (or create) the class declarative cache to look for demands */ flags = mono_declsec_flags_from_class (method->klass); if (flags & mask) { if (!result) { mono_class_init_internal (method->klass); memset (demands, 0, sizeof (MonoDeclSecurityActions)); } result |= mono_declsec_get_class_demands_params (method->klass, demands, SECURITY_ACTION_DEMAND, SECURITY_ACTION_NONCASDEMAND, SECURITY_ACTION_DEMANDCHOICE); } /* The boolean return value is used as a shortcut in case nothing needs to be generated (e.g. LinkDemand[Choice] and InheritanceDemand[Choice]) */ return result; } /** * mono_declsec_get_linkdemands: * Collect all Link actions: \c LinkDemand, \c NonCasLinkDemand and \c LinkDemandChoice (2.0). * Don't use the content of actions if the function return FALSE. */ MonoBoolean mono_declsec_get_linkdemands (MonoMethod *method, MonoDeclSecurityActions* klass, MonoDeclSecurityActions *cmethod) { MonoBoolean result = FALSE; guint32 flags; /* quick exit if no declarative security is present in the metadata */ if (!table_info_get_rows (&m_class_get_image (method->klass)->tables [MONO_TABLE_DECLSECURITY])) return FALSE; /* we want the original as the wrapper is "free" of the security informations */ if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE || method->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) { method = mono_marshal_method_from_wrapper (method); if (!method) return FALSE; } /* results are independant - zeroize both */ memset (cmethod, 0, sizeof (MonoDeclSecurityActions)); memset (klass, 0, sizeof (MonoDeclSecurityActions)); /* First we look for method-level attributes */ if (method->flags & METHOD_ATTRIBUTE_HAS_SECURITY) { mono_class_init_internal (method->klass); result = mono_declsec_get_method_demands_params (method, cmethod, SECURITY_ACTION_LINKDEMAND, SECURITY_ACTION_NONCASLINKDEMAND, SECURITY_ACTION_LINKDEMANDCHOICE); } /* Here we use (or create) the class declarative cache to look for demands */ flags = mono_declsec_flags_from_class (method->klass); if (flags & (MONO_DECLSEC_FLAG_LINKDEMAND | MONO_DECLSEC_FLAG_NONCAS_LINKDEMAND | MONO_DECLSEC_FLAG_LINKDEMAND_CHOICE)) { mono_class_init_internal (method->klass); result |= mono_declsec_get_class_demands_params (method->klass, klass, SECURITY_ACTION_LINKDEMAND, SECURITY_ACTION_NONCASLINKDEMAND, SECURITY_ACTION_LINKDEMANDCHOICE); } return result; } /** * mono_declsec_get_inheritdemands_class: * \param klass The inherited class - this is the class that provides the security check (attributes) * \param demands * Collect all Inherit actions - \c InheritanceDemand, \c NonCasInheritanceDemand and \c InheritanceDemandChoice (2.0). * Don't use the content of actions if the function return FALSE. * \returns TRUE if inheritance demands (any kind) are present, FALSE otherwise. */ MonoBoolean mono_declsec_get_inheritdemands_class (MonoClass *klass, MonoDeclSecurityActions* demands) { MonoBoolean result = FALSE; guint32 flags; /* quick exit if no declarative security is present in the metadata */ if (!table_info_get_rows (&m_class_get_image (klass)->tables [MONO_TABLE_DECLSECURITY])) return FALSE; /* Here we use (or create) the class declarative cache to look for demands */ flags = mono_declsec_flags_from_class (klass); if (flags & (MONO_DECLSEC_FLAG_INHERITANCEDEMAND | MONO_DECLSEC_FLAG_NONCAS_INHERITANCEDEMAND | MONO_DECLSEC_FLAG_INHERITANCEDEMAND_CHOICE)) { mono_class_init_internal (klass); memset (demands, 0, sizeof (MonoDeclSecurityActions)); result |= mono_declsec_get_class_demands_params (klass, demands, SECURITY_ACTION_INHERITDEMAND, SECURITY_ACTION_NONCASINHERITANCE, SECURITY_ACTION_INHERITDEMANDCHOICE); } return result; } /** * mono_declsec_get_inheritdemands_method: * Collect all Inherit actions: \c InheritanceDemand, \c NonCasInheritanceDemand and \c InheritanceDemandChoice (2.0). * Don't use the content of actions if the function return FALSE. */ MonoBoolean mono_declsec_get_inheritdemands_method (MonoMethod *method, MonoDeclSecurityActions* demands) { /* quick exit if no declarative security is present in the metadata */ if (!table_info_get_rows (&m_class_get_image (method->klass)->tables [MONO_TABLE_DECLSECURITY])) return FALSE; /* we want the original as the wrapper is "free" of the security informations */ if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE || method->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) { method = mono_marshal_method_from_wrapper (method); if (!method) return FALSE; } if (method->flags & METHOD_ATTRIBUTE_HAS_SECURITY) { mono_class_init_internal (method->klass); memset (demands, 0, sizeof (MonoDeclSecurityActions)); return mono_declsec_get_method_demands_params (method, demands, SECURITY_ACTION_INHERITDEMAND, SECURITY_ACTION_NONCASINHERITANCE, SECURITY_ACTION_INHERITDEMANDCHOICE); } return FALSE; } static MonoBoolean get_declsec_action (MonoImage *image, guint32 token, guint32 action, MonoDeclSecurityEntry *entry) { guint32 cols [MONO_DECL_SECURITY_SIZE]; int i; int index = mono_metadata_declsec_from_index (image, token); if (index == -1) return FALSE; MonoTableInfo *t = &image->tables [MONO_TABLE_DECLSECURITY]; int rows = table_info_get_rows (t); for (i = index; i < rows; i++) { mono_metadata_decode_row (t, i, cols, MONO_DECL_SECURITY_SIZE); /* shortcut - index are ordered */ if (token != cols [MONO_DECL_SECURITY_PARENT]) return FALSE; if (cols [MONO_DECL_SECURITY_ACTION] == action) { const char *metadata = mono_metadata_blob_heap (image, cols [MONO_DECL_SECURITY_PERMISSIONSET]); entry->blob = (char*) (metadata + 2); entry->size = mono_metadata_decode_blob_size (metadata, &metadata); return TRUE; } } return FALSE; } MonoBoolean mono_declsec_get_method_action (MonoMethod *method, guint32 action, MonoDeclSecurityEntry *entry) { if (method->flags & METHOD_ATTRIBUTE_HAS_SECURITY) { guint32 idx = mono_method_get_index (method); idx <<= MONO_HAS_DECL_SECURITY_BITS; idx |= MONO_HAS_DECL_SECURITY_METHODDEF; return get_declsec_action (m_class_get_image (method->klass), idx, action, entry); } return FALSE; } /** * mono_declsec_get_class_action: */ MonoBoolean mono_declsec_get_class_action (MonoClass *klass, guint32 action, MonoDeclSecurityEntry *entry) { /* use cache */ guint32 flags = mono_declsec_flags_from_class (klass); if (declsec_flags_map [action] & flags) { guint32 idx = mono_metadata_token_index (m_class_get_type_token (klass)); idx <<= MONO_HAS_DECL_SECURITY_BITS; idx |= MONO_HAS_DECL_SECURITY_TYPEDEF; return get_declsec_action (m_class_get_image (klass), idx, action, entry); } return FALSE; } /** * mono_declsec_get_assembly_action: */ MonoBoolean mono_declsec_get_assembly_action (MonoAssembly *assembly, guint32 action, MonoDeclSecurityEntry *entry) { guint32 idx = 1; /* there is only one assembly */ idx <<= MONO_HAS_DECL_SECURITY_BITS; idx |= MONO_HAS_DECL_SECURITY_ASSEMBLY; return get_declsec_action (assembly->image, idx, action, entry); } gboolean mono_reflection_call_is_assignable_to (MonoClass *klass, MonoClass *oklass, MonoError *error) { MonoObject *res, *exc; void *params [1]; static MonoMethod *method = NULL; error_init (error); if (method == NULL) { method = mono_class_get_method_from_name_checked (mono_class_get_type_builder_class (), "IsAssignableToInternal", 1, 0, error); mono_error_assert_ok (error); g_assert (method); } /* * The result of mono_type_get_object_checked () might be a System.MonoType but we * need a TypeBuilder so use mono_class_get_ref_info (klass). */ g_assert (mono_class_has_ref_info (klass)); g_assert (!strcmp (m_class_get_name (mono_object_class (&mono_class_get_ref_info_raw (klass)->type.object)), "TypeBuilder")); /* FIXME use handles */ params [0] = mono_type_get_object_checked (m_class_get_byval_arg (oklass), error); return_val_if_nok (error, FALSE); ERROR_DECL (inner_error); res = mono_runtime_try_invoke (method, &mono_class_get_ref_info_raw (klass)->type.object, params, &exc, inner_error); /* FIXME use handles */ if (exc || !is_ok (inner_error)) { mono_error_cleanup (inner_error); return FALSE; } else return *(MonoBoolean*)mono_object_unbox_internal (res); } /** * mono_reflection_type_get_type: * \param reftype the \c System.Type object * \returns the \c MonoType* associated with the C# \c System.Type object \p reftype. */ MonoType* mono_reflection_type_get_type (MonoReflectionType *reftype) { MonoType *result; MONO_ENTER_GC_UNSAFE; g_assert (reftype); ERROR_DECL (error); result = mono_reflection_type_get_handle (reftype, error); mono_error_assert_ok (error); MONO_EXIT_GC_UNSAFE; return result; } /** * mono_reflection_assembly_get_assembly: * \param refassembly the \c System.Reflection.Assembly object * \returns the \c MonoAssembly* associated with the C# \c System.Reflection.Assembly object \p refassembly. */ MonoAssembly* mono_reflection_assembly_get_assembly (MonoReflectionAssembly *refassembly) { g_assert (refassembly); return refassembly->assembly; } /** * mono_class_from_mono_type_handle: * \param reftype the \c System.Type handle * \returns the \c MonoClass* corresponding to the given type. */ MonoClass* mono_class_from_mono_type_handle (MonoReflectionTypeHandle reftype) { return mono_class_from_mono_type_internal (MONO_HANDLE_RAW (reftype)->type); } // This is called by icalls, it will return NULL and set pending exception (in wrapper) on failure. MonoReflectionTypeHandle mono_type_from_handle_impl (MonoType *handle, MonoError *error) { mono_class_init_internal (mono_class_from_mono_type_internal (handle)); return mono_type_get_object_handle (handle, error); }
/** * \file * System.Type icalls and related reflection queries. * * Author: * Paolo Molaro ([email protected]) * * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com) * Copyright 2004-2009 Novell, Inc (http://www.novell.com) * Copyright 2011 Rodrigo Kumpera * Copyright 2016 Microsoft * * Licensed under the MIT license. See LICENSE file in the project root for full license information. */ #include <config.h> #include "mono/utils/mono-membar.h" #include "mono/metadata/assembly-internals.h" #include "mono/metadata/reflection-internals.h" #include "mono/metadata/tabledefs.h" #include "mono/metadata/metadata-internals.h" #include <mono/metadata/profiler-private.h> #include "mono/metadata/class-internals.h" #include "mono/metadata/class-init.h" #include "mono/metadata/gc-internals.h" #include "mono/metadata/domain-internals.h" #include "mono/metadata/opcodes.h" #include "mono/metadata/assembly.h" #include "mono/metadata/object-internals.h" #include <mono/metadata/exception.h> #include <mono/metadata/tokentype.h> #include <mono/metadata/marshal.h> #include <mono/metadata/reflection-cache.h> #include <mono/metadata/sre-internals.h> #include <stdio.h> #include <glib.h> #include <errno.h> #include <time.h> #include <string.h> #include <ctype.h> #include <mono/metadata/image.h> #include "cil-coff.h" #include "mono-endian.h" #include <mono/metadata/gc-internals.h> #include <mono/metadata/mempool-internals.h> #include <mono/metadata/debug-helpers.h> #include <mono/metadata/verify-internals.h> #include <mono/metadata/mono-ptr-array.h> #include <mono/metadata/mono-hash-internals.h> #include <mono/utils/mono-string.h> #include <mono/utils/mono-error-internals.h> #include <mono/utils/checked-build.h> #include <mono/utils/mono-counters.h> #include "icall-decl.h" static void get_default_param_value_blobs (MonoMethod *method, char **blobs, guint32 *types); static MonoType* mono_reflection_get_type_with_rootimage (MonoAssemblyLoadContext *alc, MonoImage *rootimage, MonoImage* image, MonoTypeNameParse *info, gboolean ignorecase, gboolean search_mscorlib, gboolean *type_resolve, MonoError *error); /* Class lazy loading functions */ static GENERATE_GET_CLASS_WITH_CACHE (mono_assembly, "System.Reflection", "RuntimeAssembly") static GENERATE_GET_CLASS_WITH_CACHE (mono_module, "System.Reflection", "RuntimeModule") static GENERATE_GET_CLASS_WITH_CACHE (mono_method, "System.Reflection", "RuntimeMethodInfo"); static GENERATE_GET_CLASS_WITH_CACHE (mono_cmethod, "System.Reflection", "RuntimeConstructorInfo"); static GENERATE_GET_CLASS_WITH_CACHE (mono_field, "System.Reflection", "RuntimeFieldInfo"); static GENERATE_GET_CLASS_WITH_CACHE (mono_event, "System.Reflection", "RuntimeEventInfo"); static GENERATE_GET_CLASS_WITH_CACHE (mono_property, "System.Reflection", "RuntimePropertyInfo"); static GENERATE_GET_CLASS_WITH_CACHE (mono_parameter_info, "System.Reflection", "RuntimeParameterInfo"); static GENERATE_GET_CLASS_WITH_CACHE (missing, "System.Reflection", "Missing"); static GENERATE_GET_CLASS_WITH_CACHE (method_body, "System.Reflection", "RuntimeMethodBody"); static GENERATE_GET_CLASS_WITH_CACHE (local_variable_info, "System.Reflection", "RuntimeLocalVariableInfo"); static GENERATE_GET_CLASS_WITH_CACHE (exception_handling_clause, "System.Reflection", "RuntimeExceptionHandlingClause"); static GENERATE_GET_CLASS_WITH_CACHE (type_builder, "System.Reflection.Emit", "TypeBuilder"); static GENERATE_GET_CLASS_WITH_CACHE (dbnull, "System", "DBNull"); static int class_ref_info_handle_count; void mono_reflection_init (void) { mono_reflection_emit_init (); mono_counters_register ("MonoClass::ref_info_handle count", MONO_COUNTER_METADATA | MONO_COUNTER_INT, &class_ref_info_handle_count); } /* * mono_class_get_ref_info: * * Return the type builder corresponding to KLASS, if it exists. */ MonoReflectionTypeBuilderHandle mono_class_get_ref_info (MonoClass *klass) { MONO_REQ_GC_UNSAFE_MODE; MonoGCHandle ref_info_handle = mono_class_get_ref_info_handle (klass); if (ref_info_handle == 0) return MONO_HANDLE_NEW (MonoReflectionTypeBuilder, NULL); return MONO_HANDLE_CAST (MonoReflectionTypeBuilder, mono_gchandle_get_target_handle (ref_info_handle)); } gboolean mono_class_has_ref_info (MonoClass *klass) { MONO_REQ_GC_UNSAFE_MODE; return 0 != mono_class_get_ref_info_handle (klass); } MonoReflectionTypeBuilder* mono_class_get_ref_info_raw (MonoClass *klass) { /* FIXME callers of mono_class_get_ref_info_raw should use handles */ MONO_REQ_GC_UNSAFE_MODE; MonoGCHandle ref_info_handle = mono_class_get_ref_info_handle (klass); if (ref_info_handle == 0) return NULL; return (MonoReflectionTypeBuilder*)mono_gchandle_get_target_internal (ref_info_handle); } void mono_class_set_ref_info (MonoClass *klass, MonoObjectHandle obj) { MONO_REQ_GC_UNSAFE_MODE; MonoGCHandle candidate = mono_gchandle_from_handle (obj, FALSE); MonoGCHandle handle = mono_class_set_ref_info_handle (klass, candidate); ++class_ref_info_handle_count; if (handle != candidate) mono_gchandle_free_internal (candidate); } void mono_class_free_ref_info (MonoClass *klass) { MONO_REQ_GC_NEUTRAL_MODE; MonoGCHandle handle = mono_class_get_ref_info_handle (klass); if (handle) { mono_gchandle_free_internal (handle); mono_class_set_ref_info_handle (klass, 0); } } /** * mono_custom_attrs_free: */ void mono_custom_attrs_free (MonoCustomAttrInfo *ainfo) { MONO_REQ_GC_NEUTRAL_MODE; if (ainfo && !ainfo->cached) g_free (ainfo); } gboolean mono_reflected_equal (gconstpointer a, gconstpointer b) { const ReflectedEntry *ea = (const ReflectedEntry *)a; const ReflectedEntry *eb = (const ReflectedEntry *)b; return (ea->item == eb->item) && (ea->refclass == eb->refclass); } guint mono_reflected_hash (gconstpointer a) { const ReflectedEntry *ea = (const ReflectedEntry *)a; /* Combine hashes for item and refclass. Identical to boost's hash_combine */ guint seed = mono_aligned_addr_hash (ea->item) + 0x9e3779b9; seed ^= mono_aligned_addr_hash (ea->refclass) + 0x9e3779b9 + (seed << 6) + (seed >> 2); return seed; } static void clear_cached_object (MonoMemoryManager *mem_manager, gpointer o, MonoClass *klass) { gpointer orig_pe, orig_value; ReflectedEntry pe; pe.item = o; pe.refclass = klass; mono_mem_manager_lock (mem_manager); if (mono_conc_g_hash_table_lookup_extended (mem_manager->refobject_hash, &pe, &orig_pe, &orig_value)) { mono_conc_g_hash_table_remove (mem_manager->refobject_hash, &pe); free_reflected_entry ((ReflectedEntry *)orig_pe); } mono_mem_manager_unlock (mem_manager); } /** * mono_assembly_get_object: * \param domain an app domain * \param assembly an assembly * \returns a \c System.Reflection.Assembly object representing the \c MonoAssembly \p assembly. */ MonoReflectionAssembly* mono_assembly_get_object (MonoDomain *domain, MonoAssembly *assembly) { HANDLE_FUNCTION_ENTER (); MonoReflectionAssemblyHandle result; MONO_ENTER_GC_UNSAFE; ERROR_DECL (error); result = mono_assembly_get_object_handle (assembly, error); mono_error_cleanup (error); /* FIXME new API that doesn't swallow the error */ MONO_EXIT_GC_UNSAFE; HANDLE_FUNCTION_RETURN_OBJ (result); } static MonoReflectionAssemblyHandle assembly_object_construct (MonoClass *unused_klass, MonoAssembly *assembly, gpointer user_data, MonoError *error) { error_init (error); MonoReflectionAssemblyHandle res = MONO_HANDLE_CAST (MonoReflectionAssembly, mono_object_new_handle (mono_class_get_mono_assembly_class (), error)); return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionAssembly, NULL_HANDLE)); MONO_HANDLE_SETVAL (res, assembly, MonoAssembly*, assembly); return res; } /* * mono_assembly_get_object_handle: * @assembly: an assembly * * Return an System.Reflection.Assembly object representing the MonoAssembly @assembly. */ MonoReflectionAssemblyHandle mono_assembly_get_object_handle (MonoAssembly *assembly, MonoError *error) { error_init (error); return CHECK_OR_CONSTRUCT_HANDLE (MonoReflectionAssembly, m_image_get_mem_manager (assembly->image), assembly, NULL, assembly_object_construct, NULL); } /** * mono_module_get_object: */ MonoReflectionModule* mono_module_get_object (MonoDomain *domain, MonoImage *image) { MonoReflectionModuleHandle result; HANDLE_FUNCTION_ENTER (); MONO_ENTER_GC_UNSAFE; ERROR_DECL (error); result = mono_module_get_object_handle (image, error); mono_error_cleanup (error); MONO_EXIT_GC_UNSAFE; HANDLE_FUNCTION_RETURN_OBJ (result); } static MonoReflectionModuleHandle module_object_construct (MonoClass *unused_klass, MonoImage *image, gpointer user_data, MonoError *error) { char* basename; error_init (error); MonoReflectionModuleHandle res = MONO_HANDLE_CAST (MonoReflectionModule, mono_object_new_handle (mono_class_get_mono_module_class (), error)); goto_if_nok (error, fail); MONO_HANDLE_SETVAL (res, image, MonoImage *, image); MonoReflectionAssemblyHandle assm_obj; assm_obj = mono_assembly_get_object_handle (image->assembly, error); goto_if_nok (error, fail); MONO_HANDLE_SET (res, assembly, assm_obj); MONO_HANDLE_SET (res, fqname, mono_string_new_handle (image->name, error)); goto_if_nok (error, fail); basename = g_path_get_basename (image->name); MONO_HANDLE_SET (res, name, mono_string_new_handle (basename, error)); goto_if_nok (error, fail); MONO_HANDLE_SET (res, scopename, mono_string_new_handle (image->module_name, error)); goto_if_nok (error, fail); g_free (basename); guint32 token; token = 0; if (image->assembly->image == image) { token = mono_metadata_make_token (MONO_TABLE_MODULE, 1); } else { int i; if (image->assembly->image->modules) { for (i = 0; i < image->assembly->image->module_count; i++) { if (image->assembly->image->modules [i] == image) token = mono_metadata_make_token (MONO_TABLE_MODULEREF, i + 1); } g_assert (token != 0); } } MONO_HANDLE_SETVAL (res, token, guint32, token); return res; fail: return MONO_HANDLE_CAST (MonoReflectionModule, NULL_HANDLE); } MonoReflectionModuleHandle mono_module_get_object_handle (MonoImage *image, MonoError *error) { error_init (error); return CHECK_OR_CONSTRUCT_HANDLE (MonoReflectionModule, m_image_get_mem_manager (image), image, NULL, module_object_construct, NULL); } /** * mono_module_file_get_object: */ MonoReflectionModule* mono_module_file_get_object (MonoDomain *domain, MonoImage *image, int table_index) { MonoReflectionModuleHandle result; HANDLE_FUNCTION_ENTER (); MONO_ENTER_GC_UNSAFE; ERROR_DECL (error); result = mono_module_file_get_object_handle (image, table_index, error); mono_error_cleanup (error); MONO_EXIT_GC_UNSAFE; HANDLE_FUNCTION_RETURN_OBJ (result); } MonoReflectionModuleHandle mono_module_file_get_object_handle (MonoImage *image, int table_index, MonoError *error) { MonoTableInfo *table; guint32 cols [MONO_FILE_SIZE]; const char *name; guint32 i, name_idx; const char *val; error_init (error); MonoReflectionModuleHandle res = MONO_HANDLE_CAST (MonoReflectionModule, mono_object_new_handle (mono_class_get_mono_module_class (), error)); goto_if_nok (error, fail); table = &image->tables [MONO_TABLE_FILE]; g_assert (table_index < table_info_get_rows (table)); mono_metadata_decode_row (table, table_index, cols, MONO_FILE_SIZE); MONO_HANDLE_SETVAL (res, image, MonoImage*, NULL); MonoReflectionAssemblyHandle assm_obj; assm_obj = mono_assembly_get_object_handle (image->assembly, error); goto_if_nok (error, fail); MONO_HANDLE_SET (res, assembly, assm_obj); name = mono_metadata_string_heap (image, cols [MONO_FILE_NAME]); /* Check whenever the row has a corresponding row in the moduleref table */ table = &image->tables [MONO_TABLE_MODULEREF]; int rows = table_info_get_rows (table); for (i = 0; i < rows; ++i) { name_idx = mono_metadata_decode_row_col (table, i, MONO_MODULEREF_NAME); val = mono_metadata_string_heap (image, name_idx); if (strcmp (val, name) == 0) MONO_HANDLE_SETVAL (res, image, MonoImage*, image->modules [i]); } MONO_HANDLE_SET (res, fqname, mono_string_new_handle (name, error)); goto_if_nok (error, fail); MONO_HANDLE_SET (res, name, mono_string_new_handle (name, error)); goto_if_nok (error, fail); MONO_HANDLE_SET (res, scopename, mono_string_new_handle (name, error)); goto_if_nok (error, fail); MONO_HANDLE_SETVAL (res, is_resource, MonoBoolean, cols [MONO_FILE_FLAGS] & FILE_CONTAINS_NO_METADATA); MONO_HANDLE_SETVAL (res, token, guint32, mono_metadata_make_token (MONO_TABLE_FILE, table_index + 1)); return res; fail: return MONO_HANDLE_CAST (MonoReflectionModule, NULL_HANDLE); } static MonoType* mono_type_normalize (MonoType *type) { int i; MonoGenericClass *gclass; MonoGenericInst *ginst; MonoClass *gtd; MonoGenericContainer *gcontainer; MonoType **argv = NULL; gboolean is_denorm_gtd = TRUE, requires_rebind = FALSE; if (type->type != MONO_TYPE_GENERICINST) return type; gclass = type->data.generic_class; ginst = gclass->context.class_inst; if (!ginst->is_open) return type; gtd = gclass->container_class; gcontainer = mono_class_get_generic_container (gtd); argv = g_newa (MonoType*, ginst->type_argc); for (i = 0; i < ginst->type_argc; ++i) { MonoType *t = ginst->type_argv [i], *norm; if (t->type != MONO_TYPE_VAR || t->data.generic_param->num != i || t->data.generic_param->owner != gcontainer) is_denorm_gtd = FALSE; norm = mono_type_normalize (t); argv [i] = norm; if (norm != t) requires_rebind = TRUE; } if (is_denorm_gtd) return m_type_is_byref (type) == m_type_is_byref (m_class_get_byval_arg (gtd)) ? m_class_get_byval_arg (gtd) : m_class_get_this_arg (gtd); if (requires_rebind) { MonoClass *klass = mono_class_bind_generic_parameters (gtd, ginst->type_argc, argv, gclass->is_dynamic); return m_type_is_byref (type) == m_type_is_byref (m_class_get_byval_arg (klass)) ? m_class_get_byval_arg (klass) : m_class_get_this_arg (klass); } return type; } /** * mono_type_get_object: * \param domain an app domain * \param type a type * \returns A \c System.MonoType object representing the type \p type. */ MonoReflectionType* mono_type_get_object (MonoDomain *domain, MonoType *type) { MonoReflectionType *ret; MONO_ENTER_GC_UNSAFE; ERROR_DECL (error); ret = mono_type_get_object_checked (type, error); mono_error_cleanup (error); MONO_EXIT_GC_UNSAFE; return ret; } MonoReflectionType* mono_type_get_object_checked (MonoType *type, MonoError *error) { MonoType *norm_type; MonoReflectionType *res, *cached; MonoClass *klass; MonoDomain *domain = mono_get_root_domain (); error_init (error); g_assert (type != NULL); klass = mono_class_from_mono_type_internal (type); MonoMemoryManager *memory_manager = m_class_get_mem_manager (klass); /*we must avoid using @type as it might have come * from a mono_metadata_type_dup and the caller * expects that is can be freed. * Using the right type from */ type = m_type_is_byref (m_class_get_byval_arg (klass)) == m_type_is_byref (type) ? m_class_get_byval_arg (klass) : m_class_get_this_arg (klass); /* We don't want to return types with custom modifiers to the managed * world since they're hard to distinguish from plain types using the * reflection APIs, but they are not ReferenceEqual to the unadorned * types. * * If we ever see cmods here, it's a bug: MonoClass:byval_arg and * MonoClass:this_arg shouldn't have cmods by construction. */ g_assert (!type->has_cmods); /* void is very common */ if (!m_type_is_byref (type) && type->type == MONO_TYPE_VOID && domain->typeof_void) return (MonoReflectionType*)domain->typeof_void; /* * If the vtable of the given class was already created, we can use * the MonoType from there and avoid all locking and hash table lookups. * * We cannot do this for TypeBuilders as mono_reflection_create_runtime_class expects * that the resulting object is different. */ if (type == m_class_get_byval_arg (klass) && !image_is_dynamic (m_class_get_image (klass))) { MonoVTable *vtable = mono_class_try_get_vtable (klass); if (vtable && vtable->type) return (MonoReflectionType *)vtable->type; } mono_loader_lock (); /*FIXME mono_class_init_internal and mono_class_vtable acquire it*/ mono_mem_manager_lock (memory_manager); res = (MonoReflectionType *)mono_g_hash_table_lookup (memory_manager->type_hash, type); mono_mem_manager_unlock (memory_manager); if (res) goto leave; /*Types must be normalized so a generic instance of the GTD get's the same inner type. * For example in: Foo<A,B>; Bar<A> : Foo<A, Bar<A>> * The second Bar will be encoded a generic instance of Bar with <A> as parameter. * On all other places, Bar<A> will be encoded as the GTD itself. This is an implementation * artifact of how generics are encoded and should be transparent to managed code so we * need to weed out this diference when retrieving managed System.Type objects. */ norm_type = mono_type_normalize (type); if (norm_type != type) { res = mono_type_get_object_checked (norm_type, error); goto_if_nok (error, leave); mono_mem_manager_lock (memory_manager); cached = (MonoReflectionType *)mono_g_hash_table_lookup (memory_manager->type_hash, type); if (cached) { res = cached; } else { mono_g_hash_table_insert_internal (memory_manager->type_hash, type, res); } mono_mem_manager_unlock (memory_manager); goto leave; } if ((type->type == MONO_TYPE_GENERICINST) && type->data.generic_class->is_dynamic && !m_class_was_typebuilder (type->data.generic_class->container_class)) { /* This can happen if a TypeBuilder for a generic class K<T,U> * had reflection_create_generic_class) called on it, but not * ves_icall_TypeBuilder_create_runtime_class. This can happen * if the K`2 is refernced from a generic instantiation * (e.g. K<int,string>) that appears as type argument * (e.g. Dict<string,K<int,string>>), field (e.g. K<int,string> * Foo) or method signature, parent class or any of the above * in a nested class of some other TypeBuilder. Such an * occurrence caused mono_reflection_type_get_handle to be * called on the sre generic instance (K<int,string>) which * required the container_class for the generic class K`2 to be * set up, but the remainder of class construction for K`2 has * not been done. */ char * full_name = mono_type_get_full_name (klass); /* I would have expected ReflectionTypeLoadException, but evidently .NET throws TLE in this case. */ mono_error_set_type_load_class (error, klass, "TypeBuilder.CreateType() not called for generic class %s", full_name); g_free (full_name); res = NULL; goto leave; } if (mono_class_has_ref_info (klass) && !m_class_was_typebuilder (klass) && !m_type_is_byref (type)) { res = &mono_class_get_ref_info_raw (klass)->type; /* FIXME use handles */ goto leave; } /* This is stored in vtables/JITted code so it has to be pinned */ res = (MonoReflectionType *)mono_object_new_pinned (mono_defaults.runtimetype_class, error); goto_if_nok (error, leave); res->type = type; mono_mem_manager_lock (memory_manager); cached = (MonoReflectionType *)mono_g_hash_table_lookup (memory_manager->type_hash, type); if (cached) { res = cached; } else { mono_g_hash_table_insert_internal (memory_manager->type_hash, type, res); if (type->type == MONO_TYPE_VOID && !m_type_is_byref (type)) domain->typeof_void = (MonoObject*)res; } mono_mem_manager_unlock (memory_manager); leave: mono_loader_unlock (); return res; } MonoReflectionTypeHandle mono_type_get_object_handle (MonoType *type, MonoError *error) { /* NOTE: We happen to know that mono_type_get_object_checked returns * pinned objects, so we can just wrap its return value in a handle for * uniformity. If it ever starts returning unpinned, objects, this * implementation would need to change! */ return MONO_HANDLE_NEW (MonoReflectionType, mono_type_get_object_checked (type, error)); } /** * mono_method_get_object: * \param domain an app domain * \param method a method * \param refclass the reflected type (can be NULL) * \returns A \c System.Reflection.MonoMethod object representing the method \p method. */ MonoReflectionMethod* mono_method_get_object (MonoDomain *domain, MonoMethod *method, MonoClass *refclass) { HANDLE_FUNCTION_ENTER (); MonoReflectionMethodHandle ret; MONO_ENTER_GC_UNSAFE; ERROR_DECL (error); ret = mono_method_get_object_handle (method, refclass, error); mono_error_cleanup (error); MONO_EXIT_GC_UNSAFE; HANDLE_FUNCTION_RETURN_OBJ (ret); } static MonoReflectionMethodHandle method_object_construct (MonoClass *refclass, MonoMethod *method, gpointer user_data, MonoError *error) { error_init (error); g_assert (refclass != NULL); /* * We use the same C representation for methods and constructors, but the type * name in C# is different. */ MonoClass *klass; error_init (error); if (*method->name == '.' && (strcmp (method->name, ".ctor") == 0 || strcmp (method->name, ".cctor") == 0)) { klass = mono_class_get_mono_cmethod_class (); } else { klass = mono_class_get_mono_method_class (); } MonoReflectionMethodHandle ret = MONO_HANDLE_CAST (MonoReflectionMethod, mono_object_new_handle (klass, error)); goto_if_nok (error, fail); MONO_HANDLE_SETVAL (ret, method, MonoMethod*, method); MonoReflectionTypeHandle rt; rt = mono_type_get_object_handle (m_class_get_byval_arg (refclass), error); goto_if_nok (error, fail); MONO_HANDLE_SET (ret, reftype, rt); return ret; fail: return MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE); } /* * mono_method_get_object_handle: * @method: a method * @refclass: the reflected type (can be NULL) * @error: set on error. * * Return an System.Reflection.MonoMethod object representing the method @method. * Returns NULL and sets @error on error. */ MonoReflectionMethodHandle mono_method_get_object_handle (MonoMethod *method, MonoClass *refclass, MonoError *error) { error_init (error); if (!refclass) refclass = method->klass; // FIXME: For methods/params etc., use the mem manager for refclass or a merged one ? return CHECK_OR_CONSTRUCT_HANDLE (MonoReflectionMethod, m_method_get_mem_manager (method), method, refclass, method_object_construct, NULL); } /* * mono_method_get_object_checked: * @method: a method * @refclass: the reflected type (can be NULL) * @error: set on error. * * Return an System.Reflection.MonoMethod object representing the method @method. * Returns NULL and sets @error on error. */ MonoReflectionMethod* mono_method_get_object_checked (MonoMethod *method, MonoClass *refclass, MonoError *error) { HANDLE_FUNCTION_ENTER (); MonoReflectionMethodHandle result = mono_method_get_object_handle (method, refclass, error); HANDLE_FUNCTION_RETURN_OBJ (result); } /* * mono_method_clear_object: * * Clear the cached reflection objects for the dynamic method METHOD. */ void mono_method_clear_object (MonoMethod *method) { MonoClass *klass; g_assert (method_is_dynamic (method)); MonoMemoryManager *mem_manager = m_method_get_mem_manager (method); klass = method->klass; while (klass) { clear_cached_object (mem_manager, method, klass); klass = m_class_get_parent (klass); } /* Added by mono_param_get_objects () */ clear_cached_object (mem_manager, &(method->signature), NULL); klass = method->klass; while (klass) { clear_cached_object (mem_manager, &(method->signature), klass); klass = m_class_get_parent (klass); } } /** * mono_field_get_object: * \param domain an app domain * \param klass a type * \param field a field * \returns A \c System.Reflection.MonoField object representing the field \p field * in class \p klass. */ MonoReflectionField* mono_field_get_object (MonoDomain *domain, MonoClass *klass, MonoClassField *field) { MonoReflectionFieldHandle result; HANDLE_FUNCTION_ENTER (); MONO_ENTER_GC_UNSAFE; ERROR_DECL (error); result = mono_field_get_object_handle (klass, field, error); mono_error_cleanup (error); MONO_EXIT_GC_UNSAFE; HANDLE_FUNCTION_RETURN_OBJ (result); } static MonoReflectionFieldHandle field_object_construct (MonoClass *klass, MonoClassField *field, gpointer user_data, MonoError *error) { error_init (error); MonoReflectionFieldHandle res = MONO_HANDLE_CAST (MonoReflectionField, mono_object_new_handle (mono_class_get_mono_field_class (), error)); goto_if_nok (error, fail); MONO_HANDLE_SETVAL (res, klass, MonoClass *, klass); MONO_HANDLE_SETVAL (res, field, MonoClassField *, field); MonoStringHandle name; name = mono_string_new_handle (mono_field_get_name (field), error); goto_if_nok (error, fail); MONO_HANDLE_SET (res, name, name); if (field->type) { MonoReflectionTypeHandle rt = mono_type_get_object_handle (field->type, error); goto_if_nok (error, fail); MONO_HANDLE_SET (res, type, rt); } MONO_HANDLE_SETVAL (res, attrs, guint32, mono_field_get_flags (field)); return res; fail: return MONO_HANDLE_CAST (MonoReflectionField, NULL_HANDLE); } /* * mono_field_get_object_handle: * @klass: a type * @field: a field * @error: set on error * * Return an System.Reflection.MonoField object representing the field @field * in class @klass. On error, returns NULL and sets @error. */ MonoReflectionFieldHandle mono_field_get_object_handle (MonoClass *klass, MonoClassField *field, MonoError *error) { error_init (error); return CHECK_OR_CONSTRUCT_HANDLE (MonoReflectionField, m_class_get_mem_manager (m_field_get_parent (field)), field, klass, field_object_construct, NULL); } /* * mono_field_get_object_checked: * @klass: a type * @field: a field * @error: set on error * * Return an System.Reflection.MonoField object representing the field @field * in class @klass. On error, returns NULL and sets @error. */ MonoReflectionField* mono_field_get_object_checked (MonoClass *klass, MonoClassField *field, MonoError *error) { HANDLE_FUNCTION_ENTER (); MonoReflectionFieldHandle result = mono_field_get_object_handle (klass, field, error); HANDLE_FUNCTION_RETURN_OBJ (result); } /* * mono_property_get_object: * @domain: an app domain * @klass: a type * @property: a property * * Return an System.Reflection.MonoProperty object representing the property @property * in class @klass. */ MonoReflectionProperty* mono_property_get_object (MonoDomain *domain, MonoClass *klass, MonoProperty *property) { MonoReflectionPropertyHandle result; HANDLE_FUNCTION_ENTER (); MONO_ENTER_GC_UNSAFE; ERROR_DECL (error); result = mono_property_get_object_handle (klass, property, error); mono_error_cleanup (error); MONO_EXIT_GC_UNSAFE; HANDLE_FUNCTION_RETURN_OBJ (result); } static MonoReflectionPropertyHandle property_object_construct (MonoClass *klass, MonoProperty *property, gpointer user_data, MonoError *error) { error_init (error); MonoReflectionPropertyHandle res = MONO_HANDLE_CAST (MonoReflectionProperty, mono_object_new_handle (mono_class_get_mono_property_class (), error)); goto_if_nok (error, fail); MONO_HANDLE_SETVAL (res, klass, MonoClass *, klass); MONO_HANDLE_SETVAL (res, property, MonoProperty *, property); return res; fail: return MONO_HANDLE_CAST (MonoReflectionProperty, NULL_HANDLE); } /** * mono_property_get_object_handle: * \param klass a type * \param property a property * \param error set on error * * \returns A \c System.Reflection.MonoProperty object representing the property \p property * in class \p klass. On error returns NULL and sets \p error. */ MonoReflectionPropertyHandle mono_property_get_object_handle (MonoClass *klass, MonoProperty *property, MonoError *error) { return CHECK_OR_CONSTRUCT_HANDLE (MonoReflectionProperty, m_class_get_mem_manager (property->parent), property, klass, property_object_construct, NULL); } /** * mono_property_get_object: * \param domain an app domain * \param klass a type * \param property a property * \param error set on error * \returns a \c System.Reflection.MonoProperty object representing the property \p property * in class \p klass. On error returns NULL and sets \p error. */ MonoReflectionProperty* mono_property_get_object_checked (MonoClass *klass, MonoProperty *property, MonoError *error) { HANDLE_FUNCTION_ENTER (); MonoReflectionPropertyHandle res = mono_property_get_object_handle (klass, property, error); HANDLE_FUNCTION_RETURN_OBJ (res); } /** * mono_event_get_object: * \param domain an app domain * \param klass a type * \param event a event * \returns A \c System.Reflection.MonoEvent object representing the event \p event * in class \p klass. */ MonoReflectionEvent* mono_event_get_object (MonoDomain *domain, MonoClass *klass, MonoEvent *event) { MonoReflectionEventHandle result; HANDLE_FUNCTION_ENTER (); MONO_ENTER_GC_UNSAFE; ERROR_DECL (error); result = mono_event_get_object_handle (klass, event, error); mono_error_cleanup (error); MONO_EXIT_GC_UNSAFE; HANDLE_FUNCTION_RETURN_OBJ (result); } static MonoReflectionEventHandle event_object_construct (MonoClass *klass, MonoEvent *event, gpointer user_data, MonoError *error) { error_init (error); MonoReflectionMonoEventHandle mono_event = MONO_HANDLE_CAST (MonoReflectionMonoEvent, mono_object_new_handle (mono_class_get_mono_event_class (), error)); if (!is_ok (error)) return MONO_HANDLE_CAST (MonoReflectionEvent, NULL_HANDLE); MONO_HANDLE_SETVAL (mono_event, klass, MonoClass* , klass); MONO_HANDLE_SETVAL (mono_event, event, MonoEvent* , event); return MONO_HANDLE_CAST (MonoReflectionEvent, mono_event); } /** * mono_event_get_object_handle: * \param klass a type * \param event a event * \param error set on error * \returns a \c System.Reflection.MonoEvent object representing the event \p event * in class \p klass. On failure sets \p error and returns NULL */ MonoReflectionEventHandle mono_event_get_object_handle (MonoClass *klass, MonoEvent *event, MonoError *error) { error_init (error); return CHECK_OR_CONSTRUCT_HANDLE (MonoReflectionEvent, m_class_get_mem_manager (event->parent), event, klass, event_object_construct, NULL); } /** * mono_get_reflection_missing_object: * * \returns the \c System.Reflection.Missing.Value singleton object * (of type \c System.Reflection.Missing). * * Used as the value for \c ParameterInfo.DefaultValue when Optional * is present */ static MonoObjectHandle mono_get_reflection_missing_object (void) { ERROR_DECL (error); MONO_STATIC_POINTER_INIT (MonoClassField, missing_value_field) MonoClass *missing_klass = mono_class_get_missing_class (); mono_class_init_internal (missing_klass); missing_value_field = mono_class_get_field_from_name_full (missing_klass, "Value", NULL); g_assert (missing_value_field); MONO_STATIC_POINTER_INIT_END (MonoClassField, missing_value_field) /* FIXME change mono_field_get_value_object_checked to return a handle */ MonoObjectHandle obj = MONO_HANDLE_NEW (MonoObject, mono_field_get_value_object_checked (missing_value_field, NULL, error)); mono_error_assert_ok (error); return obj; } static MonoObjectHandle get_dbnull_object (MonoError *error) { error_init (error); MONO_STATIC_POINTER_INIT (MonoClassField, dbnull_value_field) MonoClass *dbnull_klass = mono_class_get_dbnull_class (); dbnull_value_field = mono_class_get_field_from_name_full (dbnull_klass, "Value", NULL); g_assert (dbnull_value_field); MONO_STATIC_POINTER_INIT_END (MonoClassField, dbnull_value_field) /* FIXME change mono_field_get_value_object_checked to return a handle */ MonoObjectHandle obj = MONO_HANDLE_NEW (MonoObject, mono_field_get_value_object_checked (dbnull_value_field, NULL, error)); return obj; } static MonoObjectHandle get_dbnull (MonoObjectHandle dbnull, MonoError *error) { error_init (error); if (MONO_HANDLE_IS_NULL (dbnull)) MONO_HANDLE_ASSIGN (dbnull, get_dbnull_object (error)); return dbnull; } static MonoObjectHandle get_reflection_missing (MonoObjectHandleOut reflection_missing) { if (MONO_HANDLE_IS_NULL (reflection_missing)) MONO_HANDLE_ASSIGN (reflection_missing, mono_get_reflection_missing_object ()); return reflection_missing; } static gboolean add_parameter_object_to_array (MonoMethod *method, MonoObjectHandle member, int idx, const char *name, MonoType *sig_param, guint32 blob_type_enum, const char *blob, MonoMarshalSpec *mspec, MonoObjectHandle missing, MonoObjectHandle dbnull, MonoArrayHandle dest, MonoError *error) { HANDLE_FUNCTION_ENTER (); error_init (error); MonoReflectionParameterHandle param = MONO_HANDLE_CAST (MonoReflectionParameter, mono_object_new_handle (mono_class_get_mono_parameter_info_class (), error)); goto_if_nok (error, leave); static MonoMethod *ctor; if (!ctor) { MonoMethod *m = mono_class_get_method_from_name_checked (mono_class_get_mono_parameter_info_class (), ".ctor", 7, 0, error); g_assert (m); mono_memory_barrier (); ctor = m; } MonoReflectionTypeHandle rt; rt = mono_type_get_object_handle (sig_param, error); goto_if_nok (error, leave); MonoStringHandle name_str; name_str = mono_string_new_handle (name, error); goto_if_nok (error, leave); MonoObjectHandle def_value; if (!(sig_param->attrs & PARAM_ATTRIBUTE_HAS_DEFAULT) || (method->wrapper_type != MONO_WRAPPER_NONE && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)) { if (sig_param->attrs & PARAM_ATTRIBUTE_OPTIONAL) def_value = get_reflection_missing (missing); else def_value = get_dbnull (dbnull, error); goto_if_nok (error, leave); } else { MonoType blob_type; blob_type.type = (MonoTypeEnum)blob_type_enum; blob_type.data.klass = NULL; if (blob_type_enum == MONO_TYPE_CLASS) blob_type.data.klass = mono_defaults.object_class; else if ((sig_param->type == MONO_TYPE_VALUETYPE) && m_class_is_enumtype (sig_param->data.klass)) { /* For enums, types [i] contains the base type */ blob_type.type = MONO_TYPE_VALUETYPE; blob_type.data.klass = mono_class_from_mono_type_internal (sig_param); } else blob_type.data.klass = mono_class_from_mono_type_internal (&blob_type); def_value = mono_get_object_from_blob (&blob_type, blob, MONO_HANDLE_NEW (MonoString, NULL), error); goto_if_nok (error, leave); /* Type in the Constant table is MONO_TYPE_CLASS for nulls */ if (blob_type_enum != MONO_TYPE_CLASS && MONO_HANDLE_IS_NULL(def_value)) { if (sig_param->attrs & PARAM_ATTRIBUTE_OPTIONAL) def_value = get_reflection_missing (missing); else def_value = get_dbnull (dbnull, error); goto_if_nok (error, leave); } } MonoReflectionMarshalAsAttributeHandle mobj; mobj = MONO_HANDLE_NEW (MonoReflectionMarshalAsAttribute, NULL); if (mspec) { mobj = mono_reflection_marshal_as_attribute_from_marshal_spec (method->klass, mspec, error); goto_if_nok (error, leave); } /* internal RuntimeParameterInfo (string name, Type type, int position, int attrs, object defaultValue, MemberInfo member, MarshalAsAttribute marshalAs) */ { int attrs = sig_param->attrs; void *args [ ] = { MONO_HANDLE_RAW (name_str), MONO_HANDLE_RAW (rt), &idx, &attrs, MONO_HANDLE_RAW (def_value), MONO_HANDLE_RAW (member), MONO_HANDLE_RAW (mobj) }; mono_runtime_invoke_handle_void (ctor, MONO_HANDLE_CAST (MonoObject, param), args, error); } goto_if_nok (error, leave); MONO_HANDLE_ARRAY_SETREF (dest, idx, param); leave: HANDLE_FUNCTION_RETURN_VAL (is_ok (error)); } static MonoArrayHandle param_objects_construct (MonoClass *refclass, MonoMethodSignature **addr_of_sig, gpointer user_data, MonoError *error) { MonoMethod *method = (MonoMethod*)user_data; MonoMethodSignature *sig = *addr_of_sig; /* see note in mono_param_get_objects_internal */ MonoArrayHandle res = MONO_HANDLE_NEW (MonoArray, NULL); char **names = NULL, **blobs = NULL; guint32 *types = NULL; MonoMarshalSpec **mspecs = NULL; int i; error_init (error); MonoReflectionMethodHandle member = mono_method_get_object_handle (method, refclass, error); goto_if_nok (error, leave); names = g_new (char *, sig->param_count); mono_method_get_param_names (method, (const char **) names); mspecs = g_new (MonoMarshalSpec*, sig->param_count + 1); mono_method_get_marshal_info (method, mspecs); res = mono_array_new_handle (mono_class_get_mono_parameter_info_class (), sig->param_count, error); if (MONO_HANDLE_IS_NULL (res)) goto leave; gboolean any_default_value; any_default_value = FALSE; if (method->wrapper_type == MONO_WRAPPER_NONE || method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD ) { for (i = 0; i < sig->param_count; ++i) { if ((sig->params [i]->attrs & PARAM_ATTRIBUTE_HAS_DEFAULT) != 0) { any_default_value = TRUE; break; } } } if (any_default_value) { blobs = g_new0 (char *, sig->param_count); types = g_new0 (guint32, sig->param_count); get_default_param_value_blobs (method, blobs, types); } /* Handles missing and dbnull are assigned in add_parameter_object_to_array when needed */ MonoObjectHandle missing; missing = MONO_HANDLE_NEW (MonoObject, NULL); MonoObjectHandle dbnull; dbnull = MONO_HANDLE_NEW (MonoObject, NULL); for (i = 0; i < sig->param_count; ++i) { if (!add_parameter_object_to_array (method, MONO_HANDLE_CAST(MonoObject, member), i, names[i], sig->params[i], types ? types[i] : 0, blobs ? blobs[i] : NULL, mspecs [i + 1], missing, dbnull, res, error)) goto leave; } leave: g_free (names); g_free (blobs); g_free (types); if (sig && mspecs) { for (i = sig->param_count; i >= 0; i--) { if (mspecs [i]) mono_metadata_free_marshal_spec (mspecs [i]); } } g_free (mspecs); if (!is_ok (error)) return NULL_HANDLE_ARRAY; return res; } /* * mono_param_get_objects: * @method: a method * * Return an System.Reflection.ParameterInfo array object representing the parameters * in the method @method. */ MonoArrayHandle mono_param_get_objects_internal (MonoMethod *method, MonoClass *refclass, MonoError *error) { error_init (error); /* side-effect: sets method->signature non-NULL on success */ MonoMethodSignature *sig = mono_method_signature_checked (method, error); goto_if_nok (error, fail); if (!sig->param_count) { MonoArrayHandle res = mono_array_new_handle (mono_class_get_mono_parameter_info_class (), 0, error); goto_if_nok (error, fail); return res; } /* Note: the cache is based on the address of the signature into the method * since we already cache MethodInfos with the method as keys. */ return CHECK_OR_CONSTRUCT_HANDLE (MonoArray, m_method_get_mem_manager (method), &method->signature, refclass, param_objects_construct, method); fail: return MONO_HANDLE_NEW (MonoArray, NULL); } /** * mono_param_get_objects: */ MonoArray* mono_param_get_objects (MonoDomain *domain, MonoMethod *method) { MonoArrayHandle result; HANDLE_FUNCTION_ENTER (); MONO_ENTER_GC_UNSAFE; ERROR_DECL (error); result = mono_param_get_objects_internal (method, NULL, error); mono_error_assert_ok (error); MONO_EXIT_GC_UNSAFE; HANDLE_FUNCTION_RETURN_OBJ (result); } static gboolean add_local_var_info_to_array (MonoMethodHeader *header, int idx, MonoArrayHandle dest, MonoError *error) { HANDLE_FUNCTION_ENTER (); error_init (error); MonoReflectionLocalVariableInfoHandle info = MONO_HANDLE_CAST (MonoReflectionLocalVariableInfo, mono_object_new_handle (mono_class_get_local_variable_info_class (), error)); goto_if_nok (error, leave); MonoReflectionTypeHandle rt; rt = mono_type_get_object_handle (header->locals [idx], error); goto_if_nok (error, leave); MONO_HANDLE_SET (info, local_type, rt); MONO_HANDLE_SETVAL (info, is_pinned, MonoBoolean, header->locals [idx]->pinned); MONO_HANDLE_SETVAL (info, local_index, guint16, idx); MONO_HANDLE_ARRAY_SETREF (dest, idx, info); leave: HANDLE_FUNCTION_RETURN_VAL (is_ok (error)); } static gboolean add_exception_handling_clause_to_array (MonoMethodHeader *header, int idx, MonoArrayHandle dest, MonoError *error) { HANDLE_FUNCTION_ENTER (); error_init (error); MonoReflectionExceptionHandlingClauseHandle info = MONO_HANDLE_CAST (MonoReflectionExceptionHandlingClause, mono_object_new_handle (mono_class_get_exception_handling_clause_class (), error)); goto_if_nok (error, leave); MonoExceptionClause *clause; clause = &header->clauses [idx]; MONO_HANDLE_SETVAL (info, flags, gint32, clause->flags); MONO_HANDLE_SETVAL (info, try_offset, gint32, clause->try_offset); MONO_HANDLE_SETVAL (info, try_length, gint32, clause->try_len); MONO_HANDLE_SETVAL (info, handler_offset, gint32, clause->handler_offset); MONO_HANDLE_SETVAL (info, handler_length, gint32, clause->handler_len); if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) MONO_HANDLE_SETVAL (info, filter_offset, gint32, clause->data.filter_offset); else if (clause->data.catch_class) { MonoReflectionTypeHandle rt = mono_type_get_object_handle (m_class_get_byval_arg (clause->data.catch_class), error); goto_if_nok (error, leave); MONO_HANDLE_SET (info, catch_type, rt); } MONO_HANDLE_ARRAY_SETREF (dest, idx, info); leave: HANDLE_FUNCTION_RETURN_VAL (is_ok (error)); } /** * mono_method_body_get_object: * \param domain an app domain * \param method a method * \return A \c System.Reflection.MethodBody/RuntimeMethodBody object representing the method \p method. */ MonoReflectionMethodBody* mono_method_body_get_object (MonoDomain *domain, MonoMethod *method) { MonoReflectionMethodBodyHandle result; HANDLE_FUNCTION_ENTER (); MONO_ENTER_GC_UNSAFE; ERROR_DECL (error); result = mono_method_body_get_object_handle (method, error); mono_error_cleanup (error); MONO_EXIT_GC_UNSAFE; HANDLE_FUNCTION_RETURN_OBJ (result); } /* WARNING: This method can return NULL on success */ static MonoReflectionMethodBodyHandle method_body_object_construct (MonoClass *unused_class, MonoMethod *method, gpointer user_data, MonoError *error) { MonoMethodHeader *header = NULL; MonoImage *image; guint32 method_rva, local_var_sig_token; char *ptr; unsigned char format, flags; int i; gpointer params [6]; MonoBoolean init_locals_param; gint32 sig_token_param; gint32 max_stack_param; error_init (error); /* for compatibility with .net */ if (method_is_dynamic (method)) { mono_error_set_generic_error (error, "System", "InvalidOperationException", ""); goto fail; } image = m_class_get_image (method->klass); if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) || (method->flags & METHOD_ATTRIBUTE_ABSTRACT) || (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) || (image->raw_data && image->raw_data [1] != 'Z') || (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME)) return MONO_HANDLE_CAST (MonoReflectionMethodBody, NULL_HANDLE); header = mono_method_get_header_checked (method, error); goto_if_nok (error, fail); if (!image_is_dynamic (image)) { /* Obtain local vars signature token */ method_rva = mono_metadata_decode_row_col (&image->tables [MONO_TABLE_METHOD], mono_metadata_token_index (method->token) - 1, MONO_METHOD_RVA); ptr = mono_image_rva_map (image, method_rva); flags = *(const unsigned char *) ptr; format = flags & METHOD_HEADER_FORMAT_MASK; switch (format){ case METHOD_HEADER_TINY_FORMAT: local_var_sig_token = 0; break; case METHOD_HEADER_FAT_FORMAT: ptr += 2; ptr += 2; ptr += 4; local_var_sig_token = read32 (ptr); break; default: g_assert_not_reached (); } } else local_var_sig_token = 0; //FIXME static MonoMethod *ctor; if (!ctor) { MonoMethod *tmp = mono_class_get_method_from_name_checked (mono_class_get_method_body_class (), ".ctor", 6, 0, error); mono_error_assert_ok (error); g_assert (tmp); mono_memory_barrier (); ctor = tmp; } MonoReflectionMethodBodyHandle ret; ret = MONO_HANDLE_CAST (MonoReflectionMethodBody, mono_object_new_handle (mono_class_get_method_body_class (), error)); goto_if_nok (error, fail); MonoArrayHandle il_arr; il_arr = mono_array_new_handle (mono_defaults.byte_class, header->code_size, error); goto_if_nok (error, fail); MonoGCHandle il_gchandle; guint8* il_data; il_data = MONO_ARRAY_HANDLE_PIN (il_arr, guint8, 0, &il_gchandle); memcpy (il_data, header->code, header->code_size); mono_gchandle_free_internal (il_gchandle); /* Locals */ MonoArrayHandle locals_arr; locals_arr = mono_array_new_handle (mono_class_get_local_variable_info_class (), header->num_locals, error); goto_if_nok (error, fail); for (i = 0; i < header->num_locals; ++i) { if (!add_local_var_info_to_array (header, i, locals_arr, error)) goto fail; } /* Exceptions */ MonoArrayHandle exn_clauses; exn_clauses = mono_array_new_handle (mono_class_get_exception_handling_clause_class (), header->num_clauses, error); goto_if_nok (error, fail); for (i = 0; i < header->num_clauses; ++i) { if (!add_exception_handling_clause_to_array (header, i, exn_clauses, error)) goto fail; } /* MethodBody (ExceptionHandlingClause[] clauses, LocalVariableInfo[] locals, byte[] il, bool init_locals, int sig_token, int max_stack) */ init_locals_param = header->init_locals; sig_token_param = local_var_sig_token; max_stack_param = header->max_stack; mono_metadata_free_mh (header); header = NULL; params [0] = MONO_HANDLE_RAW (exn_clauses); params [1] = MONO_HANDLE_RAW (locals_arr); params [2] = MONO_HANDLE_RAW (il_arr); params [3] = &init_locals_param; params [4] = &sig_token_param; params [5] = &max_stack_param; mono_runtime_invoke_handle_void (ctor, MONO_HANDLE_CAST (MonoObject, ret), params, error); mono_error_assert_ok (error); return ret; fail: if (header) mono_metadata_free_mh (header); return MONO_HANDLE_CAST (MonoReflectionMethodBody, NULL_HANDLE); } /** * mono_method_body_get_object_handle: * \param method a method * \param error set on error * \returns a \c System.Reflection.MethodBody object representing the * method \p method. On failure, returns NULL and sets \p error. */ MonoReflectionMethodBodyHandle mono_method_body_get_object_handle (MonoMethod *method, MonoError *error) { error_init (error); return CHECK_OR_CONSTRUCT_HANDLE (MonoReflectionMethodBody, m_method_get_mem_manager (method), method, NULL, method_body_object_construct, NULL); } /** * mono_get_dbnull_object: * \param domain Domain where the object lives * Used as the value for \c ParameterInfo.DefaultValue * \returns the \c System.DBNull.Value singleton object */ MonoObject * mono_get_dbnull_object (MonoDomain *domain) { HANDLE_FUNCTION_ENTER (); ERROR_DECL (error); MonoObjectHandle obj = get_dbnull_object (error); mono_error_assert_ok (error); HANDLE_FUNCTION_RETURN_OBJ (obj); } static void get_default_param_value_blobs (MonoMethod *method, char **blobs, guint32 *types) { guint32 param_index, i, lastp, crow = 0; guint32 param_cols [MONO_PARAM_SIZE], const_cols [MONO_CONSTANT_SIZE]; gint32 idx; MonoClass *klass = method->klass; MonoImage *image = m_class_get_image (klass); MonoMethodSignature *methodsig = mono_method_signature_internal (method); MonoTableInfo *constt; MonoTableInfo *methodt; MonoTableInfo *paramt; if (!methodsig->param_count) return; mono_class_init_internal (klass); if (image_is_dynamic (image)) { MonoReflectionMethodAux *aux; if (method->is_inflated) method = ((MonoMethodInflated*)method)->declaring; aux = (MonoReflectionMethodAux *)g_hash_table_lookup (((MonoDynamicImage*)m_class_get_image (method->klass))->method_aux_hash, method); if (aux && aux->param_defaults) { memcpy (blobs, &(aux->param_defaults [1]), methodsig->param_count * sizeof (char*)); memcpy (types, &(aux->param_default_types [1]), methodsig->param_count * sizeof (guint32)); } return; } methodt = &image->tables [MONO_TABLE_METHOD]; paramt = &image->tables [MONO_TABLE_PARAM]; constt = &image->tables [MONO_TABLE_CONSTANT]; idx = mono_method_get_index (method); g_assert (idx != 0); /* lastp is the starting param index for the next method in the table, or * one past the last row if this is the last method */ /* FIXME: metadata-update : will this work with added methods ? */ param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST); if (!mono_metadata_table_bounds_check (image, MONO_TABLE_METHOD, idx + 1)) lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST); else lastp = table_info_get_rows (paramt) + 1; for (i = param_index; i < lastp; ++i) { guint32 paramseq; mono_metadata_decode_row (paramt, i - 1, param_cols, MONO_PARAM_SIZE); paramseq = param_cols [MONO_PARAM_SEQUENCE]; if (!(param_cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_DEFAULT)) continue; crow = mono_metadata_get_constant_index (image, MONO_TOKEN_PARAM_DEF | i, crow + 1); if (!crow) { continue; } mono_metadata_decode_row (constt, crow - 1, const_cols, MONO_CONSTANT_SIZE); blobs [paramseq - 1] = (char *)mono_metadata_blob_heap (image, const_cols [MONO_CONSTANT_VALUE]); types [paramseq - 1] = const_cols [MONO_CONSTANT_TYPE]; } return; } MonoObjectHandle mono_get_object_from_blob (MonoType *type, const char *blob, MonoStringHandleOut string_handle, MonoError *error) { error_init (error); if (!blob) return NULL_HANDLE; HANDLE_FUNCTION_ENTER (); MonoObject *object; void *retval = &object; MonoType *basetype = type; MonoObjectHandle object_handle = MONO_HANDLE_NEW (MonoObject, NULL); MonoClass* const klass = mono_class_from_mono_type_internal (type); if (m_class_is_valuetype (klass)) { object = mono_object_new_checked (klass, error); MONO_HANDLE_ASSIGN_RAW (object_handle, object); return_val_if_nok (error, NULL_HANDLE); retval = mono_object_get_data (object); if (m_class_is_enumtype (klass)) basetype = mono_class_enum_basetype_internal (klass); } if (mono_get_constant_value_from_blob (basetype->type, blob, retval, string_handle, error)) MONO_HANDLE_ASSIGN_RAW (object_handle, object); else object_handle = NULL_HANDLE; HANDLE_FUNCTION_RETURN_REF (MonoObject, object_handle); } static int assembly_name_to_aname (MonoAssemblyName *assembly, char *p) { int found_sep; char *s; gboolean quoted = FALSE; memset (assembly, 0, sizeof (MonoAssemblyName)); assembly->without_version = TRUE; assembly->without_culture = TRUE; assembly->without_public_key_token = TRUE; assembly->culture = ""; memset (assembly->public_key_token, 0, MONO_PUBLIC_KEY_TOKEN_LENGTH); if (*p == '"') { quoted = TRUE; p++; } assembly->name = p; s = p; while (*p && (isalnum (*p) || *p == '.' || *p == '-' || *p == '_' || *p == '$' || *p == '@' || g_ascii_isspace (*p))) p++; if (quoted) { if (*p != '"') return 1; *p = 0; p++; } g_strchomp (s); assembly->name = s; if (*p != ',') { g_strchomp (s); assembly->name = s; return 1; } *p = 0; /* Remove trailing whitespace */ s = p - 1; while (*s && g_ascii_isspace (*s)) *s-- = 0; p ++; while (g_ascii_isspace (*p)) p++; while (*p) { if ((*p == 'V' || *p == 'v') && g_ascii_strncasecmp (p, "Version", 7) == 0) { assembly->without_version = FALSE; p += 7; while (*p && *p != '=') p++; p++; while (*p && g_ascii_isspace (*p)) p++; assembly->major = strtoul (p, &s, 10); if (s == p || *s != '.') return 1; p = ++s; assembly->minor = strtoul (p, &s, 10); if (s == p || *s != '.') return 1; p = ++s; assembly->build = strtoul (p, &s, 10); if (s == p || *s != '.') return 1; p = ++s; assembly->revision = strtoul (p, &s, 10); if (s == p) return 1; p = s; } else if ((*p == 'C' || *p == 'c') && g_ascii_strncasecmp (p, "Culture", 7) == 0) { assembly->without_culture = FALSE; p += 7; while (*p && *p != '=') p++; p++; while (*p && g_ascii_isspace (*p)) p++; if ((g_ascii_strncasecmp (p, "neutral", 7) == 0) && (p [7] == ' ' || p [7] == ',')) { assembly->culture = ""; p += 7; } else { assembly->culture = p; while (*p && *p != ',') { if (*p == ' ') *p = 0; p++; } } } else if ((*p == 'P' || *p == 'p') && g_ascii_strncasecmp (p, "PublicKeyToken", 14) == 0) { assembly->without_public_key_token = FALSE; p += 14; while (*p && *p != '=') p++; p++; while (*p && g_ascii_isspace (*p)) p++; if (strncmp (p, "null", 4) == 0) { p += 4; } else { int len; gchar *start = p; while (*p && *p != ',') { p++; } len = (p - start + 1); if (len > MONO_PUBLIC_KEY_TOKEN_LENGTH) len = MONO_PUBLIC_KEY_TOKEN_LENGTH; char* pkt_lower = g_ascii_strdown (start, len); g_strlcpy ((char*) assembly->public_key_token, pkt_lower, len); g_free (pkt_lower); } } else { while (*p && *p != ',') p++; } found_sep = 0; while (g_ascii_isspace (*p) || *p == ',') { *p++ = 0; found_sep = 1; continue; } /* failed */ if (!found_sep) return 1; } return 0; } /* * mono_reflection_parse_type: * @name: type name * * Parse a type name as accepted by the GetType () method and output the info * extracted in the info structure. * the name param will be mangled, so, make a copy before passing it to this function. * The fields in info will be valid until the memory pointed to by name is valid. * * See also mono_type_get_name () below. * * Returns: 0 on parse error. */ static int _mono_reflection_parse_type (char *name, char **endptr, gboolean is_recursed, MonoTypeNameParse *info) { char *start, *p, *w, *last_point, *startn; int in_modifiers = 0; int isbyref = 0, rank = 0, isptr = 0; start = p = w = name; memset (info, 0, sizeof (MonoTypeNameParse)); /* last_point separates the namespace from the name */ last_point = NULL; /* Skips spaces */ while (*p == ' ') p++, start++, w++, name++; while (*p) { switch (*p) { case '+': *p = 0; /* NULL terminate the name */ startn = p + 1; info->nested = g_list_append (info->nested, startn); /* we have parsed the nesting namespace + name */ if (info->name) break; if (last_point) { info->name_space = start; *last_point = 0; info->name = last_point + 1; } else { info->name_space = (char *)""; info->name = start; } break; case '.': last_point = p; break; case '\\': ++p; break; case '&': case '*': case '[': case ',': case ']': in_modifiers = 1; break; default: break; } if (in_modifiers) break; // *w++ = *p++; p++; } if (!info->name) { if (last_point) { info->name_space = start; *last_point = 0; info->name = last_point + 1; } else { info->name_space = (char *)""; info->name = start; } } while (*p) { switch (*p) { case '&': if (isbyref) /* only one level allowed by the spec */ return 0; isbyref = 1; isptr = 0; info->modifiers = g_list_append (info->modifiers, GUINT_TO_POINTER (0)); *p++ = 0; break; case '*': if (isbyref) /* pointer to ref not okay */ return 0; info->modifiers = g_list_append (info->modifiers, GUINT_TO_POINTER (-1)); isptr = 1; *p++ = 0; break; case '[': if (isbyref) /* array of ref and generic ref are not okay */ return 0; //Decide if it's an array of a generic argument list *p++ = 0; if (!*p) //XXX test return 0; if (*p == ',' || *p == '*' || *p == ']') { //array gboolean bounded = FALSE; isptr = 0; rank = 1; while (*p) { if (*p == ']') break; if (*p == ',') rank++; else if (*p == '*') /* '*' means unknown lower bound */ bounded = TRUE; else return 0; ++p; } if (*p++ != ']') return 0; /* bounded only allowed when rank == 1 */ if (bounded && rank > 1) return 0; /* n.b. bounded needs both modifiers: -2 == bounded, 1 == rank 1 array */ if (bounded) info->modifiers = g_list_append (info->modifiers, GUINT_TO_POINTER (-2)); info->modifiers = g_list_append (info->modifiers, GUINT_TO_POINTER (rank)); } else { if (rank || isptr) /* generic args after array spec or ptr*/ //XXX test return 0; isptr = 0; info->type_arguments = g_ptr_array_new (); while (*p) { MonoTypeNameParse *subinfo = g_new0 (MonoTypeNameParse, 1); gboolean fqname = FALSE; g_ptr_array_add (info->type_arguments, subinfo); while (*p == ' ') p++; if (*p == '[') { p++; fqname = TRUE; } if (!_mono_reflection_parse_type (p, &p, TRUE, subinfo)) return 0; /*MS is lenient on [] delimited parameters that aren't fqn - and F# uses them.*/ if (fqname && (*p != ']')) { char *aname; if (*p != ',') return 0; *p++ = 0; aname = p; while (*p && (*p != ']')) p++; if (*p != ']') return 0; *p++ = 0; while (*aname) { if (g_ascii_isspace (*aname)) { ++aname; continue; } break; } if (!*aname || !assembly_name_to_aname (&subinfo->assembly, aname)) return 0; } else if (fqname && (*p == ']')) { *p++ = 0; } if (*p == ']') { *p++ = 0; break; } else if (!*p) { return 0; } *p++ = 0; } } break; case ']': if (is_recursed) goto end; return 0; case ',': if (is_recursed) goto end; *p++ = 0; while (*p) { if (g_ascii_isspace (*p)) { ++p; continue; } break; } if (!*p) return 0; /* missing assembly name */ if (!assembly_name_to_aname (&info->assembly, p)) return 0; break; default: return 0; } if (info->assembly.name) break; } // *w = 0; /* terminate class name */ end: if (!info->name || !*info->name) return 0; if (endptr) *endptr = p; /* add other consistency checks */ return 1; } /** * mono_identifier_unescape_type_name_chars: * \param identifier the display name of a mono type * * \returns The name in internal form, that is without escaping backslashes. * * The string is modified in place! */ char* mono_identifier_unescape_type_name_chars(char* identifier) { char *w, *r; if (!identifier) return NULL; for (w = r = identifier; *r != 0; r++) { char c = *r; if (c == '\\') { r++; if (*r == 0) break; c = *r; } *w = c; w++; } if (w != r) *w = 0; return identifier; } void mono_identifier_unescape_info (MonoTypeNameParse* info); static void unescape_each_type_argument(void* data, void* user_data) { MonoTypeNameParse* info = (MonoTypeNameParse*)data; mono_identifier_unescape_info (info); } static void unescape_each_nested_name (void* data, void* user_data) { char* nested_name = (char*) data; mono_identifier_unescape_type_name_chars(nested_name); } /** * mono_identifier_unescape_info: * * \param info a parsed display form of an (optionally assembly qualified) full type name. * * Destructively updates the info by unescaping the identifiers that * comprise the type namespace, name, nested types (if any) and * generic type arguments (if any). * * The resulting info has the names in internal form. * */ void mono_identifier_unescape_info (MonoTypeNameParse *info) { if (!info) return; mono_identifier_unescape_type_name_chars(info->name_space); mono_identifier_unescape_type_name_chars(info->name); // but don't escape info->assembly if (info->type_arguments) g_ptr_array_foreach(info->type_arguments, &unescape_each_type_argument, NULL); if (info->nested) g_list_foreach(info->nested, &unescape_each_nested_name, NULL); } /** * mono_reflection_parse_type: */ int mono_reflection_parse_type (char *name, MonoTypeNameParse *info) { gboolean result; MONO_ENTER_GC_UNSAFE; ERROR_DECL (error); result = mono_reflection_parse_type_checked (name, info, error); mono_error_cleanup (error); MONO_EXIT_GC_UNSAFE; return result ? 1 : 0; } /** * mono_reflection_parse_type_checked: * \param name the string to parse * \param info the parsed name components * \param error set on error * * Parse the given \p name and write the results to \p info, setting \p error * on error. The string \p name is modified in place and \p info points into * its memory and into allocated memory. * * \returns TRUE if parsing succeeded, otherwise returns FALSE and sets \p error. * */ gboolean mono_reflection_parse_type_checked (char *name, MonoTypeNameParse *info, MonoError *error) { error_init (error); int ok = _mono_reflection_parse_type (name, NULL, FALSE, info); if (ok) { mono_identifier_unescape_info (info); } else { mono_error_set_argument_format (error, "typeName@0", "failed parse: %s", name); } return (ok != 0); } static MonoType* _mono_reflection_get_type_from_info (MonoAssemblyLoadContext *alc, MonoTypeNameParse *info, MonoImage *image, gboolean ignorecase, gboolean search_mscorlib, MonoError *error) { gboolean type_resolve = FALSE; MonoType *type; MonoImage *rootimage = image; error_init (error); if (info->assembly.name) { MonoAssembly *assembly = mono_assembly_loaded_internal (alc, &info->assembly); if (!assembly && image && image->assembly && mono_assembly_check_name_match (&info->assembly, &image->assembly->aname)) /* * This could happen in the AOT compiler case when the search hook is not * installed. */ assembly = image->assembly; if (!assembly) { /* then we must load the assembly ourselve - see #60439 */ MonoAssemblyByNameRequest req; mono_assembly_request_prepare_byname (&req, alc); req.requesting_assembly = NULL; req.basedir = image ? image->assembly->basedir : NULL; assembly = mono_assembly_request_byname (&info->assembly, &req, NULL); if (!assembly) return NULL; } image = assembly->image; } else if (!image && search_mscorlib) { image = mono_defaults.corlib; } type = mono_reflection_get_type_with_rootimage (alc, rootimage, image, info, ignorecase, search_mscorlib, &type_resolve, error); if (type == NULL && !info->assembly.name && image != mono_defaults.corlib && search_mscorlib) { /* ignore the error and try again */ mono_error_cleanup (error); error_init (error); image = mono_defaults.corlib; type = mono_reflection_get_type_with_rootimage (alc, rootimage, image, info, ignorecase, search_mscorlib, &type_resolve, error); } return type; } /** * mono_reflection_get_type_internal: * * Returns: may return NULL on success, sets error on failure. */ static MonoType* mono_reflection_get_type_internal (MonoAssemblyLoadContext *alc, MonoImage *rootimage, MonoImage* image, MonoTypeNameParse *info, gboolean ignorecase, gboolean search_mscorlib, MonoError *error) { HANDLE_FUNCTION_ENTER (); MonoClass *klass; GList *mod; int modval; gboolean bounded = FALSE; MonoType* type = NULL; error_init (error); if (!image) image = mono_defaults.corlib; if (!rootimage) rootimage = mono_defaults.corlib; if (ignorecase) klass = mono_class_from_name_case_checked (image, info->name_space, info->name, error); else klass = mono_class_from_name_checked (image, info->name_space, info->name, error); if (!klass) goto leave; for (mod = info->nested; mod; mod = mod->next) { gpointer iter = NULL; MonoClass *parent; parent = klass; mono_class_init_internal (parent); while ((klass = mono_class_get_nested_types (parent, &iter))) { const char *lastp; char *nested_name, *nested_nspace; gboolean match = TRUE; lastp = strrchr ((const char *)mod->data, '.'); if (lastp) { /* Nested classes can have namespaces */ int nspace_len; nested_name = g_strdup (lastp + 1); nspace_len = lastp - (char*)mod->data; nested_nspace = (char *)g_malloc (nspace_len + 1); memcpy (nested_nspace, mod->data, nspace_len); nested_nspace [nspace_len] = '\0'; } else { nested_name = (char *)mod->data; nested_nspace = NULL; } if (nested_nspace) { const char *klass_name_space = m_class_get_name_space (klass); if (ignorecase) { if (!(klass_name_space && mono_utf8_strcasecmp (klass_name_space, nested_nspace) == 0)) match = FALSE; } else { if (!(klass_name_space && strcmp (klass_name_space, nested_nspace) == 0)) match = FALSE; } } if (match) { const char *klass_name = m_class_get_name (klass); if (ignorecase) { if (mono_utf8_strcasecmp (klass_name, nested_name) != 0) match = FALSE; } else { if (strcmp (klass_name, nested_name) != 0) match = FALSE; } } if (lastp) { g_free (nested_name); g_free (nested_nspace); } if (match) break; } if (!klass) break; } if (!klass) goto leave; if (info->type_arguments) { MonoType **type_args = g_new0 (MonoType *, info->type_arguments->len); MonoReflectionTypeHandle the_type; MonoType *instance; int i; for (i = 0; i < info->type_arguments->len; i++) { MonoTypeNameParse *subinfo = (MonoTypeNameParse *)g_ptr_array_index (info->type_arguments, i); type_args [i] = _mono_reflection_get_type_from_info (alc, subinfo, rootimage, ignorecase, search_mscorlib, error); if (!type_args [i]) { g_free (type_args); goto leave; } } the_type = mono_type_get_object_handle (m_class_get_byval_arg (klass), error); if (!is_ok (error) || MONO_HANDLE_IS_NULL (the_type)) goto leave; instance = mono_reflection_bind_generic_parameters ( the_type, info->type_arguments->len, type_args, error); g_free (type_args); if (!instance) goto leave; klass = mono_class_from_mono_type_internal (instance); } for (mod = info->modifiers; mod; mod = mod->next) { modval = GPOINTER_TO_UINT (mod->data); if (!modval) { /* byref: must be last modifier */ type = mono_class_get_byref_type (klass); goto leave; } else if (modval == -1) { klass = mono_class_create_ptr (m_class_get_byval_arg (klass)); } else if (modval == -2) { bounded = TRUE; } else { /* array rank */ klass = mono_class_create_bounded_array (klass, modval, bounded); } } type = m_class_get_byval_arg (klass); leave: HANDLE_FUNCTION_RETURN_VAL (type); } /** * mono_reflection_get_type: * \param image a metadata context * \param info type description structure * \param ignorecase flag for case-insensitive string compares * \param type_resolve whenever type resolve was already tried * * Build a MonoType from the type description in \p info. * */ MonoType* mono_reflection_get_type (MonoImage* image, MonoTypeNameParse *info, gboolean ignorecase, gboolean *type_resolve) { MonoType *result; MONO_ENTER_GC_UNSAFE; ERROR_DECL (error); result = mono_reflection_get_type_with_rootimage (mono_alc_get_default (), image, image, info, ignorecase, TRUE, type_resolve, error); mono_error_cleanup (error); MONO_EXIT_GC_UNSAFE; return result; } /** * mono_reflection_get_type_checked: * \param alc the AssemblyLoadContext to check/load into * \param rootimage the image of the currently active managed caller * \param image a metadata context * \param info type description structure * \param ignorecase flag for case-insensitive string compares * \param type_resolve whenever type resolve was already tried * \param * \param error set on error. * Build a \c MonoType from the type description in \p info. On failure returns NULL and sets \p error. */ MonoType* mono_reflection_get_type_checked (MonoAssemblyLoadContext *alc, MonoImage *rootimage, MonoImage* image, MonoTypeNameParse *info, gboolean ignorecase, gboolean search_mscorlib, gboolean *type_resolve, MonoError *error) { error_init (error); return mono_reflection_get_type_with_rootimage (alc, rootimage, image, info, ignorecase, search_mscorlib, type_resolve, error); } static MonoType* module_builder_array_get_type (MonoAssemblyLoadContext *alc, MonoArrayHandle module_builders, int i, MonoImage *rootimage, MonoTypeNameParse *info, gboolean ignorecase, gboolean search_mscorlib, MonoError *error) { HANDLE_FUNCTION_ENTER (); error_init (error); MonoType *type = NULL; MonoReflectionModuleBuilderHandle mb = MONO_HANDLE_NEW (MonoReflectionModuleBuilder, NULL); MONO_HANDLE_ARRAY_GETREF (mb, module_builders, i); MonoDynamicImage *dynamic_image = MONO_HANDLE_GETVAL (mb, dynamic_image); type = mono_reflection_get_type_internal (alc, rootimage, &dynamic_image->image, info, ignorecase, search_mscorlib, error); HANDLE_FUNCTION_RETURN_VAL (type); } static MonoType* module_array_get_type (MonoAssemblyLoadContext *alc, MonoArrayHandle modules, int i, MonoImage *rootimage, MonoTypeNameParse *info, gboolean ignorecase, gboolean search_mscorlib, MonoError *error) { HANDLE_FUNCTION_ENTER (); error_init (error); MonoType *type = NULL; MonoReflectionModuleHandle mod = MONO_HANDLE_NEW (MonoReflectionModule, NULL); MONO_HANDLE_ARRAY_GETREF (mod, modules, i); MonoImage *image = MONO_HANDLE_GETVAL (mod, image); type = mono_reflection_get_type_internal (alc, rootimage, image, info, ignorecase, search_mscorlib, error); HANDLE_FUNCTION_RETURN_VAL (type); } static MonoType* mono_reflection_get_type_internal_dynamic (MonoAssemblyLoadContext *alc, MonoImage *rootimage, MonoAssembly *assembly, MonoTypeNameParse *info, gboolean ignorecase, gboolean search_mscorlib, MonoError *error) { HANDLE_FUNCTION_ENTER (); MonoType *type = NULL; int i; error_init (error); g_assert (assembly_is_dynamic (assembly)); MonoReflectionAssemblyBuilderHandle abuilder = MONO_HANDLE_CAST (MonoReflectionAssemblyBuilder, mono_assembly_get_object_handle (assembly, error)); goto_if_nok (error, leave); /* Enumerate all modules */ MonoArrayHandle modules; modules = MONO_HANDLE_NEW (MonoArray, NULL); MONO_HANDLE_GET (modules, abuilder, modules); if (!MONO_HANDLE_IS_NULL (modules)) { int n = mono_array_handle_length (modules); for (i = 0; i < n; ++i) { type = module_builder_array_get_type (alc, modules, i, rootimage, info, ignorecase, search_mscorlib, error); if (type) break; goto_if_nok (error, leave); } } MonoArrayHandle loaded_modules; loaded_modules = MONO_HANDLE_NEW (MonoArray, NULL); MONO_HANDLE_GET (loaded_modules, abuilder, loaded_modules); if (!type && !MONO_HANDLE_IS_NULL(loaded_modules)) { int n = mono_array_handle_length (loaded_modules); for (i = 0; i < n; ++i) { type = module_array_get_type (alc, loaded_modules, i, rootimage, info, ignorecase, search_mscorlib, error); if (type) break; goto_if_nok (error, leave); } } leave: HANDLE_FUNCTION_RETURN_VAL (type); } MonoType* mono_reflection_get_type_with_rootimage (MonoAssemblyLoadContext *alc, MonoImage *rootimage, MonoImage* image, MonoTypeNameParse *info, gboolean ignorecase, gboolean search_mscorlib, gboolean *type_resolve, MonoError *error) { HANDLE_FUNCTION_ENTER (); MonoType *type; MonoReflectionAssemblyHandle reflection_assembly; MonoDomain *domain = mono_get_root_domain (); GString *fullName = NULL; GList *mod; error_init (error); if (image && image_is_dynamic (image)) type = mono_reflection_get_type_internal_dynamic (alc, rootimage, image->assembly, info, ignorecase, search_mscorlib, error); else type = mono_reflection_get_type_internal (alc, rootimage, image, info, ignorecase, search_mscorlib, error); goto_if_nok (error, return_null); if (type) goto exit; if (!mono_domain_has_type_resolve (domain)) goto return_null; if (type_resolve) { if (*type_resolve) goto return_null; *type_resolve = TRUE; } /* Reconstruct the type name */ fullName = g_string_new (""); if (info->name_space && (info->name_space [0] != '\0')) g_string_printf (fullName, "%s.%s", info->name_space, info->name); else g_string_printf (fullName, "%s", info->name); for (mod = info->nested; mod; mod = mod->next) g_string_append_printf (fullName, "+%s", (char*)mod->data); MonoStringHandle name_handle; name_handle = mono_string_new_handle (fullName->str, error); goto_if_nok (error, return_null); reflection_assembly = mono_domain_try_type_resolve_name (image->assembly, name_handle, error); goto_if_nok (error, return_null); if (MONO_HANDLE_BOOL (reflection_assembly)) { MonoAssembly *assembly = MONO_HANDLE_GETVAL (reflection_assembly, assembly); if (assembly_is_dynamic (assembly)) type = mono_reflection_get_type_internal_dynamic (alc, rootimage, assembly, info, ignorecase, search_mscorlib, error); else type = mono_reflection_get_type_internal (alc, rootimage, assembly->image, info, ignorecase, search_mscorlib, error); } goto_if_nok (error, return_null); goto exit; return_null: type = NULL; goto exit; exit: if (fullName) g_string_free (fullName, TRUE); HANDLE_FUNCTION_RETURN_VAL (type); } /** * mono_reflection_free_type_info: */ void mono_reflection_free_type_info (MonoTypeNameParse *info) { g_list_free (info->modifiers); g_list_free (info->nested); if (info->type_arguments) { int i; for (i = 0; i < info->type_arguments->len; i++) { MonoTypeNameParse *subinfo = (MonoTypeNameParse *)g_ptr_array_index (info->type_arguments, i); mono_reflection_free_type_info (subinfo); /*We free the subinfo since it is allocated by _mono_reflection_parse_type*/ g_free (subinfo); } g_ptr_array_free (info->type_arguments, TRUE); } } /** * mono_reflection_type_from_name: * \param name type name. * \param image a metadata context (can be NULL). * * Retrieves a \c MonoType from its \p name. If the name is not fully qualified, * it defaults to get the type from \p image or, if \p image is NULL or loading * from it fails, uses corlib. * */ MonoType* mono_reflection_type_from_name (char *name, MonoImage *image) { MonoType *result; MONO_ENTER_GC_UNSAFE; ERROR_DECL (error); MonoAssemblyLoadContext *alc = mono_alc_get_default (); result = mono_reflection_type_from_name_checked (name, alc, image, error); mono_error_cleanup (error); MONO_EXIT_GC_UNSAFE; return result; } /** * mono_reflection_type_from_name_checked: * \param name type name. * \param alc the AssemblyLoadContext to check/load into * \param image a metadata context (can be NULL). * \param error set on errror. * Retrieves a MonoType from its \p name. If the name is not fully qualified, * it defaults to get the type from \p image or, if \p image is NULL or loading * from it fails, uses corlib. On failure returns NULL and sets \p error. */ MonoType* mono_reflection_type_from_name_checked (char *name, MonoAssemblyLoadContext *alc, MonoImage *image, MonoError *error) { MonoType *type = NULL; MonoTypeNameParse info; char *tmp; error_init (error); /* Make a copy since parse_type modifies its argument */ tmp = g_strdup (name); /*g_print ("requested type %s\n", str);*/ ERROR_DECL (parse_error); if (!mono_reflection_parse_type_checked (tmp, &info, parse_error)) { mono_error_cleanup (parse_error); goto leave; } type = _mono_reflection_get_type_from_info (alc, &info, image, FALSE, TRUE, error); leave: g_free (tmp); mono_reflection_free_type_info (&info); return type; } /** * mono_reflection_get_token: * \returns the metadata token of \p obj which should be an object * representing a metadata element. */ guint32 mono_reflection_get_token (MonoObject *obj_raw) { guint32 result; HANDLE_FUNCTION_ENTER (); MONO_ENTER_GC_UNSAFE; MONO_HANDLE_DCL (MonoObject, obj); ERROR_DECL (error); result = mono_reflection_get_token_checked (obj, error); mono_error_assert_ok (error); MONO_EXIT_GC_UNSAFE; HANDLE_FUNCTION_RETURN_VAL (result); } /** * mono_reflection_get_param_info_member_and_pos: * * Return the MemberImpl and PositionImpl fields of P. */ void mono_reflection_get_param_info_member_and_pos (MonoReflectionParameterHandle p, MonoObjectHandle member_impl, int *out_position) { MonoClass *klass = mono_class_get_mono_parameter_info_class (); /* These two fields are part of ParameterInfo instead of RuntimeParameterInfo, and they cannot be moved */ static MonoClassField *member_field; if (!member_field) { MonoClassField *f = mono_class_get_field_from_name_full (klass, "MemberImpl", NULL); g_assert (f); member_field = f; } MonoObject *member; mono_field_get_value_internal (MONO_HANDLE_RAW (MONO_HANDLE_CAST (MonoObject, p)), member_field, &member); MONO_HANDLE_ASSIGN_RAW (member_impl, member); static MonoClassField *pos_field; if (!pos_field) { MonoClassField *f = mono_class_get_field_from_name_full (klass, "PositionImpl", NULL); g_assert (f); pos_field = f; } mono_field_get_value_internal (MONO_HANDLE_RAW (MONO_HANDLE_CAST (MonoObject, p)), pos_field, out_position); } /** * mono_reflection_get_token_checked: * \param obj the object * \param error set on error * \returns the metadata token of \p obj which should be an object * representing a metadata element. On failure sets \p error. */ guint32 mono_reflection_get_token_checked (MonoObjectHandle obj, MonoError *error) { guint32 token = 0; error_init (error); MonoClass *klass = mono_handle_class (obj); const char *klass_name = m_class_get_name (klass); if (strcmp (klass_name, "MethodBuilder") == 0) { MonoReflectionMethodBuilderHandle mb = MONO_HANDLE_CAST (MonoReflectionMethodBuilder, obj); token = MONO_HANDLE_GETVAL (mb, table_idx) | MONO_TOKEN_METHOD_DEF; } else if (strcmp (klass_name, "ConstructorBuilder") == 0) { MonoReflectionCtorBuilderHandle mb = MONO_HANDLE_CAST (MonoReflectionCtorBuilder, obj); token = MONO_HANDLE_GETVAL (mb, table_idx) | MONO_TOKEN_METHOD_DEF; } else if (strcmp (klass_name, "FieldBuilder") == 0) { g_assert_not_reached (); } else if (strcmp (klass_name, "TypeBuilder") == 0) { MonoReflectionTypeBuilderHandle tb = MONO_HANDLE_CAST (MonoReflectionTypeBuilder, obj); token = MONO_HANDLE_GETVAL (tb, table_idx) | MONO_TOKEN_TYPE_DEF; } else if (strcmp (klass_name, "RuntimeType") == 0) { MonoType *type = mono_reflection_type_handle_mono_type (MONO_HANDLE_CAST (MonoReflectionType, obj), error); return_val_if_nok (error, 0); MonoClass *mc = mono_class_from_mono_type_internal (type); if (!mono_class_init_internal (mc)) { mono_error_set_for_class_failure (error, mc); return 0; } token = m_class_get_type_token (mc); } else if (strcmp (klass_name, "RuntimeMethodInfo") == 0 || strcmp (klass_name, "RuntimeConstructorInfo") == 0) { MonoReflectionMethodHandle m = MONO_HANDLE_CAST (MonoReflectionMethod, obj); MonoMethod *method = MONO_HANDLE_GETVAL (m, method); if (method->is_inflated) { MonoMethodInflated *inflated = (MonoMethodInflated *) method; return inflated->declaring->token; } else { token = method->token; } } else if (strcmp (klass_name, "RuntimeFieldInfo") == 0) { MonoReflectionFieldHandle f = MONO_HANDLE_CAST (MonoReflectionField, obj); token = mono_class_get_field_token (MONO_HANDLE_GETVAL (f, field)); } else if (strcmp (klass_name, "RuntimePropertyInfo") == 0) { MonoReflectionPropertyHandle p = MONO_HANDLE_CAST (MonoReflectionProperty, obj); token = mono_class_get_property_token (MONO_HANDLE_GETVAL (p, property)); } else if (strcmp (klass_name, "RuntimeEventInfo") == 0) { MonoReflectionMonoEventHandle p = MONO_HANDLE_CAST (MonoReflectionMonoEvent, obj); token = mono_class_get_event_token (MONO_HANDLE_GETVAL (p, event)); } else if (strcmp (klass_name, "ParameterInfo") == 0 || strcmp (klass_name, "RuntimeParameterInfo") == 0) { MonoReflectionParameterHandle p = MONO_HANDLE_CAST (MonoReflectionParameter, obj); MonoObjectHandle member_impl = MONO_HANDLE_NEW (MonoObject, NULL); int position; mono_reflection_get_param_info_member_and_pos (p, member_impl, &position); MonoClass *member_class = mono_handle_class (member_impl); g_assert (mono_class_is_reflection_method_or_constructor (member_class)); MonoMethod *method = MONO_HANDLE_GETVAL (MONO_HANDLE_CAST (MonoReflectionMethod, member_impl), method); token = mono_method_get_param_token (method, position); } else if (strcmp (klass_name, "RuntimeModule") == 0 || strcmp (klass_name, "ModuleBuilder") == 0) { MonoReflectionModuleHandle m = MONO_HANDLE_CAST (MonoReflectionModule, obj); token = MONO_HANDLE_GETVAL (m, token); } else if (strcmp (klass_name, "RuntimeAssembly") == 0) { token = mono_metadata_make_token (MONO_TABLE_ASSEMBLY, 1); } else { mono_error_set_not_implemented (error, "MetadataToken is not supported for type '%s.%s'", m_class_get_name_space (klass), klass_name); return 0; } return token; } gboolean mono_reflection_is_usertype (MonoReflectionTypeHandle ref) { MonoClass *klass = mono_handle_class (ref); return m_class_get_image (klass) != mono_defaults.corlib || strcmp ("TypeDelegator", m_class_get_name (klass)) == 0; } /** * mono_reflection_bind_generic_parameters: * \param type a managed type object (which should be some kind of generic (instance? definition?)) * \param type_args the number of type arguments to bind * \param types array of type arguments * \param error set on error * Given a managed type object for a generic type instance, binds each of its arguments to the specified types. * \returns the \c MonoType* for the resulting type instantiation. On failure returns NULL and sets \p error. */ MonoType* mono_reflection_bind_generic_parameters (MonoReflectionTypeHandle reftype, int type_argc, MonoType **types, MonoError *error) { gboolean is_dynamic = FALSE; MonoClass *geninst; error_init (error); mono_loader_lock (); MonoClass *klass = mono_handle_class (reftype); if (mono_is_sre_type_builder (klass)) { is_dynamic = TRUE; } else if (mono_is_sre_generic_instance (klass)) { /* Does this ever make sense? what does instantiating a generic instance even mean? */ g_assert_not_reached (); MonoReflectionGenericClassHandle rgi = MONO_HANDLE_CAST (MonoReflectionGenericClass, reftype); MonoReflectionTypeHandle gtd = MONO_HANDLE_NEW_GET (MonoReflectionType, rgi, generic_type); if (mono_is_sre_type_builder (mono_handle_class (gtd))) is_dynamic = TRUE; } MonoType *t = mono_reflection_type_handle_mono_type (reftype, error); if (!is_ok (error)) { mono_loader_unlock (); return NULL; } klass = mono_class_from_mono_type_internal (t); if (!mono_class_is_gtd (klass)) { mono_loader_unlock (); mono_error_set_type_load_class (error, klass, "Cannot bind generic parameters of a non-generic type"); return NULL; } guint gtd_type_argc = mono_class_get_generic_container (klass)->type_argc; if (gtd_type_argc != type_argc) { mono_loader_unlock (); mono_error_set_argument_format (error, "types", "The generic type definition needs %d type arguments, but was instantiated with %d ", gtd_type_argc, type_argc); return NULL; } if (m_class_was_typebuilder (klass)) is_dynamic = TRUE; mono_loader_unlock (); geninst = mono_class_bind_generic_parameters (klass, type_argc, types, is_dynamic); return m_class_get_byval_arg (geninst); } MonoClass* mono_class_bind_generic_parameters (MonoClass *klass, int type_argc, MonoType **types, gboolean is_dynamic) { MonoGenericClass *gclass; MonoGenericInst *inst; g_assert (mono_class_is_gtd (klass)); inst = mono_metadata_get_generic_inst (type_argc, types); gclass = mono_metadata_lookup_generic_class (klass, inst, is_dynamic); return mono_class_create_generic_inst (gclass); } static MonoGenericInst* generic_inst_from_type_array_handle (MonoArrayHandle types, MonoError *error) { HANDLE_FUNCTION_ENTER (); error_init (error); MonoGenericInst *ginst = NULL; int count = mono_array_handle_length (types); MonoType **type_argv = g_new0 (MonoType *, count); MonoReflectionTypeHandle garg = MONO_HANDLE_NEW (MonoReflectionType, NULL); for (int i = 0; i < count; i++) { MONO_HANDLE_ARRAY_GETREF (garg, types, i); type_argv [i] = mono_reflection_type_handle_mono_type (garg, error); goto_if_nok (error, leave); } ginst = mono_metadata_get_generic_inst (count, type_argv); leave: g_free (type_argv); HANDLE_FUNCTION_RETURN_VAL (ginst); } static MonoMethod* reflection_bind_generic_method_parameters (MonoMethod *method, MonoArrayHandle types, MonoError *error) { MonoClass *klass; MonoMethod *inflated; MonoGenericContext tmp_context; error_init (error); klass = method->klass; if (method->is_inflated) method = ((MonoMethodInflated *) method)->declaring; int count = mono_method_signature_internal (method)->generic_param_count; if (count != mono_array_handle_length (types)) { mono_error_set_argument (error, "typeArguments", "Incorrect number of generic arguments"); return NULL; } MonoGenericInst *ginst = generic_inst_from_type_array_handle (types, error); return_val_if_nok (error, NULL); tmp_context.class_inst = mono_class_is_ginst (klass) ? mono_class_get_generic_class (klass)->context.class_inst : NULL; tmp_context.method_inst = ginst; inflated = mono_class_inflate_generic_method_checked (method, &tmp_context, error); mono_error_assert_ok (error); if (!mono_verifier_is_method_valid_generic_instantiation (inflated)) { mono_error_set_argument (error, NULL, "Invalid generic arguments"); return NULL; } return inflated; } MonoReflectionMethodHandle ves_icall_RuntimeMethodInfo_MakeGenericMethod_impl (MonoReflectionMethodHandle rmethod, MonoArrayHandle types, MonoError *error) { error_init (error); g_assert (0 != strcmp (m_class_get_name (mono_handle_class (rmethod)), "MethodBuilder")); MonoMethod *method = MONO_HANDLE_GETVAL (rmethod, method); MonoMethod *imethod = reflection_bind_generic_method_parameters (method, types, error); return_val_if_nok (error, MONO_HANDLE_CAST (MonoReflectionMethod, NULL_HANDLE)); MonoReflectionType *reftype = MONO_HANDLE_GETVAL (rmethod, reftype); MonoClass *refclass = mono_class_from_mono_type_internal (reftype->type); /*FIXME but I think this is no longer necessary*/ if (image_is_dynamic (m_class_get_image (method->klass))) { MonoDynamicImage *image = (MonoDynamicImage*)m_class_get_image (method->klass); /* * This table maps metadata structures representing inflated methods/fields * to the reflection objects representing their generic definitions. */ mono_image_lock ((MonoImage*)image); mono_g_hash_table_insert_internal (image->generic_def_objects, imethod, MONO_HANDLE_RAW (rmethod)); mono_image_unlock ((MonoImage*)image); } return mono_method_get_object_handle (imethod, refclass, error); } /* SECURITY_ACTION_* are defined in mono/metadata/tabledefs.h */ const static guint32 declsec_flags_map[] = { 0x00000000, /* empty */ MONO_DECLSEC_FLAG_REQUEST, /* SECURITY_ACTION_REQUEST (x01) */ MONO_DECLSEC_FLAG_DEMAND, /* SECURITY_ACTION_DEMAND (x02) */ MONO_DECLSEC_FLAG_ASSERT, /* SECURITY_ACTION_ASSERT (x03) */ MONO_DECLSEC_FLAG_DENY, /* SECURITY_ACTION_DENY (x04) */ MONO_DECLSEC_FLAG_PERMITONLY, /* SECURITY_ACTION_PERMITONLY (x05) */ MONO_DECLSEC_FLAG_LINKDEMAND, /* SECURITY_ACTION_LINKDEMAND (x06) */ MONO_DECLSEC_FLAG_INHERITANCEDEMAND, /* SECURITY_ACTION_INHERITANCEDEMAND (x07) */ MONO_DECLSEC_FLAG_REQUEST_MINIMUM, /* SECURITY_ACTION_REQUEST_MINIMUM (x08) */ MONO_DECLSEC_FLAG_REQUEST_OPTIONAL, /* SECURITY_ACTION_REQUEST_OPTIONAL (x09) */ MONO_DECLSEC_FLAG_REQUEST_REFUSE, /* SECURITY_ACTION_REQUEST_REFUSE (x0A) */ MONO_DECLSEC_FLAG_PREJIT_GRANT, /* SECURITY_ACTION_PREJIT_GRANT (x0B) */ MONO_DECLSEC_FLAG_PREJIT_DENY, /* SECURITY_ACTION_PREJIT_DENY (x0C) */ MONO_DECLSEC_FLAG_NONCAS_DEMAND, /* SECURITY_ACTION_NONCAS_DEMAND (x0D) */ MONO_DECLSEC_FLAG_NONCAS_LINKDEMAND, /* SECURITY_ACTION_NONCAS_LINKDEMAND (x0E) */ MONO_DECLSEC_FLAG_NONCAS_INHERITANCEDEMAND, /* SECURITY_ACTION_NONCAS_INHERITANCEDEMAND (x0F) */ MONO_DECLSEC_FLAG_LINKDEMAND_CHOICE, /* SECURITY_ACTION_LINKDEMAND_CHOICE (x10) */ MONO_DECLSEC_FLAG_INHERITANCEDEMAND_CHOICE, /* SECURITY_ACTION_INHERITANCEDEMAND_CHOICE (x11) */ MONO_DECLSEC_FLAG_DEMAND_CHOICE, /* SECURITY_ACTION_DEMAND_CHOICE (x12) */ }; /* * Returns flags that includes all available security action associated to the handle. * @token: metadata token (either for a class or a method) * @image: image where resides the metadata. */ static guint32 mono_declsec_get_flags (MonoImage *image, guint32 token) { int index = mono_metadata_declsec_from_index (image, token); MonoTableInfo *t = &image->tables [MONO_TABLE_DECLSECURITY]; guint32 result = 0; guint32 action; int i; /* HasSecurity can be present for other, not specially encoded, attributes, e.g. SuppressUnmanagedCodeSecurityAttribute */ if (index < 0) return 0; int rows = table_info_get_rows (t); for (i = index; i < rows; i++) { guint32 cols [MONO_DECL_SECURITY_SIZE]; mono_metadata_decode_row (t, i, cols, MONO_DECL_SECURITY_SIZE); if (cols [MONO_DECL_SECURITY_PARENT] != token) break; action = cols [MONO_DECL_SECURITY_ACTION]; if ((action >= MONO_DECLSEC_ACTION_MIN) && (action <= MONO_DECLSEC_ACTION_MAX)) { result |= declsec_flags_map [action]; } else { g_assert_not_reached (); } } return result; } /** * mono_declsec_flags_from_method: * \param method The method for which we want the declarative security flags. * Get the security actions (in the form of flags) associated with the specified method. * To keep \c MonoMethod size down we do not cache the declarative security flags * (except for the stack modifiers which are kept in the MonoJitInfo structure) * \returns the declarative security flags for the method (only). */ guint32 mono_declsec_flags_from_method (MonoMethod *method) { if (method->flags & METHOD_ATTRIBUTE_HAS_SECURITY) { /* FIXME: No cache (for the moment) */ guint32 idx = mono_method_get_index (method); idx <<= MONO_HAS_DECL_SECURITY_BITS; idx |= MONO_HAS_DECL_SECURITY_METHODDEF; return mono_declsec_get_flags (m_class_get_image (method->klass), idx); } return 0; } /** * mono_declsec_flags_from_class: * \param klass The class for which we want the declarative security flags. * Get the security actions (in the form of flags) associated with the specified class. * We cache the flags inside the \c MonoClass structure as this will get * called very often (at least for each method). * \returns the declarative security flags for the class. */ guint32 mono_declsec_flags_from_class (MonoClass *klass) { if (mono_class_get_flags (klass) & TYPE_ATTRIBUTE_HAS_SECURITY) { guint32 flags = mono_class_get_declsec_flags (klass); if (!flags) { guint32 idx; idx = mono_metadata_token_index (m_class_get_type_token (klass)); idx <<= MONO_HAS_DECL_SECURITY_BITS; idx |= MONO_HAS_DECL_SECURITY_TYPEDEF; flags = mono_declsec_get_flags (m_class_get_image (klass), idx); /* we cache the flags on classes */ mono_class_set_declsec_flags (klass, flags); } return flags; } return 0; } /** * mono_declsec_flags_from_assembly: * \param assembly The assembly for which we want the declarative security flags. * Get the security actions (in the form of flags) associated with the specified assembly. * \returns the declarative security flags for the assembly. */ guint32 mono_declsec_flags_from_assembly (MonoAssembly *assembly) { guint32 idx = 1; /* there is only one assembly */ idx <<= MONO_HAS_DECL_SECURITY_BITS; idx |= MONO_HAS_DECL_SECURITY_ASSEMBLY; return mono_declsec_get_flags (assembly->image, idx); } /* * Fill actions for the specific index (which may either be an encoded class token or * an encoded method token) from the metadata image. * Returns TRUE if some actions requiring code generation are present, FALSE otherwise. */ static MonoBoolean fill_actions_from_index (MonoImage *image, guint32 token, MonoDeclSecurityActions* actions, guint32 id_std, guint32 id_noncas, guint32 id_choice) { MonoBoolean result = FALSE; MonoTableInfo *t; guint32 cols [MONO_DECL_SECURITY_SIZE]; int index = mono_metadata_declsec_from_index (image, token); int i; t = &image->tables [MONO_TABLE_DECLSECURITY]; int rows = table_info_get_rows (t); for (i = index; i < rows; i++) { mono_metadata_decode_row (t, i, cols, MONO_DECL_SECURITY_SIZE); if (cols [MONO_DECL_SECURITY_PARENT] != token) return result; /* if present only replace (class) permissions with method permissions */ /* if empty accept either class or method permissions */ if (cols [MONO_DECL_SECURITY_ACTION] == id_std) { if (!actions->demand.blob) { const char *blob = mono_metadata_blob_heap (image, cols [MONO_DECL_SECURITY_PERMISSIONSET]); actions->demand.index = cols [MONO_DECL_SECURITY_PERMISSIONSET]; actions->demand.blob = (char*) (blob + 2); actions->demand.size = mono_metadata_decode_blob_size (blob, &blob); result = TRUE; } } else if (cols [MONO_DECL_SECURITY_ACTION] == id_noncas) { if (!actions->noncasdemand.blob) { const char *blob = mono_metadata_blob_heap (image, cols [MONO_DECL_SECURITY_PERMISSIONSET]); actions->noncasdemand.index = cols [MONO_DECL_SECURITY_PERMISSIONSET]; actions->noncasdemand.blob = (char*) (blob + 2); actions->noncasdemand.size = mono_metadata_decode_blob_size (blob, &blob); result = TRUE; } } else if (cols [MONO_DECL_SECURITY_ACTION] == id_choice) { if (!actions->demandchoice.blob) { const char *blob = mono_metadata_blob_heap (image, cols [MONO_DECL_SECURITY_PERMISSIONSET]); actions->demandchoice.index = cols [MONO_DECL_SECURITY_PERMISSIONSET]; actions->demandchoice.blob = (char*) (blob + 2); actions->demandchoice.size = mono_metadata_decode_blob_size (blob, &blob); result = TRUE; } } } return result; } static MonoBoolean mono_declsec_get_class_demands_params (MonoClass *klass, MonoDeclSecurityActions* demands, guint32 id_std, guint32 id_noncas, guint32 id_choice) { guint32 idx = mono_metadata_token_index (m_class_get_type_token (klass)); idx <<= MONO_HAS_DECL_SECURITY_BITS; idx |= MONO_HAS_DECL_SECURITY_TYPEDEF; return fill_actions_from_index (m_class_get_image (klass), idx, demands, id_std, id_noncas, id_choice); } static MonoBoolean mono_declsec_get_method_demands_params (MonoMethod *method, MonoDeclSecurityActions* demands, guint32 id_std, guint32 id_noncas, guint32 id_choice) { guint32 idx = mono_method_get_index (method); idx <<= MONO_HAS_DECL_SECURITY_BITS; idx |= MONO_HAS_DECL_SECURITY_METHODDEF; return fill_actions_from_index (m_class_get_image (method->klass), idx, demands, id_std, id_noncas, id_choice); } /** * mono_declsec_get_demands: * Collect all actions (that requires to generate code in mini) assigned for * the specified method. * Don't use the content of actions if the function return FALSE. */ MonoBoolean mono_declsec_get_demands (MonoMethod *method, MonoDeclSecurityActions* demands) { guint32 mask = MONO_DECLSEC_FLAG_DEMAND | MONO_DECLSEC_FLAG_NONCAS_DEMAND | MONO_DECLSEC_FLAG_DEMAND_CHOICE; MonoBoolean result = FALSE; guint32 flags; /* quick exit if no declarative security is present in the metadata */ if (!table_info_get_rows (&m_class_get_image (method->klass)->tables [MONO_TABLE_DECLSECURITY])) return FALSE; /* we want the original as the wrapper is "free" of the security informations */ if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE || method->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) { method = mono_marshal_method_from_wrapper (method); if (!method) return FALSE; } /* First we look for method-level attributes */ if (method->flags & METHOD_ATTRIBUTE_HAS_SECURITY) { mono_class_init_internal (method->klass); memset (demands, 0, sizeof (MonoDeclSecurityActions)); result = mono_declsec_get_method_demands_params (method, demands, SECURITY_ACTION_DEMAND, SECURITY_ACTION_NONCASDEMAND, SECURITY_ACTION_DEMANDCHOICE); } /* Here we use (or create) the class declarative cache to look for demands */ flags = mono_declsec_flags_from_class (method->klass); if (flags & mask) { if (!result) { mono_class_init_internal (method->klass); memset (demands, 0, sizeof (MonoDeclSecurityActions)); } result |= mono_declsec_get_class_demands_params (method->klass, demands, SECURITY_ACTION_DEMAND, SECURITY_ACTION_NONCASDEMAND, SECURITY_ACTION_DEMANDCHOICE); } /* The boolean return value is used as a shortcut in case nothing needs to be generated (e.g. LinkDemand[Choice] and InheritanceDemand[Choice]) */ return result; } /** * mono_declsec_get_linkdemands: * Collect all Link actions: \c LinkDemand, \c NonCasLinkDemand and \c LinkDemandChoice (2.0). * Don't use the content of actions if the function return FALSE. */ MonoBoolean mono_declsec_get_linkdemands (MonoMethod *method, MonoDeclSecurityActions* klass, MonoDeclSecurityActions *cmethod) { MonoBoolean result = FALSE; guint32 flags; /* quick exit if no declarative security is present in the metadata */ if (!table_info_get_rows (&m_class_get_image (method->klass)->tables [MONO_TABLE_DECLSECURITY])) return FALSE; /* we want the original as the wrapper is "free" of the security informations */ if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE || method->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) { method = mono_marshal_method_from_wrapper (method); if (!method) return FALSE; } /* results are independant - zeroize both */ memset (cmethod, 0, sizeof (MonoDeclSecurityActions)); memset (klass, 0, sizeof (MonoDeclSecurityActions)); /* First we look for method-level attributes */ if (method->flags & METHOD_ATTRIBUTE_HAS_SECURITY) { mono_class_init_internal (method->klass); result = mono_declsec_get_method_demands_params (method, cmethod, SECURITY_ACTION_LINKDEMAND, SECURITY_ACTION_NONCASLINKDEMAND, SECURITY_ACTION_LINKDEMANDCHOICE); } /* Here we use (or create) the class declarative cache to look for demands */ flags = mono_declsec_flags_from_class (method->klass); if (flags & (MONO_DECLSEC_FLAG_LINKDEMAND | MONO_DECLSEC_FLAG_NONCAS_LINKDEMAND | MONO_DECLSEC_FLAG_LINKDEMAND_CHOICE)) { mono_class_init_internal (method->klass); result |= mono_declsec_get_class_demands_params (method->klass, klass, SECURITY_ACTION_LINKDEMAND, SECURITY_ACTION_NONCASLINKDEMAND, SECURITY_ACTION_LINKDEMANDCHOICE); } return result; } /** * mono_declsec_get_inheritdemands_class: * \param klass The inherited class - this is the class that provides the security check (attributes) * \param demands * Collect all Inherit actions - \c InheritanceDemand, \c NonCasInheritanceDemand and \c InheritanceDemandChoice (2.0). * Don't use the content of actions if the function return FALSE. * \returns TRUE if inheritance demands (any kind) are present, FALSE otherwise. */ MonoBoolean mono_declsec_get_inheritdemands_class (MonoClass *klass, MonoDeclSecurityActions* demands) { MonoBoolean result = FALSE; guint32 flags; /* quick exit if no declarative security is present in the metadata */ if (!table_info_get_rows (&m_class_get_image (klass)->tables [MONO_TABLE_DECLSECURITY])) return FALSE; /* Here we use (or create) the class declarative cache to look for demands */ flags = mono_declsec_flags_from_class (klass); if (flags & (MONO_DECLSEC_FLAG_INHERITANCEDEMAND | MONO_DECLSEC_FLAG_NONCAS_INHERITANCEDEMAND | MONO_DECLSEC_FLAG_INHERITANCEDEMAND_CHOICE)) { mono_class_init_internal (klass); memset (demands, 0, sizeof (MonoDeclSecurityActions)); result |= mono_declsec_get_class_demands_params (klass, demands, SECURITY_ACTION_INHERITDEMAND, SECURITY_ACTION_NONCASINHERITANCE, SECURITY_ACTION_INHERITDEMANDCHOICE); } return result; } /** * mono_declsec_get_inheritdemands_method: * Collect all Inherit actions: \c InheritanceDemand, \c NonCasInheritanceDemand and \c InheritanceDemandChoice (2.0). * Don't use the content of actions if the function return FALSE. */ MonoBoolean mono_declsec_get_inheritdemands_method (MonoMethod *method, MonoDeclSecurityActions* demands) { /* quick exit if no declarative security is present in the metadata */ if (!table_info_get_rows (&m_class_get_image (method->klass)->tables [MONO_TABLE_DECLSECURITY])) return FALSE; /* we want the original as the wrapper is "free" of the security informations */ if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE || method->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) { method = mono_marshal_method_from_wrapper (method); if (!method) return FALSE; } if (method->flags & METHOD_ATTRIBUTE_HAS_SECURITY) { mono_class_init_internal (method->klass); memset (demands, 0, sizeof (MonoDeclSecurityActions)); return mono_declsec_get_method_demands_params (method, demands, SECURITY_ACTION_INHERITDEMAND, SECURITY_ACTION_NONCASINHERITANCE, SECURITY_ACTION_INHERITDEMANDCHOICE); } return FALSE; } static MonoBoolean get_declsec_action (MonoImage *image, guint32 token, guint32 action, MonoDeclSecurityEntry *entry) { guint32 cols [MONO_DECL_SECURITY_SIZE]; int i; int index = mono_metadata_declsec_from_index (image, token); if (index == -1) return FALSE; MonoTableInfo *t = &image->tables [MONO_TABLE_DECLSECURITY]; int rows = table_info_get_rows (t); for (i = index; i < rows; i++) { mono_metadata_decode_row (t, i, cols, MONO_DECL_SECURITY_SIZE); /* shortcut - index are ordered */ if (token != cols [MONO_DECL_SECURITY_PARENT]) return FALSE; if (cols [MONO_DECL_SECURITY_ACTION] == action) { const char *metadata = mono_metadata_blob_heap (image, cols [MONO_DECL_SECURITY_PERMISSIONSET]); entry->blob = (char*) (metadata + 2); entry->size = mono_metadata_decode_blob_size (metadata, &metadata); return TRUE; } } return FALSE; } MonoBoolean mono_declsec_get_method_action (MonoMethod *method, guint32 action, MonoDeclSecurityEntry *entry) { if (method->flags & METHOD_ATTRIBUTE_HAS_SECURITY) { guint32 idx = mono_method_get_index (method); idx <<= MONO_HAS_DECL_SECURITY_BITS; idx |= MONO_HAS_DECL_SECURITY_METHODDEF; return get_declsec_action (m_class_get_image (method->klass), idx, action, entry); } return FALSE; } /** * mono_declsec_get_class_action: */ MonoBoolean mono_declsec_get_class_action (MonoClass *klass, guint32 action, MonoDeclSecurityEntry *entry) { /* use cache */ guint32 flags = mono_declsec_flags_from_class (klass); if (declsec_flags_map [action] & flags) { guint32 idx = mono_metadata_token_index (m_class_get_type_token (klass)); idx <<= MONO_HAS_DECL_SECURITY_BITS; idx |= MONO_HAS_DECL_SECURITY_TYPEDEF; return get_declsec_action (m_class_get_image (klass), idx, action, entry); } return FALSE; } /** * mono_declsec_get_assembly_action: */ MonoBoolean mono_declsec_get_assembly_action (MonoAssembly *assembly, guint32 action, MonoDeclSecurityEntry *entry) { guint32 idx = 1; /* there is only one assembly */ idx <<= MONO_HAS_DECL_SECURITY_BITS; idx |= MONO_HAS_DECL_SECURITY_ASSEMBLY; return get_declsec_action (assembly->image, idx, action, entry); } gboolean mono_reflection_call_is_assignable_to (MonoClass *klass, MonoClass *oklass, MonoError *error) { MonoObject *res, *exc; void *params [1]; static MonoMethod *method = NULL; error_init (error); if (method == NULL) { method = mono_class_get_method_from_name_checked (mono_class_get_type_builder_class (), "IsAssignableToInternal", 1, 0, error); mono_error_assert_ok (error); g_assert (method); } /* * The result of mono_type_get_object_checked () might be a System.MonoType but we * need a TypeBuilder so use mono_class_get_ref_info (klass). */ g_assert (mono_class_has_ref_info (klass)); g_assert (!strcmp (m_class_get_name (mono_object_class (&mono_class_get_ref_info_raw (klass)->type.object)), "TypeBuilder")); /* FIXME use handles */ params [0] = mono_type_get_object_checked (m_class_get_byval_arg (oklass), error); return_val_if_nok (error, FALSE); ERROR_DECL (inner_error); res = mono_runtime_try_invoke (method, &mono_class_get_ref_info_raw (klass)->type.object, params, &exc, inner_error); /* FIXME use handles */ if (exc || !is_ok (inner_error)) { mono_error_cleanup (inner_error); return FALSE; } else return *(MonoBoolean*)mono_object_unbox_internal (res); } /** * mono_reflection_type_get_type: * \param reftype the \c System.Type object * \returns the \c MonoType* associated with the C# \c System.Type object \p reftype. */ MonoType* mono_reflection_type_get_type (MonoReflectionType *reftype) { MonoType *result; MONO_ENTER_GC_UNSAFE; g_assert (reftype); ERROR_DECL (error); result = mono_reflection_type_get_handle (reftype, error); mono_error_assert_ok (error); MONO_EXIT_GC_UNSAFE; return result; } /** * mono_reflection_assembly_get_assembly: * \param refassembly the \c System.Reflection.Assembly object * \returns the \c MonoAssembly* associated with the C# \c System.Reflection.Assembly object \p refassembly. */ MonoAssembly* mono_reflection_assembly_get_assembly (MonoReflectionAssembly *refassembly) { g_assert (refassembly); return refassembly->assembly; } /** * mono_class_from_mono_type_handle: * \param reftype the \c System.Type handle * \returns the \c MonoClass* corresponding to the given type. */ MonoClass* mono_class_from_mono_type_handle (MonoReflectionTypeHandle reftype) { return mono_class_from_mono_type_internal (MONO_HANDLE_RAW (reftype)->type); } // This is called by icalls, it will return NULL and set pending exception (in wrapper) on failure. MonoReflectionTypeHandle mono_type_from_handle_impl (MonoType *handle, MonoError *error) { mono_class_init_internal (mono_class_from_mono_type_internal (handle)); return mono_type_get_object_handle (handle, error); }
-1
dotnet/runtime
66,462
Support using the system version of brotli
This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
omajid
2022-03-10T17:19:11Z
2022-03-23T03:49:50Z
c3e1d21c2fb30436ae24ef7ef4f458e3270bb7e3
5ca9223639700750ff12bb1fed9fa6e397062b78
Support using the system version of brotli . This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
./src/native/external/libunwind/src/ppc32/Lregs.c
#define UNW_LOCAL_ONLY #include <libunwind.h> #if defined(UNW_LOCAL_ONLY) && !defined(UNW_REMOTE_ONLY) #include "Gregs.c" #endif
#define UNW_LOCAL_ONLY #include <libunwind.h> #if defined(UNW_LOCAL_ONLY) && !defined(UNW_REMOTE_ONLY) #include "Gregs.c" #endif
-1
dotnet/runtime
66,462
Support using the system version of brotli
This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
omajid
2022-03-10T17:19:11Z
2022-03-23T03:49:50Z
c3e1d21c2fb30436ae24ef7ef4f458e3270bb7e3
5ca9223639700750ff12bb1fed9fa6e397062b78
Support using the system version of brotli . This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
./src/libraries/System.Private.Xml/tests/Xslt/TestFiles/TestData/XsltApiV2/baseline/MyObject_Recursion.txt
<result xmlns:myObj="urn:my-object">Recursive Function Returning the factorial of five:120</result>
<result xmlns:myObj="urn:my-object">Recursive Function Returning the factorial of five:120</result>
-1
dotnet/runtime
66,462
Support using the system version of brotli
This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
omajid
2022-03-10T17:19:11Z
2022-03-23T03:49:50Z
c3e1d21c2fb30436ae24ef7ef4f458e3270bb7e3
5ca9223639700750ff12bb1fed9fa6e397062b78
Support using the system version of brotli . This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
./src/libraries/System.Private.Xml/tests/Xslt/TestFiles/TestData/xsltc/baseline/sft1.txt
<?xml version="1.0" encoding="utf-8"?><testOut> Let's see if we can resolve entities: RESOLVED_ENTITY </testOut>
<?xml version="1.0" encoding="utf-8"?><testOut> Let's see if we can resolve entities: RESOLVED_ENTITY </testOut>
-1
dotnet/runtime
66,462
Support using the system version of brotli
This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
omajid
2022-03-10T17:19:11Z
2022-03-23T03:49:50Z
c3e1d21c2fb30436ae24ef7ef4f458e3270bb7e3
5ca9223639700750ff12bb1fed9fa6e397062b78
Support using the system version of brotli . This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
./src/native/libs/System.Security.Cryptography.Native.Android/pal_cipher.c
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include "pal_cipher.h" #include "pal_utilities.h" enum { CIPHER_NONE = 0, CIPHER_HAS_VARIABLE_TAG = 1, CIPHER_REQUIRES_IV = 2, }; typedef uint32_t CipherFlags; typedef struct CipherInfo { CipherFlags flags; int32_t width; const char* name; } CipherInfo; #define DEFINE_CIPHER(cipherId, width, javaName, flags) \ CipherInfo* AndroidCryptoNative_ ## cipherId() \ { \ static CipherInfo info = { flags, width, javaName }; \ return &info; \ } DEFINE_CIPHER(Aes128Ecb, 128, "AES/ECB/NoPadding", CIPHER_NONE) DEFINE_CIPHER(Aes128Cbc, 128, "AES/CBC/NoPadding", CIPHER_REQUIRES_IV) DEFINE_CIPHER(Aes128Cfb8, 128, "AES/CFB8/NoPadding", CIPHER_REQUIRES_IV) DEFINE_CIPHER(Aes128Cfb128, 128, "AES/CFB128/NoPadding", CIPHER_REQUIRES_IV) DEFINE_CIPHER(Aes128Gcm, 128, "AES/GCM/NoPadding", CIPHER_HAS_VARIABLE_TAG | CIPHER_REQUIRES_IV) DEFINE_CIPHER(Aes128Ccm, 128, "AES/CCM/NoPadding", CIPHER_HAS_VARIABLE_TAG | CIPHER_REQUIRES_IV) DEFINE_CIPHER(Aes192Ecb, 192, "AES/ECB/NoPadding", CIPHER_NONE) DEFINE_CIPHER(Aes192Cbc, 192, "AES/CBC/NoPadding", CIPHER_REQUIRES_IV) DEFINE_CIPHER(Aes192Cfb8, 192, "AES/CFB8/NoPadding", CIPHER_REQUIRES_IV) DEFINE_CIPHER(Aes192Cfb128, 192, "AES/CFB128/NoPadding", CIPHER_REQUIRES_IV) DEFINE_CIPHER(Aes192Gcm, 192, "AES/GCM/NoPadding", CIPHER_HAS_VARIABLE_TAG | CIPHER_REQUIRES_IV) DEFINE_CIPHER(Aes192Ccm, 192, "AES/CCM/NoPadding", CIPHER_HAS_VARIABLE_TAG | CIPHER_REQUIRES_IV) DEFINE_CIPHER(Aes256Ecb, 256, "AES/ECB/NoPadding", CIPHER_NONE) DEFINE_CIPHER(Aes256Cbc, 256, "AES/CBC/NoPadding", CIPHER_REQUIRES_IV) DEFINE_CIPHER(Aes256Cfb8, 256, "AES/CFB8/NoPadding", CIPHER_REQUIRES_IV) DEFINE_CIPHER(Aes256Cfb128, 256, "AES/CFB128/NoPadding", CIPHER_REQUIRES_IV) DEFINE_CIPHER(Aes256Gcm, 256, "AES/GCM/NoPadding", CIPHER_HAS_VARIABLE_TAG | CIPHER_REQUIRES_IV) DEFINE_CIPHER(Aes256Ccm, 256, "AES/CCM/NoPadding", CIPHER_HAS_VARIABLE_TAG | CIPHER_REQUIRES_IV) DEFINE_CIPHER(DesEcb, 64, "DES/ECB/NoPadding", CIPHER_NONE) DEFINE_CIPHER(DesCbc, 64, "DES/CBC/NoPadding", CIPHER_REQUIRES_IV) DEFINE_CIPHER(DesCfb8, 64, "DES/CFB8/NoPadding", CIPHER_REQUIRES_IV) DEFINE_CIPHER(Des3Ecb, 128, "DESede/ECB/NoPadding", CIPHER_NONE) DEFINE_CIPHER(Des3Cbc, 128, "DESede/CBC/NoPadding", CIPHER_REQUIRES_IV) DEFINE_CIPHER(Des3Cfb8, 128, "DESede/CFB8/NoPadding", CIPHER_REQUIRES_IV) DEFINE_CIPHER(Des3Cfb64, 128, "DESede/CFB/NoPadding", CIPHER_REQUIRES_IV) DEFINE_CIPHER(ChaCha20Poly1305, 256, "ChaCha20/Poly1305/NoPadding", CIPHER_REQUIRES_IV) // // We don't have to check whether `CipherInfo` arguments are valid pointers, as these functions will be called after the // context is created and the type stored in `CipherInfo` is asserted to be not NULL on creation time. Managed code // cannot modify the context so it's fairly safe to assume that we're passed a valid pointer here. // // The entry functions (those that can be called by external code) take care to validate that the context passed to them // is a valid pointer and so we can assume the assertion from the preceding paragraph. // ARGS_NON_NULL_ALL static bool HasVariableTag(CipherInfo* type) { return (type->flags & CIPHER_HAS_VARIABLE_TAG) == CIPHER_HAS_VARIABLE_TAG; } ARGS_NON_NULL_ALL static bool RequiresIV(CipherInfo* type) { return (type->flags & CIPHER_REQUIRES_IV) == CIPHER_REQUIRES_IV; } ARGS_NON_NULL_ALL static jobject GetAlgorithmName(JNIEnv* env, CipherInfo* type) { return make_java_string(env, type->name); } int32_t AndroidCryptoNative_CipherIsSupported(CipherInfo* type) { abort_if_invalid_pointer_argument (type); JNIEnv* env = GetJNIEnv(); jobject algName = GetAlgorithmName(env, type); if (!algName) return FAIL; jobject cipher = (*env)->CallStaticObjectMethod(env, g_cipherClass, g_cipherGetInstanceMethod, algName); (*env)->DeleteLocalRef(env, algName); (*env)->DeleteLocalRef(env, cipher); // If we were able to call Cipher.getInstance without an exception, like NoSuchAlgorithmException, // then the algorithm is supported. return TryClearJNIExceptions(env) ? FAIL : SUCCESS; } CipherCtx* AndroidCryptoNative_CipherCreatePartial(CipherInfo* type) { abort_if_invalid_pointer_argument (type); JNIEnv* env = GetJNIEnv(); jobject algName = GetAlgorithmName(env, type); if (!algName) return FAIL; jobject cipher = ToGRef(env, (*env)->CallStaticObjectMethod(env, g_cipherClass, g_cipherGetInstanceMethod, algName)); (*env)->DeleteLocalRef(env, algName); if (CheckJNIExceptions(env)) { return FAIL; } CipherCtx* ctx = xmalloc(sizeof(CipherCtx)); ctx->cipher = cipher; ctx->type = type; ctx->tagLength = TAG_MAX_LENGTH; ctx->keySizeInBits = type->width; ctx->ivLength = 0; ctx->encMode = 0; ctx->key = NULL; ctx->iv = NULL; return ctx; } int32_t AndroidCryptoNative_CipherSetTagLength(CipherCtx* ctx, int32_t tagLength) { if (!ctx) return FAIL; if(tagLength > TAG_MAX_LENGTH) return FAIL; ctx->tagLength = tagLength; return SUCCESS; } ARGS_NON_NULL_ALL static int32_t ReinitializeCipher(CipherCtx* ctx) { JNIEnv* env = GetJNIEnv(); // SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), "AES"); // IvParameterSpec ivSpec = new IvParameterSpec(IV); or GCMParameterSpec for GCM/CCM // cipher.init(encMode, keySpec, ivSpec); jobject algName = GetAlgorithmName(env, ctx->type); if (!algName) return FAIL; int32_t keyLength = ctx->keySizeInBits / 8; jbyteArray keyBytes = make_java_byte_array(env, keyLength); (*env)->SetByteArrayRegion(env, keyBytes, 0, keyLength, (jbyte*)ctx->key); jobject sksObj = (*env)->NewObject(env, g_sksClass, g_sksCtor, keyBytes, algName); jobject ivPsObj = NULL; if (RequiresIV(ctx->type)) { jbyteArray ivBytes = make_java_byte_array(env, ctx->ivLength); (*env)->SetByteArrayRegion(env, ivBytes, 0, ctx->ivLength, (jbyte*)ctx->iv); if (HasVariableTag(ctx->type)) { ivPsObj = (*env)->NewObject(env, g_GCMParameterSpecClass, g_GCMParameterSpecCtor, ctx->tagLength * 8, ivBytes); } else { ivPsObj = (*env)->NewObject(env, g_ivPsClass, g_ivPsCtor, ivBytes); } (*env)->DeleteLocalRef(env, ivBytes); } (*env)->CallVoidMethod(env, ctx->cipher, g_cipherInitMethod, ctx->encMode, sksObj, ivPsObj); (*env)->DeleteLocalRef(env, algName); (*env)->DeleteLocalRef(env, sksObj); (*env)->DeleteLocalRef(env, ivPsObj); (*env)->DeleteLocalRef(env, keyBytes); return CheckJNIExceptions(env) ? FAIL : SUCCESS; } int32_t AndroidCryptoNative_CipherSetKeyAndIV(CipherCtx* ctx, uint8_t* key, uint8_t* iv, int32_t enc) { if (!ctx) return FAIL; // input: 0 for Decrypt, 1 for Encrypt, -1 leave untouched // Cipher: 2 for Decrypt, 1 for Encrypt, N/A if (enc != -1) { abort_unless(enc == 0 || enc == 1, "The 'enc' parameter must be either 1 or 0"); ctx->encMode = enc == 0 ? CIPHER_DECRYPT_MODE : CIPHER_ENCRYPT_MODE; } // CryptoNative_CipherSetKeyAndIV can be called separately for key and iv // so we need to wait for both and do Init after. if (key) SaveTo(key, &ctx->key, (size_t)ctx->keySizeInBits / 8, /* overwrite */ true); if (iv) { // Make sure length is set if (!ctx->ivLength) { // ivLength = cipher.getBlockSize(); JNIEnv *env = GetJNIEnv(); ctx->ivLength = (*env)->CallIntMethod(env, ctx->cipher, g_getBlockSizeMethod); } SaveTo(iv, &ctx->iv, (size_t)ctx->ivLength, /* overwrite */ true); } if (!ctx->key || (!ctx->iv && RequiresIV(ctx->type))) return SUCCESS; return ReinitializeCipher(ctx); } CipherCtx* AndroidCryptoNative_CipherCreate(CipherInfo* type, uint8_t* key, int32_t keySizeInBits, uint8_t* iv, int32_t enc) { CipherCtx* ctx = AndroidCryptoNative_CipherCreatePartial(type); // Update the key size if provided if (keySizeInBits > 0) ctx->keySizeInBits = keySizeInBits; if (AndroidCryptoNative_CipherSetKeyAndIV(ctx, key, iv, enc) != SUCCESS) return FAIL; return ctx; } int32_t AndroidCryptoNative_CipherUpdateAAD(CipherCtx* ctx, uint8_t* in, int32_t inl) { if (!ctx) return FAIL; abort_if_invalid_pointer_argument(in); JNIEnv* env = GetJNIEnv(); jbyteArray inDataBytes = make_java_byte_array(env, inl); (*env)->SetByteArrayRegion(env, inDataBytes, 0, inl, (jbyte*)in); (*env)->CallVoidMethod(env, ctx->cipher, g_cipherUpdateAADMethod, inDataBytes); (*env)->DeleteLocalRef(env, inDataBytes); return CheckJNIExceptions(env) ? FAIL : SUCCESS; } int32_t AndroidCryptoNative_CipherUpdate(CipherCtx* ctx, uint8_t* outm, int32_t* outl, uint8_t* in, int32_t inl) { if (!ctx) return FAIL; if (!outl && !in) // it means caller wants us to record "inl" but we don't need it. return SUCCESS; abort_if_invalid_pointer_argument(outl); abort_if_invalid_pointer_argument(in); JNIEnv* env = GetJNIEnv(); jbyteArray inDataBytes = make_java_byte_array(env, inl); (*env)->SetByteArrayRegion(env, inDataBytes, 0, inl, (jbyte*)in); *outl = 0; jbyteArray outDataBytes = (jbyteArray)(*env)->CallObjectMethod(env, ctx->cipher, g_cipherUpdateMethod, inDataBytes); if (outDataBytes && outm) { jsize outDataBytesLen = (*env)->GetArrayLength(env, outDataBytes); *outl = outDataBytesLen; (*env)->GetByteArrayRegion(env, outDataBytes, 0, outDataBytesLen, (jbyte*) outm); (*env)->DeleteLocalRef(env, outDataBytes); } (*env)->DeleteLocalRef(env, inDataBytes); return CheckJNIExceptions(env) ? FAIL : SUCCESS; } int32_t AndroidCryptoNative_CipherFinalEx(CipherCtx* ctx, uint8_t* outm, int32_t* outl) { if (!ctx) return FAIL; abort_if_invalid_pointer_argument(outm); abort_if_invalid_pointer_argument(outl); JNIEnv* env = GetJNIEnv(); *outl = 0; jbyteArray outBytes = (jbyteArray)(*env)->CallObjectMethod(env, ctx->cipher, g_cipherDoFinalMethod); if (CheckJNIExceptions(env)) return FAIL; jsize outBytesLen = (*env)->GetArrayLength(env, outBytes); *outl = outBytesLen; (*env)->GetByteArrayRegion(env, outBytes, 0, outBytesLen, (jbyte*) outm); (*env)->DeleteLocalRef(env, outBytes); return CheckJNIExceptions(env) ? FAIL : SUCCESS; } int32_t AndroidCryptoNative_CipherCtxSetPadding(CipherCtx* ctx, int32_t padding) { if (!ctx) return FAIL; if (padding == 0) { return SUCCESS; } else { // TODO: re-init ctx->cipher ? LOG_ERROR("Non-zero padding (%d) is not supported yet", (int)padding); return FAIL; } } int32_t AndroidCryptoNative_CipherReset(CipherCtx* ctx, uint8_t* pIv, int32_t cIv) { if (!ctx) return FAIL; JNIEnv* env = GetJNIEnv(); ReleaseGRef(env, ctx->cipher); jobject algName = GetAlgorithmName(env, ctx->type); if (!algName) return FAIL; // Resetting is only for the cipher, not the context. // We recreate and reinitialize a cipher with the same context. ctx->cipher = ToGRef(env, (*env)->CallStaticObjectMethod(env, g_cipherClass, g_cipherGetInstanceMethod, algName)); (*env)->DeleteLocalRef(env, algName); if (CheckJNIExceptions(env)) return FAIL; if (pIv) { if (ctx->ivLength != cIv) { return FAIL; } SaveTo(pIv, &ctx->iv, (size_t)ctx->ivLength, /* overwrite */ true); } else if (cIv != 0) { return FAIL; } return ReinitializeCipher(ctx); } int32_t AndroidCryptoNative_CipherSetNonceLength(CipherCtx* ctx, int32_t ivLength) { if (!ctx) return FAIL; ctx->ivLength = ivLength; return SUCCESS; } void AndroidCryptoNative_CipherDestroy(CipherCtx* ctx) { if (ctx) { JNIEnv* env = GetJNIEnv(); ReleaseGRef(env, ctx->cipher); free(ctx->key); free(ctx->iv); free(ctx); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include "pal_cipher.h" #include "pal_utilities.h" enum { CIPHER_NONE = 0, CIPHER_HAS_VARIABLE_TAG = 1, CIPHER_REQUIRES_IV = 2, }; typedef uint32_t CipherFlags; typedef struct CipherInfo { CipherFlags flags; int32_t width; const char* name; } CipherInfo; #define DEFINE_CIPHER(cipherId, width, javaName, flags) \ CipherInfo* AndroidCryptoNative_ ## cipherId() \ { \ static CipherInfo info = { flags, width, javaName }; \ return &info; \ } DEFINE_CIPHER(Aes128Ecb, 128, "AES/ECB/NoPadding", CIPHER_NONE) DEFINE_CIPHER(Aes128Cbc, 128, "AES/CBC/NoPadding", CIPHER_REQUIRES_IV) DEFINE_CIPHER(Aes128Cfb8, 128, "AES/CFB8/NoPadding", CIPHER_REQUIRES_IV) DEFINE_CIPHER(Aes128Cfb128, 128, "AES/CFB128/NoPadding", CIPHER_REQUIRES_IV) DEFINE_CIPHER(Aes128Gcm, 128, "AES/GCM/NoPadding", CIPHER_HAS_VARIABLE_TAG | CIPHER_REQUIRES_IV) DEFINE_CIPHER(Aes128Ccm, 128, "AES/CCM/NoPadding", CIPHER_HAS_VARIABLE_TAG | CIPHER_REQUIRES_IV) DEFINE_CIPHER(Aes192Ecb, 192, "AES/ECB/NoPadding", CIPHER_NONE) DEFINE_CIPHER(Aes192Cbc, 192, "AES/CBC/NoPadding", CIPHER_REQUIRES_IV) DEFINE_CIPHER(Aes192Cfb8, 192, "AES/CFB8/NoPadding", CIPHER_REQUIRES_IV) DEFINE_CIPHER(Aes192Cfb128, 192, "AES/CFB128/NoPadding", CIPHER_REQUIRES_IV) DEFINE_CIPHER(Aes192Gcm, 192, "AES/GCM/NoPadding", CIPHER_HAS_VARIABLE_TAG | CIPHER_REQUIRES_IV) DEFINE_CIPHER(Aes192Ccm, 192, "AES/CCM/NoPadding", CIPHER_HAS_VARIABLE_TAG | CIPHER_REQUIRES_IV) DEFINE_CIPHER(Aes256Ecb, 256, "AES/ECB/NoPadding", CIPHER_NONE) DEFINE_CIPHER(Aes256Cbc, 256, "AES/CBC/NoPadding", CIPHER_REQUIRES_IV) DEFINE_CIPHER(Aes256Cfb8, 256, "AES/CFB8/NoPadding", CIPHER_REQUIRES_IV) DEFINE_CIPHER(Aes256Cfb128, 256, "AES/CFB128/NoPadding", CIPHER_REQUIRES_IV) DEFINE_CIPHER(Aes256Gcm, 256, "AES/GCM/NoPadding", CIPHER_HAS_VARIABLE_TAG | CIPHER_REQUIRES_IV) DEFINE_CIPHER(Aes256Ccm, 256, "AES/CCM/NoPadding", CIPHER_HAS_VARIABLE_TAG | CIPHER_REQUIRES_IV) DEFINE_CIPHER(DesEcb, 64, "DES/ECB/NoPadding", CIPHER_NONE) DEFINE_CIPHER(DesCbc, 64, "DES/CBC/NoPadding", CIPHER_REQUIRES_IV) DEFINE_CIPHER(DesCfb8, 64, "DES/CFB8/NoPadding", CIPHER_REQUIRES_IV) DEFINE_CIPHER(Des3Ecb, 128, "DESede/ECB/NoPadding", CIPHER_NONE) DEFINE_CIPHER(Des3Cbc, 128, "DESede/CBC/NoPadding", CIPHER_REQUIRES_IV) DEFINE_CIPHER(Des3Cfb8, 128, "DESede/CFB8/NoPadding", CIPHER_REQUIRES_IV) DEFINE_CIPHER(Des3Cfb64, 128, "DESede/CFB/NoPadding", CIPHER_REQUIRES_IV) DEFINE_CIPHER(ChaCha20Poly1305, 256, "ChaCha20/Poly1305/NoPadding", CIPHER_REQUIRES_IV) // // We don't have to check whether `CipherInfo` arguments are valid pointers, as these functions will be called after the // context is created and the type stored in `CipherInfo` is asserted to be not NULL on creation time. Managed code // cannot modify the context so it's fairly safe to assume that we're passed a valid pointer here. // // The entry functions (those that can be called by external code) take care to validate that the context passed to them // is a valid pointer and so we can assume the assertion from the preceding paragraph. // ARGS_NON_NULL_ALL static bool HasVariableTag(CipherInfo* type) { return (type->flags & CIPHER_HAS_VARIABLE_TAG) == CIPHER_HAS_VARIABLE_TAG; } ARGS_NON_NULL_ALL static bool RequiresIV(CipherInfo* type) { return (type->flags & CIPHER_REQUIRES_IV) == CIPHER_REQUIRES_IV; } ARGS_NON_NULL_ALL static jobject GetAlgorithmName(JNIEnv* env, CipherInfo* type) { return make_java_string(env, type->name); } int32_t AndroidCryptoNative_CipherIsSupported(CipherInfo* type) { abort_if_invalid_pointer_argument (type); JNIEnv* env = GetJNIEnv(); jobject algName = GetAlgorithmName(env, type); if (!algName) return FAIL; jobject cipher = (*env)->CallStaticObjectMethod(env, g_cipherClass, g_cipherGetInstanceMethod, algName); (*env)->DeleteLocalRef(env, algName); (*env)->DeleteLocalRef(env, cipher); // If we were able to call Cipher.getInstance without an exception, like NoSuchAlgorithmException, // then the algorithm is supported. return TryClearJNIExceptions(env) ? FAIL : SUCCESS; } CipherCtx* AndroidCryptoNative_CipherCreatePartial(CipherInfo* type) { abort_if_invalid_pointer_argument (type); JNIEnv* env = GetJNIEnv(); jobject algName = GetAlgorithmName(env, type); if (!algName) return FAIL; jobject cipher = ToGRef(env, (*env)->CallStaticObjectMethod(env, g_cipherClass, g_cipherGetInstanceMethod, algName)); (*env)->DeleteLocalRef(env, algName); if (CheckJNIExceptions(env)) { return FAIL; } CipherCtx* ctx = xmalloc(sizeof(CipherCtx)); ctx->cipher = cipher; ctx->type = type; ctx->tagLength = TAG_MAX_LENGTH; ctx->keySizeInBits = type->width; ctx->ivLength = 0; ctx->encMode = 0; ctx->key = NULL; ctx->iv = NULL; return ctx; } int32_t AndroidCryptoNative_CipherSetTagLength(CipherCtx* ctx, int32_t tagLength) { if (!ctx) return FAIL; if(tagLength > TAG_MAX_LENGTH) return FAIL; ctx->tagLength = tagLength; return SUCCESS; } ARGS_NON_NULL_ALL static int32_t ReinitializeCipher(CipherCtx* ctx) { JNIEnv* env = GetJNIEnv(); // SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), "AES"); // IvParameterSpec ivSpec = new IvParameterSpec(IV); or GCMParameterSpec for GCM/CCM // cipher.init(encMode, keySpec, ivSpec); jobject algName = GetAlgorithmName(env, ctx->type); if (!algName) return FAIL; int32_t keyLength = ctx->keySizeInBits / 8; jbyteArray keyBytes = make_java_byte_array(env, keyLength); (*env)->SetByteArrayRegion(env, keyBytes, 0, keyLength, (jbyte*)ctx->key); jobject sksObj = (*env)->NewObject(env, g_sksClass, g_sksCtor, keyBytes, algName); jobject ivPsObj = NULL; if (RequiresIV(ctx->type)) { jbyteArray ivBytes = make_java_byte_array(env, ctx->ivLength); (*env)->SetByteArrayRegion(env, ivBytes, 0, ctx->ivLength, (jbyte*)ctx->iv); if (HasVariableTag(ctx->type)) { ivPsObj = (*env)->NewObject(env, g_GCMParameterSpecClass, g_GCMParameterSpecCtor, ctx->tagLength * 8, ivBytes); } else { ivPsObj = (*env)->NewObject(env, g_ivPsClass, g_ivPsCtor, ivBytes); } (*env)->DeleteLocalRef(env, ivBytes); } (*env)->CallVoidMethod(env, ctx->cipher, g_cipherInitMethod, ctx->encMode, sksObj, ivPsObj); (*env)->DeleteLocalRef(env, algName); (*env)->DeleteLocalRef(env, sksObj); (*env)->DeleteLocalRef(env, ivPsObj); (*env)->DeleteLocalRef(env, keyBytes); return CheckJNIExceptions(env) ? FAIL : SUCCESS; } int32_t AndroidCryptoNative_CipherSetKeyAndIV(CipherCtx* ctx, uint8_t* key, uint8_t* iv, int32_t enc) { if (!ctx) return FAIL; // input: 0 for Decrypt, 1 for Encrypt, -1 leave untouched // Cipher: 2 for Decrypt, 1 for Encrypt, N/A if (enc != -1) { abort_unless(enc == 0 || enc == 1, "The 'enc' parameter must be either 1 or 0"); ctx->encMode = enc == 0 ? CIPHER_DECRYPT_MODE : CIPHER_ENCRYPT_MODE; } // CryptoNative_CipherSetKeyAndIV can be called separately for key and iv // so we need to wait for both and do Init after. if (key) SaveTo(key, &ctx->key, (size_t)ctx->keySizeInBits / 8, /* overwrite */ true); if (iv) { // Make sure length is set if (!ctx->ivLength) { // ivLength = cipher.getBlockSize(); JNIEnv *env = GetJNIEnv(); ctx->ivLength = (*env)->CallIntMethod(env, ctx->cipher, g_getBlockSizeMethod); } SaveTo(iv, &ctx->iv, (size_t)ctx->ivLength, /* overwrite */ true); } if (!ctx->key || (!ctx->iv && RequiresIV(ctx->type))) return SUCCESS; return ReinitializeCipher(ctx); } CipherCtx* AndroidCryptoNative_CipherCreate(CipherInfo* type, uint8_t* key, int32_t keySizeInBits, uint8_t* iv, int32_t enc) { CipherCtx* ctx = AndroidCryptoNative_CipherCreatePartial(type); // Update the key size if provided if (keySizeInBits > 0) ctx->keySizeInBits = keySizeInBits; if (AndroidCryptoNative_CipherSetKeyAndIV(ctx, key, iv, enc) != SUCCESS) return FAIL; return ctx; } int32_t AndroidCryptoNative_CipherUpdateAAD(CipherCtx* ctx, uint8_t* in, int32_t inl) { if (!ctx) return FAIL; abort_if_invalid_pointer_argument(in); JNIEnv* env = GetJNIEnv(); jbyteArray inDataBytes = make_java_byte_array(env, inl); (*env)->SetByteArrayRegion(env, inDataBytes, 0, inl, (jbyte*)in); (*env)->CallVoidMethod(env, ctx->cipher, g_cipherUpdateAADMethod, inDataBytes); (*env)->DeleteLocalRef(env, inDataBytes); return CheckJNIExceptions(env) ? FAIL : SUCCESS; } int32_t AndroidCryptoNative_CipherUpdate(CipherCtx* ctx, uint8_t* outm, int32_t* outl, uint8_t* in, int32_t inl) { if (!ctx) return FAIL; if (!outl && !in) // it means caller wants us to record "inl" but we don't need it. return SUCCESS; abort_if_invalid_pointer_argument(outl); abort_if_invalid_pointer_argument(in); JNIEnv* env = GetJNIEnv(); jbyteArray inDataBytes = make_java_byte_array(env, inl); (*env)->SetByteArrayRegion(env, inDataBytes, 0, inl, (jbyte*)in); *outl = 0; jbyteArray outDataBytes = (jbyteArray)(*env)->CallObjectMethod(env, ctx->cipher, g_cipherUpdateMethod, inDataBytes); if (outDataBytes && outm) { jsize outDataBytesLen = (*env)->GetArrayLength(env, outDataBytes); *outl = outDataBytesLen; (*env)->GetByteArrayRegion(env, outDataBytes, 0, outDataBytesLen, (jbyte*) outm); (*env)->DeleteLocalRef(env, outDataBytes); } (*env)->DeleteLocalRef(env, inDataBytes); return CheckJNIExceptions(env) ? FAIL : SUCCESS; } int32_t AndroidCryptoNative_CipherFinalEx(CipherCtx* ctx, uint8_t* outm, int32_t* outl) { if (!ctx) return FAIL; abort_if_invalid_pointer_argument(outm); abort_if_invalid_pointer_argument(outl); JNIEnv* env = GetJNIEnv(); *outl = 0; jbyteArray outBytes = (jbyteArray)(*env)->CallObjectMethod(env, ctx->cipher, g_cipherDoFinalMethod); if (CheckJNIExceptions(env)) return FAIL; jsize outBytesLen = (*env)->GetArrayLength(env, outBytes); *outl = outBytesLen; (*env)->GetByteArrayRegion(env, outBytes, 0, outBytesLen, (jbyte*) outm); (*env)->DeleteLocalRef(env, outBytes); return CheckJNIExceptions(env) ? FAIL : SUCCESS; } int32_t AndroidCryptoNative_CipherCtxSetPadding(CipherCtx* ctx, int32_t padding) { if (!ctx) return FAIL; if (padding == 0) { return SUCCESS; } else { // TODO: re-init ctx->cipher ? LOG_ERROR("Non-zero padding (%d) is not supported yet", (int)padding); return FAIL; } } int32_t AndroidCryptoNative_CipherReset(CipherCtx* ctx, uint8_t* pIv, int32_t cIv) { if (!ctx) return FAIL; JNIEnv* env = GetJNIEnv(); ReleaseGRef(env, ctx->cipher); jobject algName = GetAlgorithmName(env, ctx->type); if (!algName) return FAIL; // Resetting is only for the cipher, not the context. // We recreate and reinitialize a cipher with the same context. ctx->cipher = ToGRef(env, (*env)->CallStaticObjectMethod(env, g_cipherClass, g_cipherGetInstanceMethod, algName)); (*env)->DeleteLocalRef(env, algName); if (CheckJNIExceptions(env)) return FAIL; if (pIv) { if (ctx->ivLength != cIv) { return FAIL; } SaveTo(pIv, &ctx->iv, (size_t)ctx->ivLength, /* overwrite */ true); } else if (cIv != 0) { return FAIL; } return ReinitializeCipher(ctx); } int32_t AndroidCryptoNative_CipherSetNonceLength(CipherCtx* ctx, int32_t ivLength) { if (!ctx) return FAIL; ctx->ivLength = ivLength; return SUCCESS; } void AndroidCryptoNative_CipherDestroy(CipherCtx* ctx) { if (ctx) { JNIEnv* env = GetJNIEnv(); ReleaseGRef(env, ctx->cipher); free(ctx->key); free(ctx->iv); free(ctx); } }
-1
dotnet/runtime
66,462
Support using the system version of brotli
This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
omajid
2022-03-10T17:19:11Z
2022-03-23T03:49:50Z
c3e1d21c2fb30436ae24ef7ef4f458e3270bb7e3
5ca9223639700750ff12bb1fed9fa6e397062b78
Support using the system version of brotli . This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
./src/coreclr/classlibnative/bcltype/CMakeLists.txt
set(CMAKE_INCLUDE_CURRENT_DIR ON) set(BCLTYPE_SOURCES arraynative.cpp oavariant.cpp objectnative.cpp stringnative.cpp system.cpp varargsnative.cpp variant.cpp ) add_library_clr(bcltype_obj OBJECT ${BCLTYPE_SOURCES} ) add_dependencies(bcltype_obj eventing_headers) add_library(bcltype INTERFACE) target_sources(bcltype INTERFACE $<TARGET_OBJECTS:bcltype_obj>)
set(CMAKE_INCLUDE_CURRENT_DIR ON) set(BCLTYPE_SOURCES arraynative.cpp oavariant.cpp objectnative.cpp stringnative.cpp system.cpp varargsnative.cpp variant.cpp ) add_library_clr(bcltype_obj OBJECT ${BCLTYPE_SOURCES} ) add_dependencies(bcltype_obj eventing_headers) add_library(bcltype INTERFACE) target_sources(bcltype INTERFACE $<TARGET_OBJECTS:bcltype_obj>)
-1
dotnet/runtime
66,462
Support using the system version of brotli
This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
omajid
2022-03-10T17:19:11Z
2022-03-23T03:49:50Z
c3e1d21c2fb30436ae24ef7ef4f458e3270bb7e3
5ca9223639700750ff12bb1fed9fa6e397062b78
Support using the system version of brotli . This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
./src/native/external/libunwind/tests/Lperf-trace.c
#define UNW_LOCAL_ONLY #include <libunwind.h> #if !defined(UNW_REMOTE_ONLY) #include "Gperf-trace.c" #endif
#define UNW_LOCAL_ONLY #include <libunwind.h> #if !defined(UNW_REMOTE_ONLY) #include "Gperf-trace.c" #endif
-1
dotnet/runtime
66,462
Support using the system version of brotli
This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
omajid
2022-03-10T17:19:11Z
2022-03-23T03:49:50Z
c3e1d21c2fb30436ae24ef7ef4f458e3270bb7e3
5ca9223639700750ff12bb1fed9fa6e397062b78
Support using the system version of brotli . This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
./src/libraries/System.Private.Xml/tests/Xslt/TestFiles/TestData/xsltc/baseline/bft11.txt
<?xml version="1.0" encoding="utf-8"?>Hello, world!
<?xml version="1.0" encoding="utf-8"?>Hello, world!
-1
dotnet/runtime
66,462
Support using the system version of brotli
This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
omajid
2022-03-10T17:19:11Z
2022-03-23T03:49:50Z
c3e1d21c2fb30436ae24ef7ef4f458e3270bb7e3
5ca9223639700750ff12bb1fed9fa6e397062b78
Support using the system version of brotli . This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
./src/libraries/System.DirectoryServices/src/Interop/AdsType.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.DirectoryServices.Interop { internal enum AdsType { ADSTYPE_INVALID = 0, ADSTYPE_DN_STRING = 1, ADSTYPE_CASE_EXACT_STRING = 2, ADSTYPE_CASE_IGNORE_STRING = 3, ADSTYPE_PRINTABLE_STRING = 4, ADSTYPE_NUMERIC_STRING = 5, ADSTYPE_BOOLEAN = 6, ADSTYPE_INTEGER = 7, ADSTYPE_OCTET_STRING = 8, ADSTYPE_UTC_TIME = 9, ADSTYPE_LARGE_INTEGER = 10, ADSTYPE_PROV_SPECIFIC = 11, ADSTYPE_OBJECT_CLASS = 12, ADSTYPE_CASEIGNORE_LIST = 13, ADSTYPE_OCTET_LIST = 14, ADSTYPE_PATH = 15, ADSTYPE_POSTALADDRESS = 16, ADSTYPE_TIMESTAMP = 17, ADSTYPE_BACKLINK = 18, ADSTYPE_TYPEDNAME = 19, ADSTYPE_HOLD = 20, ADSTYPE_NETADDRESS = 21, ADSTYPE_REPLICAPOINTER = 22, ADSTYPE_FAXNUMBER = 23, ADSTYPE_EMAIL = 24, ADSTYPE_NT_SECURITY_DESCRIPTOR = 25, ADSTYPE_UNKNOWN = 26, ADSTYPE_DN_WITH_BINARY = 27, ADSTYPE_DN_WITH_STRING = 28 } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.DirectoryServices.Interop { internal enum AdsType { ADSTYPE_INVALID = 0, ADSTYPE_DN_STRING = 1, ADSTYPE_CASE_EXACT_STRING = 2, ADSTYPE_CASE_IGNORE_STRING = 3, ADSTYPE_PRINTABLE_STRING = 4, ADSTYPE_NUMERIC_STRING = 5, ADSTYPE_BOOLEAN = 6, ADSTYPE_INTEGER = 7, ADSTYPE_OCTET_STRING = 8, ADSTYPE_UTC_TIME = 9, ADSTYPE_LARGE_INTEGER = 10, ADSTYPE_PROV_SPECIFIC = 11, ADSTYPE_OBJECT_CLASS = 12, ADSTYPE_CASEIGNORE_LIST = 13, ADSTYPE_OCTET_LIST = 14, ADSTYPE_PATH = 15, ADSTYPE_POSTALADDRESS = 16, ADSTYPE_TIMESTAMP = 17, ADSTYPE_BACKLINK = 18, ADSTYPE_TYPEDNAME = 19, ADSTYPE_HOLD = 20, ADSTYPE_NETADDRESS = 21, ADSTYPE_REPLICAPOINTER = 22, ADSTYPE_FAXNUMBER = 23, ADSTYPE_EMAIL = 24, ADSTYPE_NT_SECURITY_DESCRIPTOR = 25, ADSTYPE_UNKNOWN = 26, ADSTYPE_DN_WITH_BINARY = 27, ADSTYPE_DN_WITH_STRING = 28 } }
-1
dotnet/runtime
66,462
Support using the system version of brotli
This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
omajid
2022-03-10T17:19:11Z
2022-03-23T03:49:50Z
c3e1d21c2fb30436ae24ef7ef4f458e3270bb7e3
5ca9223639700750ff12bb1fed9fa6e397062b78
Support using the system version of brotli . This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
./src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/LicenseContext.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Reflection; namespace System.ComponentModel { /// <summary> /// Specifies when the licensed object can be used. /// </summary> public class LicenseContext : IServiceProvider { /// <summary> /// When overridden in a derived class, gets a value that specifies when a license can be used. /// </summary> public virtual LicenseUsageMode UsageMode => LicenseUsageMode.Runtime; /// <summary> /// When overridden in a derived class, gets a saved license /// key for the specified type, from the specified resource assembly. /// </summary> public virtual string? GetSavedLicenseKey(Type type, Assembly? resourceAssembly) => null; /// <summary> /// When overridden in a derived class, will return an object that implements the asked for service. /// </summary> public virtual object? GetService(Type type) => null; /// <summary> /// When overridden in a derived class, sets a license key for the specified type. /// </summary> public virtual void SetSavedLicenseKey(Type type, string key) { // no-op; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Reflection; namespace System.ComponentModel { /// <summary> /// Specifies when the licensed object can be used. /// </summary> public class LicenseContext : IServiceProvider { /// <summary> /// When overridden in a derived class, gets a value that specifies when a license can be used. /// </summary> public virtual LicenseUsageMode UsageMode => LicenseUsageMode.Runtime; /// <summary> /// When overridden in a derived class, gets a saved license /// key for the specified type, from the specified resource assembly. /// </summary> public virtual string? GetSavedLicenseKey(Type type, Assembly? resourceAssembly) => null; /// <summary> /// When overridden in a derived class, will return an object that implements the asked for service. /// </summary> public virtual object? GetService(Type type) => null; /// <summary> /// When overridden in a derived class, sets a license key for the specified type. /// </summary> public virtual void SetSavedLicenseKey(Type type, string key) { // no-op; } } }
-1
dotnet/runtime
66,462
Support using the system version of brotli
This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
omajid
2022-03-10T17:19:11Z
2022-03-23T03:49:50Z
c3e1d21c2fb30436ae24ef7ef4f458e3270bb7e3
5ca9223639700750ff12bb1fed9fa6e397062b78
Support using the system version of brotli . This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
./src/tests/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b16896/b16896.il
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. .assembly extern legacy library mscorlib {} .assembly extern System.Console { .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) .ver 4:0:0:0 } .assembly ILGEN_0x38e6a02d {} .class ILGEN_0x38e6a02d { .field static unsigned int64 field_0x3 .field static int16 field_0x5 .field static float32 field_0x8 .method static int32 main() { .entrypoint .maxstack 14 .locals (unsigned int8 local_0xa,unsigned int16 local_0xb,int16 local_0xd,int32 local_0xe,int64 local_0xf,float32 local_0x10) ldc.i4.0 stloc.0 ldc.i4.0 stloc.1 ldc.i4.0 stloc.2 ldc.i4.0 stloc.3 ldc.i8 0 stloc 4 ldc.r4 0 stloc 5 .try { ldc.i4 0x4a3e70aa stloc local_0xa ldc.i4 0x496a6b4f stloc local_0xd ldc.i4 0x3be55136 stloc local_0xe ldc.i8 0x38f9668b658c7c52 stloc local_0xf ldc.r4 float32(0x7b5d5f1c) stloc local_0x10 ldc.i8 0x2e955def5c8d4af1 stsfld unsigned int64 ILGEN_0x38e6a02d::field_0x3 ldc.i4 0x4fcc1252 stsfld int16 ILGEN_0x38e6a02d::field_0x5 ldc.r4 float32(0x7aa321fe) stsfld float32 ILGEN_0x38e6a02d::field_0x8 Start_Orphan_0: ldloc local_0xa conv.u1 newarr [mscorlib]System.UInt16 Start_Orphan_6: Start_Orphan_7: ldsfld unsigned int64 ILGEN_0x38e6a02d::field_0x3 stloc local_0xf End_Orphan_7: End_Orphan_6: ldsfld unsigned int64 ILGEN_0x38e6a02d::field_0x3 conv.ovf.i conv.r4 ldsfld float32 ILGEN_0x38e6a02d::field_0x8 mul conv.ovf.u4 ldelema [mscorlib]System.UInt16 pop End_Orphan_0: ldloc local_0x10 conv.ovf.u8 ldsflda unsigned int64 ILGEN_0x38e6a02d::field_0x3 ldind.u8 ldc.i4.1 conv.i8 mul.ovf or ldsfld int16 ILGEN_0x38e6a02d::field_0x5 ldloc local_0xb div conv.ovf.u8.un ldloc local_0xf conv.ovf.u8 ldc.i4.8 conv.ovf.i8 add.ovf sub.ovf div ldc.i4.s -88 ldloc local_0xe clt conv.ovf.u8.un mul.ovf.un conv.ovf.u1 conv.u1 pop leave Beyond } catch [mscorlib]System.OverflowException { pop leave Beyond } Beyond: ldc.i4 100 ret } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. .assembly extern legacy library mscorlib {} .assembly extern System.Console { .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) .ver 4:0:0:0 } .assembly ILGEN_0x38e6a02d {} .class ILGEN_0x38e6a02d { .field static unsigned int64 field_0x3 .field static int16 field_0x5 .field static float32 field_0x8 .method static int32 main() { .entrypoint .maxstack 14 .locals (unsigned int8 local_0xa,unsigned int16 local_0xb,int16 local_0xd,int32 local_0xe,int64 local_0xf,float32 local_0x10) ldc.i4.0 stloc.0 ldc.i4.0 stloc.1 ldc.i4.0 stloc.2 ldc.i4.0 stloc.3 ldc.i8 0 stloc 4 ldc.r4 0 stloc 5 .try { ldc.i4 0x4a3e70aa stloc local_0xa ldc.i4 0x496a6b4f stloc local_0xd ldc.i4 0x3be55136 stloc local_0xe ldc.i8 0x38f9668b658c7c52 stloc local_0xf ldc.r4 float32(0x7b5d5f1c) stloc local_0x10 ldc.i8 0x2e955def5c8d4af1 stsfld unsigned int64 ILGEN_0x38e6a02d::field_0x3 ldc.i4 0x4fcc1252 stsfld int16 ILGEN_0x38e6a02d::field_0x5 ldc.r4 float32(0x7aa321fe) stsfld float32 ILGEN_0x38e6a02d::field_0x8 Start_Orphan_0: ldloc local_0xa conv.u1 newarr [mscorlib]System.UInt16 Start_Orphan_6: Start_Orphan_7: ldsfld unsigned int64 ILGEN_0x38e6a02d::field_0x3 stloc local_0xf End_Orphan_7: End_Orphan_6: ldsfld unsigned int64 ILGEN_0x38e6a02d::field_0x3 conv.ovf.i conv.r4 ldsfld float32 ILGEN_0x38e6a02d::field_0x8 mul conv.ovf.u4 ldelema [mscorlib]System.UInt16 pop End_Orphan_0: ldloc local_0x10 conv.ovf.u8 ldsflda unsigned int64 ILGEN_0x38e6a02d::field_0x3 ldind.u8 ldc.i4.1 conv.i8 mul.ovf or ldsfld int16 ILGEN_0x38e6a02d::field_0x5 ldloc local_0xb div conv.ovf.u8.un ldloc local_0xf conv.ovf.u8 ldc.i4.8 conv.ovf.i8 add.ovf sub.ovf div ldc.i4.s -88 ldloc local_0xe clt conv.ovf.u8.un mul.ovf.un conv.ovf.u1 conv.u1 pop leave Beyond } catch [mscorlib]System.OverflowException { pop leave Beyond } Beyond: ldc.i4 100 ret } }
-1
dotnet/runtime
66,462
Support using the system version of brotli
This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
omajid
2022-03-10T17:19:11Z
2022-03-23T03:49:50Z
c3e1d21c2fb30436ae24ef7ef4f458e3270bb7e3
5ca9223639700750ff12bb1fed9fa6e397062b78
Support using the system version of brotli . This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
./src/libraries/System.Private.Xml/src/System/Xml/XmlQualifiedName.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics.CodeAnalysis; namespace System.Xml { /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public class XmlQualifiedName { private int _hash; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static readonly XmlQualifiedName Empty = new(string.Empty); /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlQualifiedName() : this(string.Empty, string.Empty) { } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlQualifiedName(string? name) : this(name, string.Empty) { } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlQualifiedName(string? name, string? ns) { Namespace = ns ?? string.Empty; Name = name ?? string.Empty; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public string Namespace { get; private set; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public string Name { get; private set; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public override int GetHashCode() { if (_hash == 0) { _hash = Name.GetHashCode(); /*+ Namespace.GetHashCode()*/ // for perf reasons we are not taking ns's hashcode. } return _hash; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public bool IsEmpty => Name.Length == 0 && Namespace.Length == 0; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public override string ToString() { return Namespace.Length == 0 ? Name : $"{Namespace}:{Name}"; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public override bool Equals([NotNullWhen(true)] object? other) { if (ReferenceEquals(this, other)) { return true; } return other is XmlQualifiedName qName && Name == qName.Name && Namespace == qName.Namespace; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static bool operator ==(XmlQualifiedName? a, XmlQualifiedName? b) { if (ReferenceEquals(a, b)) { return true; } if (a is null || b is null) { return false; } return a.Name == b.Name && a.Namespace == b.Namespace; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static bool operator !=(XmlQualifiedName? a, XmlQualifiedName? b) { return !(a == b); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static string ToString(string name, string? ns) { return ns == null || ns.Length == 0 ? name : $"{ns}:{name}"; } // --------- Some useful internal stuff ----------------- internal void Init(string? name, string? ns) { Name = name ?? string.Empty; Namespace = ns ?? string.Empty; _hash = 0; } internal void SetNamespace(string? ns) { Namespace = ns ?? string.Empty; // Not changing hash since ns is not used to compute hashcode } internal void Verify() { XmlConvert.VerifyNCName(Name); if (Namespace.Length != 0) { XmlConvert.ToUri(Namespace); } } internal void Atomize(XmlNameTable nameTable) { Name = nameTable.Add(Name); Namespace = nameTable.Add(Namespace); } internal static XmlQualifiedName Parse(string s, IXmlNamespaceResolver nsmgr, out string prefix) { ValidateNames.ParseQNameThrow(s, out prefix, out string localName); string? uri = nsmgr.LookupNamespace(prefix); if (uri == null) { if (prefix.Length != 0) { throw new XmlException(SR.Xml_UnknownNs, prefix); } // Re-map namespace of empty prefix to string.Empty when there is no default namespace declared uri = string.Empty; } return new XmlQualifiedName(localName, uri); } internal XmlQualifiedName Clone() { return (XmlQualifiedName)MemberwiseClone(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics.CodeAnalysis; namespace System.Xml { /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public class XmlQualifiedName { private int _hash; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static readonly XmlQualifiedName Empty = new(string.Empty); /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlQualifiedName() : this(string.Empty, string.Empty) { } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlQualifiedName(string? name) : this(name, string.Empty) { } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlQualifiedName(string? name, string? ns) { Namespace = ns ?? string.Empty; Name = name ?? string.Empty; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public string Namespace { get; private set; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public string Name { get; private set; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public override int GetHashCode() { if (_hash == 0) { _hash = Name.GetHashCode(); /*+ Namespace.GetHashCode()*/ // for perf reasons we are not taking ns's hashcode. } return _hash; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public bool IsEmpty => Name.Length == 0 && Namespace.Length == 0; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public override string ToString() { return Namespace.Length == 0 ? Name : $"{Namespace}:{Name}"; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public override bool Equals([NotNullWhen(true)] object? other) { if (ReferenceEquals(this, other)) { return true; } return other is XmlQualifiedName qName && Name == qName.Name && Namespace == qName.Namespace; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static bool operator ==(XmlQualifiedName? a, XmlQualifiedName? b) { if (ReferenceEquals(a, b)) { return true; } if (a is null || b is null) { return false; } return a.Name == b.Name && a.Namespace == b.Namespace; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static bool operator !=(XmlQualifiedName? a, XmlQualifiedName? b) { return !(a == b); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static string ToString(string name, string? ns) { return ns == null || ns.Length == 0 ? name : $"{ns}:{name}"; } // --------- Some useful internal stuff ----------------- internal void Init(string? name, string? ns) { Name = name ?? string.Empty; Namespace = ns ?? string.Empty; _hash = 0; } internal void SetNamespace(string? ns) { Namespace = ns ?? string.Empty; // Not changing hash since ns is not used to compute hashcode } internal void Verify() { XmlConvert.VerifyNCName(Name); if (Namespace.Length != 0) { XmlConvert.ToUri(Namespace); } } internal void Atomize(XmlNameTable nameTable) { Name = nameTable.Add(Name); Namespace = nameTable.Add(Namespace); } internal static XmlQualifiedName Parse(string s, IXmlNamespaceResolver nsmgr, out string prefix) { ValidateNames.ParseQNameThrow(s, out prefix, out string localName); string? uri = nsmgr.LookupNamespace(prefix); if (uri == null) { if (prefix.Length != 0) { throw new XmlException(SR.Xml_UnknownNs, prefix); } // Re-map namespace of empty prefix to string.Empty when there is no default namespace declared uri = string.Empty; } return new XmlQualifiedName(localName, uri); } internal XmlQualifiedName Clone() { return (XmlQualifiedName)MemberwiseClone(); } } }
-1
dotnet/runtime
66,462
Support using the system version of brotli
This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
omajid
2022-03-10T17:19:11Z
2022-03-23T03:49:50Z
c3e1d21c2fb30436ae24ef7ef4f458e3270bb7e3
5ca9223639700750ff12bb1fed9fa6e397062b78
Support using the system version of brotli . This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
./src/coreclr/jit/blockset.h
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // This include file determines how BlockSet is implemented. // #ifndef _BLOCKSET_INCLUDED_ #define _BLOCKSET_INCLUDED_ 1 // A BlockSet is a set of BasicBlocks, represented by the BasicBlock number (bbNum). // Unlike VARSET_TP, we only support a single implementation: the bitset "shortlong" // implementation. // // Note that BasicBlocks in the JIT are numbered starting at 1. We always just waste the // 0th bit to avoid having to do "bbNum - 1" calculations everywhere (at the BlockSet call // sites). This makes reading the code easier, and avoids potential problems of forgetting // to do a "- 1" somewhere. // // Basic blocks can be renumbered during compilation, so it is important to not mix // BlockSets created before and after a renumbering. Every time the blocks are renumbered // creates a different "epoch", during which the basic block numbers are stable. #include "bitset.h" #include "compilerbitsettraits.h" #include "bitsetasshortlong.h" class BlockSetOps : public BitSetOps</*BitSetType*/ BitSetShortLongRep, /*Brand*/ BSShortLong, /*Env*/ Compiler*, /*BitSetTraits*/ BasicBlockBitSetTraits> { public: // Specialize BlockSetOps::MakeFull(). Since we number basic blocks from one, we remove bit zero from // the block set. Otherwise, IsEmpty() would never return true. static BitSetShortLongRep MakeFull(Compiler* env) { BitSetShortLongRep retval; // First, make a full set using the BitSetOps::MakeFull retval = BitSetOps</*BitSetType*/ BitSetShortLongRep, /*Brand*/ BSShortLong, /*Env*/ Compiler*, /*BitSetTraits*/ BasicBlockBitSetTraits>::MakeFull(env); // Now, remove element zero, since we number basic blocks starting at one, and index the set with the // basic block number. If we left this, then IsEmpty() would never return true. BlockSetOps::RemoveElemD(env, retval, 0); return retval; } }; typedef BitSetShortLongRep BlockSet; // These types should be used as the types for BlockSet arguments and return values, respectively. typedef BlockSetOps::ValArgType BlockSet_ValArg_T; typedef BlockSetOps::RetValType BlockSet_ValRet_T; #endif // _BLOCKSET_INCLUDED_
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // This include file determines how BlockSet is implemented. // #ifndef _BLOCKSET_INCLUDED_ #define _BLOCKSET_INCLUDED_ 1 // A BlockSet is a set of BasicBlocks, represented by the BasicBlock number (bbNum). // Unlike VARSET_TP, we only support a single implementation: the bitset "shortlong" // implementation. // // Note that BasicBlocks in the JIT are numbered starting at 1. We always just waste the // 0th bit to avoid having to do "bbNum - 1" calculations everywhere (at the BlockSet call // sites). This makes reading the code easier, and avoids potential problems of forgetting // to do a "- 1" somewhere. // // Basic blocks can be renumbered during compilation, so it is important to not mix // BlockSets created before and after a renumbering. Every time the blocks are renumbered // creates a different "epoch", during which the basic block numbers are stable. #include "bitset.h" #include "compilerbitsettraits.h" #include "bitsetasshortlong.h" class BlockSetOps : public BitSetOps</*BitSetType*/ BitSetShortLongRep, /*Brand*/ BSShortLong, /*Env*/ Compiler*, /*BitSetTraits*/ BasicBlockBitSetTraits> { public: // Specialize BlockSetOps::MakeFull(). Since we number basic blocks from one, we remove bit zero from // the block set. Otherwise, IsEmpty() would never return true. static BitSetShortLongRep MakeFull(Compiler* env) { BitSetShortLongRep retval; // First, make a full set using the BitSetOps::MakeFull retval = BitSetOps</*BitSetType*/ BitSetShortLongRep, /*Brand*/ BSShortLong, /*Env*/ Compiler*, /*BitSetTraits*/ BasicBlockBitSetTraits>::MakeFull(env); // Now, remove element zero, since we number basic blocks starting at one, and index the set with the // basic block number. If we left this, then IsEmpty() would never return true. BlockSetOps::RemoveElemD(env, retval, 0); return retval; } }; typedef BitSetShortLongRep BlockSet; // These types should be used as the types for BlockSet arguments and return values, respectively. typedef BlockSetOps::ValArgType BlockSet_ValArg_T; typedef BlockSetOps::RetValType BlockSet_ValRet_T; #endif // _BLOCKSET_INCLUDED_
-1
dotnet/runtime
66,462
Support using the system version of brotli
This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
omajid
2022-03-10T17:19:11Z
2022-03-23T03:49:50Z
c3e1d21c2fb30436ae24ef7ef4f458e3270bb7e3
5ca9223639700750ff12bb1fed9fa6e397062b78
Support using the system version of brotli . This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
./src/libraries/System.Private.Xml/tests/XmlDocument/XmlNodeTests/LastChildTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; namespace System.Xml.Tests { public class LastChildTests { [Fact] public static void ElementWithNoChild() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<top />"); Assert.Null(xmlDocument.DocumentElement.LastChild); } [Fact] public static void ElementWithNoChildTwoAttributes() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<top attr1='test1' attr2='test2' />"); Assert.Null(xmlDocument.DocumentElement.LastChild); } [Fact] public static void DeleteOnlyChildInsertNewNode() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<elem att1='foo'><a /></elem>"); var node = xmlDocument.DocumentElement; var old = node.FirstChild; node.RemoveChild(old); var newNode = xmlDocument.CreateTextNode("textNode"); node.AppendChild(newNode); Assert.Equal("textNode", node.LastChild.Value); Assert.Equal(XmlNodeType.Text, node.LastChild.NodeType); Assert.Equal(1, node.ChildNodes.Count); } [Fact] public static void DeleteOnlyChild() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<elem att1='foo'><a /></elem>"); var node = xmlDocument.DocumentElement; var oldNode = node.FirstChild; node.RemoveChild(oldNode); Assert.Null(node.LastChild); Assert.Equal(0, node.ChildNodes.Count); } [Fact] public static void DeleteOnlyChildAddTwoChildren() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<elem att1='foo'><a /></elem>"); var node = xmlDocument.DocumentElement; var oldNode = node.FirstChild; node.RemoveChild(oldNode); var element1 = xmlDocument.CreateElement("elem1"); var element2 = xmlDocument.CreateElement("elem2"); node.AppendChild(element1); node.AppendChild(element2); Assert.Equal(2, node.ChildNodes.Count); Assert.Equal(element2, node.LastChild); } [Fact] public static void DeleteOnlyChildAddTwoChildrenDeleteBoth() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<elem att1='foo'><a /></elem>"); var node = xmlDocument.DocumentElement; var oldNode = node.FirstChild; node.RemoveChild(oldNode); var element1 = xmlDocument.CreateElement("elem1"); var element2 = xmlDocument.CreateElement("elem2"); node.AppendChild(element1); node.AppendChild(element2); node.RemoveChild(element1); node.RemoveChild(element2); Assert.Null(node.LastChild); Assert.Equal(0, node.ChildNodes.Count); } [Fact] public static void AttributeWithOnlyText() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<element attrib='helloworld' />"); var node = xmlDocument.DocumentElement.GetAttributeNode("attrib"); Assert.Equal("helloworld", node.LastChild.Value); Assert.Equal(1, node.ChildNodes.Count); } [Fact] public static void ElementWithTwoAttributes() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml(" <element attrib1='hello' attrib2='world' />"); Assert.Null(xmlDocument.DocumentElement.LastChild); } [Fact] public static void ElementWithOneChild() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<root><child1/></root>"); Assert.Equal(XmlNodeType.Element, xmlDocument.DocumentElement.LastChild.NodeType); Assert.Equal("child1", xmlDocument.DocumentElement.LastChild.Name); } [Fact] public static void ElementWithMoreThanOneChild() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<root><child1/><child2>Some Text</child2><!-- comment --><?PI pi comments?></root>"); Assert.Equal(4, xmlDocument.DocumentElement.ChildNodes.Count); Assert.NotNull(xmlDocument.DocumentElement.LastChild); Assert.Equal(XmlNodeType.ProcessingInstruction, xmlDocument.DocumentElement.LastChild.NodeType); } [Fact] public static void ElementNodeWithOneChildAndOneElement() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<element attrib1='value'>content</element>"); Assert.Equal(XmlNodeType.Text, xmlDocument.DocumentElement.LastChild.NodeType); Assert.Equal("content", xmlDocument.DocumentElement.LastChild.Value); } [Fact] public static void NewlyCreatedElement() { var xmlDocument = new XmlDocument(); var node = xmlDocument.CreateElement("element"); Assert.Null(node.LastChild); } [Fact] public static void NewlyCreatedAttribute() { var xmlDocument = new XmlDocument(); var node = xmlDocument.CreateAttribute("attribute"); Assert.Null(node.LastChild); } [Fact] public static void NewlyCreatedTextNode() { var xmlDocument = new XmlDocument(); var node = xmlDocument.CreateTextNode("textnode"); Assert.Null(node.LastChild); } [Fact] public static void NewlyCreatedCDataNode() { var xmlDocument = new XmlDocument(); var node = xmlDocument.CreateCDataSection("cdata section"); Assert.Null(node.LastChild); } [Fact] public static void NewlyCreatedProcessingInstruction() { var xmlDocument = new XmlDocument(); var node = xmlDocument.CreateProcessingInstruction("PI", "data"); Assert.Null(node.LastChild); } [Fact] public static void NewlyCreatedComment() { var xmlDocument = new XmlDocument(); var node = xmlDocument.CreateComment("comment"); Assert.Null(node.LastChild); } [Fact] public static void NewlyCreatedDocumentFragment() { var xmlDocument = new XmlDocument(); var node = xmlDocument.CreateDocumentFragment(); Assert.Null(node.LastChild); } [Fact] public static void InsertChildAtLengthMinus1() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<root><child1/><child2/><child3/></root>"); var child3 = xmlDocument.DocumentElement.LastChild; Assert.Equal(3, xmlDocument.DocumentElement.ChildNodes.Count); Assert.Equal("child3", child3.Name); var newNode = xmlDocument.CreateElement("elem1"); xmlDocument.DocumentElement.InsertBefore(newNode, child3); Assert.Equal(4, xmlDocument.DocumentElement.ChildNodes.Count); Assert.Equal(child3, xmlDocument.DocumentElement.LastChild); } [Fact] public static void InsertChildToElementWithNoNode() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<root/>"); Assert.False(xmlDocument.DocumentElement.HasChildNodes); var newNode = xmlDocument.CreateElement("elem1"); xmlDocument.DocumentElement.AppendChild(newNode); Assert.Equal(1, xmlDocument.DocumentElement.ChildNodes.Count); Assert.Equal(newNode, xmlDocument.DocumentElement.LastChild); } [Fact] public static void ReplaceOnlyChildOfNode() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<root><child/></root>"); var oldNode = xmlDocument.DocumentElement.LastChild; var newNode = xmlDocument.CreateElement("elem1"); Assert.Equal(1, xmlDocument.DocumentElement.ChildNodes.Count); Assert.Equal(oldNode, xmlDocument.DocumentElement.LastChild); xmlDocument.DocumentElement.ReplaceChild(newNode, oldNode); Assert.Equal(1, xmlDocument.DocumentElement.ChildNodes.Count); Assert.Equal(newNode, xmlDocument.DocumentElement.LastChild); } [Fact] public static void ReplaceChild() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<root><child1/><child2/><child3/></root>"); var oldNode = xmlDocument.DocumentElement.LastChild; var newNode = xmlDocument.CreateElement("elem1"); Assert.Equal(3, xmlDocument.DocumentElement.ChildNodes.Count); Assert.Equal(oldNode, xmlDocument.DocumentElement.LastChild); xmlDocument.DocumentElement.ReplaceChild(newNode, oldNode); Assert.Equal(3, xmlDocument.DocumentElement.ChildNodes.Count); Assert.Equal(newNode, xmlDocument.DocumentElement.LastChild); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; namespace System.Xml.Tests { public class LastChildTests { [Fact] public static void ElementWithNoChild() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<top />"); Assert.Null(xmlDocument.DocumentElement.LastChild); } [Fact] public static void ElementWithNoChildTwoAttributes() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<top attr1='test1' attr2='test2' />"); Assert.Null(xmlDocument.DocumentElement.LastChild); } [Fact] public static void DeleteOnlyChildInsertNewNode() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<elem att1='foo'><a /></elem>"); var node = xmlDocument.DocumentElement; var old = node.FirstChild; node.RemoveChild(old); var newNode = xmlDocument.CreateTextNode("textNode"); node.AppendChild(newNode); Assert.Equal("textNode", node.LastChild.Value); Assert.Equal(XmlNodeType.Text, node.LastChild.NodeType); Assert.Equal(1, node.ChildNodes.Count); } [Fact] public static void DeleteOnlyChild() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<elem att1='foo'><a /></elem>"); var node = xmlDocument.DocumentElement; var oldNode = node.FirstChild; node.RemoveChild(oldNode); Assert.Null(node.LastChild); Assert.Equal(0, node.ChildNodes.Count); } [Fact] public static void DeleteOnlyChildAddTwoChildren() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<elem att1='foo'><a /></elem>"); var node = xmlDocument.DocumentElement; var oldNode = node.FirstChild; node.RemoveChild(oldNode); var element1 = xmlDocument.CreateElement("elem1"); var element2 = xmlDocument.CreateElement("elem2"); node.AppendChild(element1); node.AppendChild(element2); Assert.Equal(2, node.ChildNodes.Count); Assert.Equal(element2, node.LastChild); } [Fact] public static void DeleteOnlyChildAddTwoChildrenDeleteBoth() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<elem att1='foo'><a /></elem>"); var node = xmlDocument.DocumentElement; var oldNode = node.FirstChild; node.RemoveChild(oldNode); var element1 = xmlDocument.CreateElement("elem1"); var element2 = xmlDocument.CreateElement("elem2"); node.AppendChild(element1); node.AppendChild(element2); node.RemoveChild(element1); node.RemoveChild(element2); Assert.Null(node.LastChild); Assert.Equal(0, node.ChildNodes.Count); } [Fact] public static void AttributeWithOnlyText() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<element attrib='helloworld' />"); var node = xmlDocument.DocumentElement.GetAttributeNode("attrib"); Assert.Equal("helloworld", node.LastChild.Value); Assert.Equal(1, node.ChildNodes.Count); } [Fact] public static void ElementWithTwoAttributes() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml(" <element attrib1='hello' attrib2='world' />"); Assert.Null(xmlDocument.DocumentElement.LastChild); } [Fact] public static void ElementWithOneChild() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<root><child1/></root>"); Assert.Equal(XmlNodeType.Element, xmlDocument.DocumentElement.LastChild.NodeType); Assert.Equal("child1", xmlDocument.DocumentElement.LastChild.Name); } [Fact] public static void ElementWithMoreThanOneChild() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<root><child1/><child2>Some Text</child2><!-- comment --><?PI pi comments?></root>"); Assert.Equal(4, xmlDocument.DocumentElement.ChildNodes.Count); Assert.NotNull(xmlDocument.DocumentElement.LastChild); Assert.Equal(XmlNodeType.ProcessingInstruction, xmlDocument.DocumentElement.LastChild.NodeType); } [Fact] public static void ElementNodeWithOneChildAndOneElement() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<element attrib1='value'>content</element>"); Assert.Equal(XmlNodeType.Text, xmlDocument.DocumentElement.LastChild.NodeType); Assert.Equal("content", xmlDocument.DocumentElement.LastChild.Value); } [Fact] public static void NewlyCreatedElement() { var xmlDocument = new XmlDocument(); var node = xmlDocument.CreateElement("element"); Assert.Null(node.LastChild); } [Fact] public static void NewlyCreatedAttribute() { var xmlDocument = new XmlDocument(); var node = xmlDocument.CreateAttribute("attribute"); Assert.Null(node.LastChild); } [Fact] public static void NewlyCreatedTextNode() { var xmlDocument = new XmlDocument(); var node = xmlDocument.CreateTextNode("textnode"); Assert.Null(node.LastChild); } [Fact] public static void NewlyCreatedCDataNode() { var xmlDocument = new XmlDocument(); var node = xmlDocument.CreateCDataSection("cdata section"); Assert.Null(node.LastChild); } [Fact] public static void NewlyCreatedProcessingInstruction() { var xmlDocument = new XmlDocument(); var node = xmlDocument.CreateProcessingInstruction("PI", "data"); Assert.Null(node.LastChild); } [Fact] public static void NewlyCreatedComment() { var xmlDocument = new XmlDocument(); var node = xmlDocument.CreateComment("comment"); Assert.Null(node.LastChild); } [Fact] public static void NewlyCreatedDocumentFragment() { var xmlDocument = new XmlDocument(); var node = xmlDocument.CreateDocumentFragment(); Assert.Null(node.LastChild); } [Fact] public static void InsertChildAtLengthMinus1() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<root><child1/><child2/><child3/></root>"); var child3 = xmlDocument.DocumentElement.LastChild; Assert.Equal(3, xmlDocument.DocumentElement.ChildNodes.Count); Assert.Equal("child3", child3.Name); var newNode = xmlDocument.CreateElement("elem1"); xmlDocument.DocumentElement.InsertBefore(newNode, child3); Assert.Equal(4, xmlDocument.DocumentElement.ChildNodes.Count); Assert.Equal(child3, xmlDocument.DocumentElement.LastChild); } [Fact] public static void InsertChildToElementWithNoNode() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<root/>"); Assert.False(xmlDocument.DocumentElement.HasChildNodes); var newNode = xmlDocument.CreateElement("elem1"); xmlDocument.DocumentElement.AppendChild(newNode); Assert.Equal(1, xmlDocument.DocumentElement.ChildNodes.Count); Assert.Equal(newNode, xmlDocument.DocumentElement.LastChild); } [Fact] public static void ReplaceOnlyChildOfNode() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<root><child/></root>"); var oldNode = xmlDocument.DocumentElement.LastChild; var newNode = xmlDocument.CreateElement("elem1"); Assert.Equal(1, xmlDocument.DocumentElement.ChildNodes.Count); Assert.Equal(oldNode, xmlDocument.DocumentElement.LastChild); xmlDocument.DocumentElement.ReplaceChild(newNode, oldNode); Assert.Equal(1, xmlDocument.DocumentElement.ChildNodes.Count); Assert.Equal(newNode, xmlDocument.DocumentElement.LastChild); } [Fact] public static void ReplaceChild() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<root><child1/><child2/><child3/></root>"); var oldNode = xmlDocument.DocumentElement.LastChild; var newNode = xmlDocument.CreateElement("elem1"); Assert.Equal(3, xmlDocument.DocumentElement.ChildNodes.Count); Assert.Equal(oldNode, xmlDocument.DocumentElement.LastChild); xmlDocument.DocumentElement.ReplaceChild(newNode, oldNode); Assert.Equal(3, xmlDocument.DocumentElement.ChildNodes.Count); Assert.Equal(newNode, xmlDocument.DocumentElement.LastChild); } } }
-1
dotnet/runtime
66,462
Support using the system version of brotli
This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
omajid
2022-03-10T17:19:11Z
2022-03-23T03:49:50Z
c3e1d21c2fb30436ae24ef7ef4f458e3270bb7e3
5ca9223639700750ff12bb1fed9fa6e397062b78
Support using the system version of brotli . This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
./src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.HandleMetadata.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Text.Json.Serialization; namespace System.Text.Json { public static partial class JsonSerializer { // Pre-encoded metadata properties. internal static readonly JsonEncodedText s_metadataId = JsonEncodedText.Encode("$id", encoder: null); internal static readonly JsonEncodedText s_metadataRef = JsonEncodedText.Encode("$ref", encoder: null); internal static readonly JsonEncodedText s_metadataValues = JsonEncodedText.Encode("$values", encoder: null); internal static MetadataPropertyName WriteReferenceForObject( JsonConverter jsonConverter, ref WriteStack state, Utf8JsonWriter writer) { if (state.NewReferenceId != null) { Debug.Assert(jsonConverter.CanHaveIdMetadata); writer.WriteString(s_metadataId, state.NewReferenceId); state.NewReferenceId = null; return MetadataPropertyName.Id; } return MetadataPropertyName.NoMetadata; } internal static MetadataPropertyName WriteReferenceForCollection( JsonConverter jsonConverter, ref WriteStack state, Utf8JsonWriter writer) { if (state.NewReferenceId != null) { Debug.Assert(jsonConverter.CanHaveIdMetadata); writer.WriteStartObject(); writer.WriteString(s_metadataId, state.NewReferenceId); writer.WriteStartArray(s_metadataValues); state.NewReferenceId = null; return MetadataPropertyName.Id; } // If the jsonConverter supports immutable enumerables or value type collections, don't write any metadata writer.WriteStartArray(); return MetadataPropertyName.NoMetadata; } /// <summary> /// Compute reference id for the next value to be serialized. /// </summary> internal static bool TryGetReferenceForValue(object currentValue, ref WriteStack state, Utf8JsonWriter writer) { Debug.Assert(state.NewReferenceId == null); string referenceId = state.ReferenceResolver.GetReference(currentValue, out bool alreadyExists); Debug.Assert(referenceId != null); if (alreadyExists) { // Instance already serialized, write as { "$ref" : "referenceId" } writer.WriteStartObject(); writer.WriteString(s_metadataRef, referenceId); writer.WriteEndObject(); } else { // New instance, store computed reference id in the state state.NewReferenceId = referenceId; } return alreadyExists; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Text.Json.Serialization; namespace System.Text.Json { public static partial class JsonSerializer { // Pre-encoded metadata properties. internal static readonly JsonEncodedText s_metadataId = JsonEncodedText.Encode("$id", encoder: null); internal static readonly JsonEncodedText s_metadataRef = JsonEncodedText.Encode("$ref", encoder: null); internal static readonly JsonEncodedText s_metadataValues = JsonEncodedText.Encode("$values", encoder: null); internal static MetadataPropertyName WriteReferenceForObject( JsonConverter jsonConverter, ref WriteStack state, Utf8JsonWriter writer) { if (state.NewReferenceId != null) { Debug.Assert(jsonConverter.CanHaveIdMetadata); writer.WriteString(s_metadataId, state.NewReferenceId); state.NewReferenceId = null; return MetadataPropertyName.Id; } return MetadataPropertyName.NoMetadata; } internal static MetadataPropertyName WriteReferenceForCollection( JsonConverter jsonConverter, ref WriteStack state, Utf8JsonWriter writer) { if (state.NewReferenceId != null) { Debug.Assert(jsonConverter.CanHaveIdMetadata); writer.WriteStartObject(); writer.WriteString(s_metadataId, state.NewReferenceId); writer.WriteStartArray(s_metadataValues); state.NewReferenceId = null; return MetadataPropertyName.Id; } // If the jsonConverter supports immutable enumerables or value type collections, don't write any metadata writer.WriteStartArray(); return MetadataPropertyName.NoMetadata; } /// <summary> /// Compute reference id for the next value to be serialized. /// </summary> internal static bool TryGetReferenceForValue(object currentValue, ref WriteStack state, Utf8JsonWriter writer) { Debug.Assert(state.NewReferenceId == null); string referenceId = state.ReferenceResolver.GetReference(currentValue, out bool alreadyExists); Debug.Assert(referenceId != null); if (alreadyExists) { // Instance already serialized, write as { "$ref" : "referenceId" } writer.WriteStartObject(); writer.WriteString(s_metadataRef, referenceId); writer.WriteEndObject(); } else { // New instance, store computed reference id in the state state.NewReferenceId = referenceId; } return alreadyExists; } } }
-1
dotnet/runtime
66,462
Support using the system version of brotli
This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
omajid
2022-03-10T17:19:11Z
2022-03-23T03:49:50Z
c3e1d21c2fb30436ae24ef7ef4f458e3270bb7e3
5ca9223639700750ff12bb1fed9fa6e397062b78
Support using the system version of brotli . This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
./src/tests/JIT/IL_Conformance/Old/Conformance_Base/clt_u.ilproj
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> <RestorePackages>true</RestorePackages> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="clt_u.il" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> <RestorePackages>true</RestorePackages> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="clt_u.il" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,462
Support using the system version of brotli
This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
omajid
2022-03-10T17:19:11Z
2022-03-23T03:49:50Z
c3e1d21c2fb30436ae24ef7ef4f458e3270bb7e3
5ca9223639700750ff12bb1fed9fa6e397062b78
Support using the system version of brotli . This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
./src/tests/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b46569/b46569.il
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. .assembly extern legacy library mscorlib {} .assembly extern System.Console { .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) .ver 4:0:0:0 } .assembly 'b46569' {} .assembly extern xunit.core {} .class ILGEN_0x5db0aa0 { .method static int32 Method_0x14ca58b7(int64 Arg_0x0, float32 Arg_0x1, float32 Arg_0x2, int16 Arg_0x3, unsigned int16 Arg_0x4, float32 Arg_0x5, int32 Arg_0x6, int32 Arg_0x7, float64 Arg_0x8) { .maxstack 19 .locals (unsigned int16 local_0x0,unsigned int16[] local_0x1,unsigned int32 local_0x2,float32 local_0x3) ldc.i4 0xff96c4b6 stloc local_0x0 ldc.i4 255 newarr [mscorlib]System.UInt16 stloc local_0x1 ldc.i4 0x49856ea stloc local_0x2 ldc.r4 float32(0xecab3c57) stloc local_0x3 Start_Orphan_0: Start_Orphan_1: ldc.i8 0x3cfd13f01085ce81 conv.r8 neg conv.ovf.i8 Start_Orphan_8: Start_Orphan_9: nop End_Orphan_9: ldc.i4.6 stloc local_0x2 End_Orphan_8: Start_Orphan_a: nop End_Orphan_a: ldc.r8 float64(0x735539f730c9b3d1) conv.ovf.i2 Start_Orphan_b: nop End_Orphan_b: ldc.i4.2 ldc.i4 0x6cd4310f and mul.ovf conv.ovf.u8.un mul.ovf.un conv.ovf.i2.un Start_Orphan_c: Start_Orphan_d: ldc.r4 float32(0x528314cd) ldarg Arg_0x5 mul conv.r4 starg Arg_0x8 End_Orphan_d: Start_Orphan_e: nop End_Orphan_e: ldarg Arg_0x0 conv.ovf.i8 conv.ovf.u2 conv.u2 pop End_Orphan_c: Start_Orphan_f: nop End_Orphan_f: ldarg Arg_0x0 ldarg Arg_0x0 add.ovf.un conv.ovf.u1 ldc.i4.s 87 ldc.i4.s 86 add conv.i4 shr.un Start_Orphan_10: Start_Orphan_11: nop End_Orphan_11: ldc.i4.0 pop End_Orphan_10: Start_Orphan_12: ldloc local_0x1 stloc local_0x1 End_Orphan_12: ldloc local_0x2 conv.ovf.i.un mul.ovf.un Start_Orphan_13: ldloca local_0x3 pop End_Orphan_13: Start_Orphan_14: ldc.i4.7 starg Arg_0x7 End_Orphan_14: ldarg Arg_0x0 ldc.i4.5 shl conv.ovf.i1.un and bgt.un Branch_0x2 Start_Orphan_15: Start_Orphan_16: nop End_Orphan_16: ldc.i4.2 ldc.i4.4 cgt stloc local_0x0 End_Orphan_15: ldc.i4.0 conv.ovf.i1 conv.ovf.u1.un stloc local_0x2 br Branch_0x3 Branch_0x2: Start_Orphan_17: nop End_Orphan_17: ldarg Arg_0x0 conv.ovf.u Start_Orphan_18: nop End_Orphan_18: ldc.i4.5 ldarg Arg_0x3 mul.ovf.un div.un Start_Orphan_19: ldc.i4.1 starg Arg_0x3 End_Orphan_19: ldc.i8 0x9dd147c54dba12b8 conv.ovf.i8.un conv.ovf.i add.ovf.un conv.u8 starg Arg_0x0 Branch_0x3: End_Orphan_1: ldarg Arg_0x1 conv.i1 Start_Orphan_1a: ldloca local_0x3 Start_Orphan_1b: Start_Orphan_1c: ldc.i4.m1 starg Arg_0x4 End_Orphan_1c: Start_Orphan_1d: nop End_Orphan_1d: ldc.i4.m1 ldloc local_0x0 rem.un conv.r8 pop End_Orphan_1b: Start_Orphan_1e: Start_Orphan_1f: nop End_Orphan_1f: ldloc local_0x1 ldlen starg Arg_0x7 End_Orphan_1e: ldc.r8 float64(0xf422eead895b14d7) conv.i2 conv.ovf.i1 conv.r4 stind.r4 End_Orphan_1a: Start_Orphan_20: Start_Orphan_21: ldc.i4.4 starg Arg_0x4 End_Orphan_21: ldarg Arg_0x8 conv.r4 neg ckfinite stloc local_0x3 End_Orphan_20: ldc.i4.m1 conv.r4 ldc.r8 float64(0x62a271d88a8dbac) clt.un conv.ovf.i4.un Start_Orphan_22: ldloc local_0x1 ldc.i4.6 ldelema [mscorlib]System.UInt16 ldc.i4.2 ldc.i4 0xe0edd145 cgt stind.i2 End_Orphan_22: Start_Orphan_23: ldloc local_0x0 starg Arg_0x7 End_Orphan_23: Start_Orphan_24: nop End_Orphan_24: ldarg Arg_0x2 ldloc local_0x3 div conv.r4 ldc.r8 float64(0xadccf7e51feff98c) ldc.r8 float64(0xbdf33a9817ef0172) rem conv.r4 sub conv.r4 conv.ovf.i mul.ovf conv.ovf.i8.un conv.u4 xor Start_Orphan_25: Start_Orphan_26: ldloca local_0x3 pop End_Orphan_26: ldloc local_0x3 stloc local_0x3 End_Orphan_25: Start_Orphan_27: Start_Orphan_28: nop End_Orphan_28: ldc.r4 float32(0x26f1025f) ldloc local_0x3 rem conv.r4 conv.i2 starg Arg_0x4 End_Orphan_27: ldc.r4 float32(0x78b0d106) ckfinite conv.u8 Start_Orphan_29: ldarga Arg_0x4 ldc.i4.8 stind.i2 End_Orphan_29: Start_Orphan_2a: nop End_Orphan_2a: ldc.r8 float64(0xc7bb3f9b490c8e19) conv.ovf.u8 conv.i8 Start_Orphan_2b: nop End_Orphan_2b: ldarg Arg_0x0 conv.i8 conv.ovf.u1 conv.ovf.i8.un or and Start_Orphan_2e: ldarga Arg_0x4 ldc.i4.4 stind.i2 End_Orphan_2e: conv.ovf.i1 bgt.un Branch_0x0 ldc.i4.7 not conv.ovf.u8.un conv.i1 conv.u1 newarr [mscorlib]System.UInt16 pop br Branch_0x1 Branch_0x0: ldc.i4.7 starg Arg_0x4 Branch_0x1: End_Orphan_0: Start_Orphan_37: ldc.i8 0xb05204d73e690f1e conv.ovf.i ldarg Arg_0x0 conv.ovf.i.un and starg Arg_0x7 End_Orphan_37: ldc.i4 55 ret } .method static int32 Main() { .custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = ( 01 00 00 00 ) .entrypoint .maxstack 20 .try { ldc.i8 0x32e05eaaae466f4 ldc.r4 float32(0x977cc1dc) ldc.r4 float32(0x1ff2dd0e) ldc.i4 0x605fd326 ldc.i4 0xe5abd4a9 ldc.r4 float32(0x4fd5952d) ldc.i4 0xd23a95c2 ldc.i4 0x1548acbf ldc.r8 float64(0xe743a5a5c5c5be76) call int32 ILGEN_0x5db0aa0::Method_0x14ca58b7(int64 Arg_0x0, float32 Arg_0x1, float32 Arg_0x2, int16 Arg_0x3, unsigned int16 Arg_0x4, float32 Arg_0x5, int32 Arg_0x6, int32 Arg_0x7, float64 Arg_0x8) pop leave X } catch [mscorlib]System.OverflowException { pop leave X } X: ldc.i4 100 ret } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. .assembly extern legacy library mscorlib {} .assembly extern System.Console { .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) .ver 4:0:0:0 } .assembly 'b46569' {} .assembly extern xunit.core {} .class ILGEN_0x5db0aa0 { .method static int32 Method_0x14ca58b7(int64 Arg_0x0, float32 Arg_0x1, float32 Arg_0x2, int16 Arg_0x3, unsigned int16 Arg_0x4, float32 Arg_0x5, int32 Arg_0x6, int32 Arg_0x7, float64 Arg_0x8) { .maxstack 19 .locals (unsigned int16 local_0x0,unsigned int16[] local_0x1,unsigned int32 local_0x2,float32 local_0x3) ldc.i4 0xff96c4b6 stloc local_0x0 ldc.i4 255 newarr [mscorlib]System.UInt16 stloc local_0x1 ldc.i4 0x49856ea stloc local_0x2 ldc.r4 float32(0xecab3c57) stloc local_0x3 Start_Orphan_0: Start_Orphan_1: ldc.i8 0x3cfd13f01085ce81 conv.r8 neg conv.ovf.i8 Start_Orphan_8: Start_Orphan_9: nop End_Orphan_9: ldc.i4.6 stloc local_0x2 End_Orphan_8: Start_Orphan_a: nop End_Orphan_a: ldc.r8 float64(0x735539f730c9b3d1) conv.ovf.i2 Start_Orphan_b: nop End_Orphan_b: ldc.i4.2 ldc.i4 0x6cd4310f and mul.ovf conv.ovf.u8.un mul.ovf.un conv.ovf.i2.un Start_Orphan_c: Start_Orphan_d: ldc.r4 float32(0x528314cd) ldarg Arg_0x5 mul conv.r4 starg Arg_0x8 End_Orphan_d: Start_Orphan_e: nop End_Orphan_e: ldarg Arg_0x0 conv.ovf.i8 conv.ovf.u2 conv.u2 pop End_Orphan_c: Start_Orphan_f: nop End_Orphan_f: ldarg Arg_0x0 ldarg Arg_0x0 add.ovf.un conv.ovf.u1 ldc.i4.s 87 ldc.i4.s 86 add conv.i4 shr.un Start_Orphan_10: Start_Orphan_11: nop End_Orphan_11: ldc.i4.0 pop End_Orphan_10: Start_Orphan_12: ldloc local_0x1 stloc local_0x1 End_Orphan_12: ldloc local_0x2 conv.ovf.i.un mul.ovf.un Start_Orphan_13: ldloca local_0x3 pop End_Orphan_13: Start_Orphan_14: ldc.i4.7 starg Arg_0x7 End_Orphan_14: ldarg Arg_0x0 ldc.i4.5 shl conv.ovf.i1.un and bgt.un Branch_0x2 Start_Orphan_15: Start_Orphan_16: nop End_Orphan_16: ldc.i4.2 ldc.i4.4 cgt stloc local_0x0 End_Orphan_15: ldc.i4.0 conv.ovf.i1 conv.ovf.u1.un stloc local_0x2 br Branch_0x3 Branch_0x2: Start_Orphan_17: nop End_Orphan_17: ldarg Arg_0x0 conv.ovf.u Start_Orphan_18: nop End_Orphan_18: ldc.i4.5 ldarg Arg_0x3 mul.ovf.un div.un Start_Orphan_19: ldc.i4.1 starg Arg_0x3 End_Orphan_19: ldc.i8 0x9dd147c54dba12b8 conv.ovf.i8.un conv.ovf.i add.ovf.un conv.u8 starg Arg_0x0 Branch_0x3: End_Orphan_1: ldarg Arg_0x1 conv.i1 Start_Orphan_1a: ldloca local_0x3 Start_Orphan_1b: Start_Orphan_1c: ldc.i4.m1 starg Arg_0x4 End_Orphan_1c: Start_Orphan_1d: nop End_Orphan_1d: ldc.i4.m1 ldloc local_0x0 rem.un conv.r8 pop End_Orphan_1b: Start_Orphan_1e: Start_Orphan_1f: nop End_Orphan_1f: ldloc local_0x1 ldlen starg Arg_0x7 End_Orphan_1e: ldc.r8 float64(0xf422eead895b14d7) conv.i2 conv.ovf.i1 conv.r4 stind.r4 End_Orphan_1a: Start_Orphan_20: Start_Orphan_21: ldc.i4.4 starg Arg_0x4 End_Orphan_21: ldarg Arg_0x8 conv.r4 neg ckfinite stloc local_0x3 End_Orphan_20: ldc.i4.m1 conv.r4 ldc.r8 float64(0x62a271d88a8dbac) clt.un conv.ovf.i4.un Start_Orphan_22: ldloc local_0x1 ldc.i4.6 ldelema [mscorlib]System.UInt16 ldc.i4.2 ldc.i4 0xe0edd145 cgt stind.i2 End_Orphan_22: Start_Orphan_23: ldloc local_0x0 starg Arg_0x7 End_Orphan_23: Start_Orphan_24: nop End_Orphan_24: ldarg Arg_0x2 ldloc local_0x3 div conv.r4 ldc.r8 float64(0xadccf7e51feff98c) ldc.r8 float64(0xbdf33a9817ef0172) rem conv.r4 sub conv.r4 conv.ovf.i mul.ovf conv.ovf.i8.un conv.u4 xor Start_Orphan_25: Start_Orphan_26: ldloca local_0x3 pop End_Orphan_26: ldloc local_0x3 stloc local_0x3 End_Orphan_25: Start_Orphan_27: Start_Orphan_28: nop End_Orphan_28: ldc.r4 float32(0x26f1025f) ldloc local_0x3 rem conv.r4 conv.i2 starg Arg_0x4 End_Orphan_27: ldc.r4 float32(0x78b0d106) ckfinite conv.u8 Start_Orphan_29: ldarga Arg_0x4 ldc.i4.8 stind.i2 End_Orphan_29: Start_Orphan_2a: nop End_Orphan_2a: ldc.r8 float64(0xc7bb3f9b490c8e19) conv.ovf.u8 conv.i8 Start_Orphan_2b: nop End_Orphan_2b: ldarg Arg_0x0 conv.i8 conv.ovf.u1 conv.ovf.i8.un or and Start_Orphan_2e: ldarga Arg_0x4 ldc.i4.4 stind.i2 End_Orphan_2e: conv.ovf.i1 bgt.un Branch_0x0 ldc.i4.7 not conv.ovf.u8.un conv.i1 conv.u1 newarr [mscorlib]System.UInt16 pop br Branch_0x1 Branch_0x0: ldc.i4.7 starg Arg_0x4 Branch_0x1: End_Orphan_0: Start_Orphan_37: ldc.i8 0xb05204d73e690f1e conv.ovf.i ldarg Arg_0x0 conv.ovf.i.un and starg Arg_0x7 End_Orphan_37: ldc.i4 55 ret } .method static int32 Main() { .custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = ( 01 00 00 00 ) .entrypoint .maxstack 20 .try { ldc.i8 0x32e05eaaae466f4 ldc.r4 float32(0x977cc1dc) ldc.r4 float32(0x1ff2dd0e) ldc.i4 0x605fd326 ldc.i4 0xe5abd4a9 ldc.r4 float32(0x4fd5952d) ldc.i4 0xd23a95c2 ldc.i4 0x1548acbf ldc.r8 float64(0xe743a5a5c5c5be76) call int32 ILGEN_0x5db0aa0::Method_0x14ca58b7(int64 Arg_0x0, float32 Arg_0x1, float32 Arg_0x2, int16 Arg_0x3, unsigned int16 Arg_0x4, float32 Arg_0x5, int32 Arg_0x6, int32 Arg_0x7, float64 Arg_0x8) pop leave X } catch [mscorlib]System.OverflowException { pop leave X } X: ldc.i4 100 ret } }
-1
dotnet/runtime
66,462
Support using the system version of brotli
This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
omajid
2022-03-10T17:19:11Z
2022-03-23T03:49:50Z
c3e1d21c2fb30436ae24ef7ef4f458e3270bb7e3
5ca9223639700750ff12bb1fed9fa6e397062b78
Support using the system version of brotli . This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
./src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapConnection.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections; using System.ComponentModel; using System.Diagnostics; using System.Net; using System.Runtime.InteropServices; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml; namespace System.DirectoryServices.Protocols { internal delegate DirectoryResponse GetLdapResponseCallback(int messageId, LdapOperation operation, ResultAll resultType, TimeSpan requestTimeout, bool exceptionOnTimeOut); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate bool QUERYCLIENTCERT(IntPtr Connection, IntPtr trusted_CAs, ref IntPtr certificateHandle); public partial class LdapConnection : DirectoryConnection, IDisposable { internal enum LdapResult { LDAP_RES_SEARCH_RESULT = 0x65, LDAP_RES_SEARCH_ENTRY = 0x64, LDAP_RES_MODIFY = 0x67, LDAP_RES_ADD = 0x69, LDAP_RES_DELETE = 0x6b, LDAP_RES_MODRDN = 0x6d, LDAP_RES_COMPARE = 0x6f, LDAP_RES_REFERRAL = 0x73, LDAP_RES_EXTENDED = 0x78 } private const int LDAP_MOD_BVALUES = 0x80; internal static readonly object s_objectLock = new object(); internal static readonly Hashtable s_handleTable = new Hashtable(); private static readonly Hashtable s_asyncResultTable = Hashtable.Synchronized(new Hashtable()); private static readonly ManualResetEvent s_waitHandle = new ManualResetEvent(false); private static readonly LdapPartialResultsProcessor s_partialResultsProcessor = new LdapPartialResultsProcessor(s_waitHandle); private AuthType _connectionAuthType = AuthType.Negotiate; internal bool _needDispose = true; internal ConnectionHandle _ldapHandle; internal bool _disposed; private bool _bounded; private bool _needRebind; private bool _connected; internal QUERYCLIENTCERT _clientCertificateRoutine; public LdapConnection(string server) : this(new LdapDirectoryIdentifier(server)) { } public LdapConnection(LdapDirectoryIdentifier identifier) : this(identifier, null, AuthType.Negotiate) { } public LdapConnection(LdapDirectoryIdentifier identifier, NetworkCredential credential) : this(identifier, credential, AuthType.Negotiate) { } public LdapConnection(LdapDirectoryIdentifier identifier, NetworkCredential credential, AuthType authType) { _directoryIdentifier = identifier; _directoryCredential = (credential != null) ? new NetworkCredential(credential.UserName, credential.Password, credential.Domain) : null; _connectionAuthType = authType; if (authType < AuthType.Anonymous || authType > AuthType.Kerberos) { throw new InvalidEnumArgumentException(nameof(authType), (int)authType, typeof(AuthType)); } // Throw if user wants to do anonymous bind but specifies credentials. if (AuthType == AuthType.Anonymous && (_directoryCredential != null && (!string.IsNullOrEmpty(_directoryCredential.Password) || !string.IsNullOrEmpty(_directoryCredential.UserName)))) { throw new ArgumentException(SR.InvalidAuthCredential); } Init(); SessionOptions = new LdapSessionOptions(this); _clientCertificateRoutine = new QUERYCLIENTCERT(ProcessClientCertificate); } internal LdapConnection(LdapDirectoryIdentifier identifier, NetworkCredential credential, AuthType authType, IntPtr handle) { _directoryIdentifier = identifier; _needDispose = false; _ldapHandle = new ConnectionHandle(handle, _needDispose); _directoryCredential = credential; _connectionAuthType = authType; SessionOptions = new LdapSessionOptions(this); _clientCertificateRoutine = new QUERYCLIENTCERT(ProcessClientCertificate); } ~LdapConnection() => Dispose(false); public override TimeSpan Timeout { get => _connectionTimeOut; set { if (value < TimeSpan.Zero) { throw new ArgumentException(SR.NoNegativeTimeLimit, nameof(value)); } // Prevent integer overflow. if (value.TotalSeconds > int.MaxValue) { throw new ArgumentException(SR.TimespanExceedMax, nameof(value)); } _connectionTimeOut = value; } } public AuthType AuthType { get => _connectionAuthType; set { if (value < AuthType.Anonymous || value > AuthType.Kerberos) { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(AuthType)); } // If the change is made after we have bound to the server and value is really // changed, set the flag to indicate the need to do rebind. if (_bounded && (value != _connectionAuthType)) { _needRebind = true; } _connectionAuthType = value; } } public LdapSessionOptions SessionOptions { get; } public override NetworkCredential Credential { set { if (_bounded && !SameCredential(_directoryCredential, value)) { _needRebind = true; } _directoryCredential = (value != null) ? new NetworkCredential(value.UserName, value.Password, value.Domain) : null; } } public bool AutoBind { get; set; } = true; internal bool NeedDispose { get => _needDispose; set { if (_ldapHandle != null) { _ldapHandle._needDispose = value; } _needDispose = value; } } internal void Init() { string hostname = null; string[] servers = ((LdapDirectoryIdentifier)_directoryIdentifier)?.Servers; if (servers != null && servers.Length != 0) { var temp = new StringBuilder(200); for (int i = 0; i < servers.Length; i++) { if (servers[i] != null) { temp.Append(servers[i]); if (i < servers.Length - 1) { temp.Append(' '); } } } if (temp.Length != 0) { hostname = temp.ToString(); } } InternalInitConnectionHandle(hostname); // Create a WeakReference object with the target of ldapHandle and put it into our handle table. lock (s_objectLock) { if (s_handleTable[_ldapHandle.DangerousGetHandle()] != null) { s_handleTable.Remove(_ldapHandle.DangerousGetHandle()); } s_handleTable.Add(_ldapHandle.DangerousGetHandle(), new WeakReference(this)); } } public override DirectoryResponse SendRequest(DirectoryRequest request) { // No request specific timeout is specified, use the connection timeout. return SendRequest(request, _connectionTimeOut); } public DirectoryResponse SendRequest(DirectoryRequest request, TimeSpan requestTimeout) { if (_disposed) { throw new ObjectDisposedException(GetType().Name); } if (request == null) { throw new ArgumentNullException(nameof(request)); } if (request is DsmlAuthRequest) { throw new NotSupportedException(SR.DsmlAuthRequestNotSupported); } int messageID = 0; int error = SendRequestHelper(request, ref messageID); LdapOperation operation = LdapOperation.LdapSearch; if (request is DeleteRequest) { operation = LdapOperation.LdapDelete; } else if (request is AddRequest) { operation = LdapOperation.LdapAdd; } else if (request is ModifyRequest) { operation = LdapOperation.LdapModify; } else if (request is SearchRequest) { operation = LdapOperation.LdapSearch; } else if (request is ModifyDNRequest) { operation = LdapOperation.LdapModifyDn; } else if (request is CompareRequest) { operation = LdapOperation.LdapCompare; } else if (request is ExtendedRequest) { operation = LdapOperation.LdapExtendedRequest; } if (error == 0 && messageID != -1) { ValueTask<DirectoryResponse> vt = ConstructResponseAsync(messageID, operation, ResultAll.LDAP_MSG_ALL, requestTimeout, true, sync: true); Debug.Assert(vt.IsCompleted); return vt.GetAwaiter().GetResult(); } else { if (error == 0) { // Success code but message is -1, unexpected. error = LdapPal.GetLastErrorFromConnection(_ldapHandle); } throw ConstructException(error, operation); } } public IAsyncResult BeginSendRequest(DirectoryRequest request, PartialResultProcessing partialMode, AsyncCallback callback, object state) { return BeginSendRequest(request, _connectionTimeOut, partialMode, callback, state); } public IAsyncResult BeginSendRequest(DirectoryRequest request, TimeSpan requestTimeout, PartialResultProcessing partialMode, AsyncCallback callback, object state) { if (_disposed) { throw new ObjectDisposedException(GetType().Name); } if (request == null) { throw new ArgumentNullException(nameof(request)); } if (partialMode < PartialResultProcessing.NoPartialResultSupport || partialMode > PartialResultProcessing.ReturnPartialResultsAndNotifyCallback) { throw new InvalidEnumArgumentException(nameof(partialMode), (int)partialMode, typeof(PartialResultProcessing)); } if (partialMode != PartialResultProcessing.NoPartialResultSupport && !(request is SearchRequest)) { throw new NotSupportedException(SR.PartialResultsNotSupported); } if (partialMode == PartialResultProcessing.ReturnPartialResultsAndNotifyCallback && callback == null) { throw new ArgumentException(SR.CallBackIsNull, nameof(callback)); } int messageID = 0; int error = SendRequestHelper(request, ref messageID); LdapOperation operation = LdapOperation.LdapSearch; if (request is DeleteRequest) { operation = LdapOperation.LdapDelete; } else if (request is AddRequest) { operation = LdapOperation.LdapAdd; } else if (request is ModifyRequest) { operation = LdapOperation.LdapModify; } else if (request is SearchRequest) { operation = LdapOperation.LdapSearch; } else if (request is ModifyDNRequest) { operation = LdapOperation.LdapModifyDn; } else if (request is CompareRequest) { operation = LdapOperation.LdapCompare; } else if (request is ExtendedRequest) { operation = LdapOperation.LdapExtendedRequest; } if (error == 0 && messageID != -1) { if (partialMode == PartialResultProcessing.NoPartialResultSupport) { var requestState = new LdapRequestState(); var asyncResult = new LdapAsyncResult(callback, state, false); requestState._ldapAsync = asyncResult; asyncResult._resultObject = requestState; s_asyncResultTable.Add(asyncResult, messageID); _ = ResponseCallback(ConstructResponseAsync(messageID, operation, ResultAll.LDAP_MSG_ALL, requestTimeout, true, sync: false), requestState); static async Task ResponseCallback(ValueTask<DirectoryResponse> vt, LdapRequestState requestState) { try { DirectoryResponse response = await vt.ConfigureAwait(false); requestState._response = response; } catch (Exception e) { requestState._exception = e; requestState._response = null; } // Signal waitable object, indicate operation completed and fire callback. requestState._ldapAsync._manualResetEvent.Set(); requestState._ldapAsync._completed = true; if (requestState._ldapAsync._callback != null && !requestState._abortCalled) { requestState._ldapAsync._callback(requestState._ldapAsync); } } return asyncResult; } else { // the user registers to retrieve partial results bool partialCallback = partialMode == PartialResultProcessing.ReturnPartialResultsAndNotifyCallback; var asyncResult = new LdapPartialAsyncResult(messageID, callback, state, true, this, partialCallback, requestTimeout); s_partialResultsProcessor.Add(asyncResult); return asyncResult; } } if (error == 0) { // Success code but message is -1, unexpected. error = LdapPal.GetLastErrorFromConnection(_ldapHandle); } throw ConstructException(error, operation); } public void Abort(IAsyncResult asyncResult) { if (_disposed) { throw new ObjectDisposedException(GetType().Name); } if (asyncResult == null) { throw new ArgumentNullException(nameof(asyncResult)); } if (!(asyncResult is LdapAsyncResult)) { throw new ArgumentException(SR.Format(SR.NotReturnedAsyncResult, nameof(asyncResult))); } int messageId; LdapAsyncResult result = (LdapAsyncResult)asyncResult; if (!result._partialResults) { if (!s_asyncResultTable.Contains(asyncResult)) { throw new ArgumentException(SR.InvalidAsyncResult); } messageId = (int)(s_asyncResultTable[asyncResult]); // remove the asyncResult from our connection table s_asyncResultTable.Remove(asyncResult); } else { s_partialResultsProcessor.Remove((LdapPartialAsyncResult)asyncResult); messageId = ((LdapPartialAsyncResult)asyncResult)._messageID; } // Cancel the request. LdapPal.CancelDirectoryAsyncOperation(_ldapHandle, messageId); LdapRequestState resultObject = result._resultObject; if (resultObject != null) { resultObject._abortCalled = true; } } public PartialResultsCollection GetPartialResults(IAsyncResult asyncResult) { if (_disposed) { throw new ObjectDisposedException(GetType().Name); } if (asyncResult == null) { throw new ArgumentNullException(nameof(asyncResult)); } if (!(asyncResult is LdapAsyncResult)) { throw new ArgumentException(SR.Format(SR.NotReturnedAsyncResult, nameof(asyncResult))); } if (!(asyncResult is LdapPartialAsyncResult)) { throw new InvalidOperationException(SR.NoPartialResults); } return s_partialResultsProcessor.GetPartialResults((LdapPartialAsyncResult)asyncResult); } public DirectoryResponse EndSendRequest(IAsyncResult asyncResult) { if (_disposed) { throw new ObjectDisposedException(GetType().Name); } if (asyncResult == null) { throw new ArgumentNullException(nameof(asyncResult)); } if (!(asyncResult is LdapAsyncResult)) { throw new ArgumentException(SR.Format(SR.NotReturnedAsyncResult, nameof(asyncResult))); } LdapAsyncResult result = (LdapAsyncResult)asyncResult; if (!result._partialResults) { // Not a partial results. if (!s_asyncResultTable.Contains(asyncResult)) { throw new ArgumentException(SR.InvalidAsyncResult); } // Remove the asyncResult from our connection table. s_asyncResultTable.Remove(asyncResult); asyncResult.AsyncWaitHandle.WaitOne(); if (result._resultObject._exception != null) { throw result._resultObject._exception; } return result._resultObject._response; } // Deal with partial results. s_partialResultsProcessor.NeedCompleteResult((LdapPartialAsyncResult)asyncResult); asyncResult.AsyncWaitHandle.WaitOne(); return s_partialResultsProcessor.GetCompleteResult((LdapPartialAsyncResult)asyncResult); } private int SendRequestHelper(DirectoryRequest request, ref int messageID) { IntPtr serverControlArray = IntPtr.Zero; LdapControl[] managedServerControls = null; IntPtr clientControlArray = IntPtr.Zero; LdapControl[] managedClientControls = null; var ptrToFree = new ArrayList(); LdapMod[] modifications = null; IntPtr modArray = IntPtr.Zero; int addModCount = 0; BerVal berValuePtr = null; IntPtr searchAttributes = IntPtr.Zero; int attributeCount = 0; int error = 0; // Connect to the server first if have not done so. if (!_connected) { Connect(); _connected = true; } // Bind if user has not turned off automatic bind, have not done so or there is a need // to do rebind, also connectionless LDAP does not need to do bind. if (AutoBind && (!_bounded || _needRebind) && ((LdapDirectoryIdentifier)Directory).Connectionless != true) { Debug.WriteLine("rebind occurs\n"); Bind(); } try { IntPtr tempPtr = IntPtr.Zero; // Build server control. managedServerControls = BuildControlArray(request.Controls, true); int structSize = Marshal.SizeOf(typeof(LdapControl)); if (managedServerControls != null) { serverControlArray = Utility.AllocHGlobalIntPtrArray(managedServerControls.Length + 1); for (int i = 0; i < managedServerControls.Length; i++) { IntPtr controlPtr = Marshal.AllocHGlobal(structSize); Marshal.StructureToPtr(managedServerControls[i], controlPtr, false); tempPtr = (IntPtr)((long)serverControlArray + IntPtr.Size * i); Marshal.WriteIntPtr(tempPtr, controlPtr); } tempPtr = (IntPtr)((long)serverControlArray + IntPtr.Size * managedServerControls.Length); Marshal.WriteIntPtr(tempPtr, IntPtr.Zero); } // build client control managedClientControls = BuildControlArray(request.Controls, false); if (managedClientControls != null) { clientControlArray = Utility.AllocHGlobalIntPtrArray(managedClientControls.Length + 1); for (int i = 0; i < managedClientControls.Length; i++) { IntPtr controlPtr = Marshal.AllocHGlobal(structSize); Marshal.StructureToPtr(managedClientControls[i], controlPtr, false); tempPtr = (IntPtr)((long)clientControlArray + IntPtr.Size * i); Marshal.WriteIntPtr(tempPtr, controlPtr); } tempPtr = (IntPtr)((long)clientControlArray + IntPtr.Size * managedClientControls.Length); Marshal.WriteIntPtr(tempPtr, IntPtr.Zero); } if (request is DeleteRequest) { // It is an delete operation. error = LdapPal.DeleteDirectoryEntry(_ldapHandle, ((DeleteRequest)request).DistinguishedName, serverControlArray, clientControlArray, ref messageID); } else if (request is ModifyDNRequest) { // It is a modify dn operation error = LdapPal.RenameDirectoryEntry( _ldapHandle, ((ModifyDNRequest)request).DistinguishedName, ((ModifyDNRequest)request).NewName, ((ModifyDNRequest)request).NewParentDistinguishedName, ((ModifyDNRequest)request).DeleteOldRdn ? 1 : 0, serverControlArray, clientControlArray, ref messageID); } else if (request is CompareRequest compareRequest) { // It is a compare request. DirectoryAttribute assertion = compareRequest.Assertion; if (assertion == null) { throw new ArgumentException(SR.WrongAssertionCompare); } if (assertion.Count != 1) { throw new ArgumentException(SR.WrongNumValuesCompare); } // Process the attribute. string stringValue = null; if (assertion[0] is byte[] byteArray) { if (byteArray != null && byteArray.Length != 0) { berValuePtr = new BerVal { bv_len = byteArray.Length, bv_val = Marshal.AllocHGlobal(byteArray.Length) }; Marshal.Copy(byteArray, 0, berValuePtr.bv_val, byteArray.Length); } } else { stringValue = assertion[0].ToString(); } // It is a compare request. error = LdapPal.CompareDirectoryEntries( _ldapHandle, ((CompareRequest)request).DistinguishedName, assertion.Name, stringValue, berValuePtr, serverControlArray, clientControlArray, ref messageID); } else if (request is AddRequest || request is ModifyRequest) { // Build the attributes. if (request is AddRequest) { modifications = BuildAttributes(((AddRequest)request).Attributes, ptrToFree); } else { modifications = BuildAttributes(((ModifyRequest)request).Modifications, ptrToFree); } addModCount = (modifications == null ? 1 : modifications.Length + 1); modArray = Utility.AllocHGlobalIntPtrArray(addModCount); int modStructSize = Marshal.SizeOf(typeof(LdapMod)); int i = 0; for (i = 0; i < addModCount - 1; i++) { IntPtr controlPtr = Marshal.AllocHGlobal(modStructSize); Marshal.StructureToPtr(modifications[i], controlPtr, false); tempPtr = (IntPtr)((long)modArray + IntPtr.Size * i); Marshal.WriteIntPtr(tempPtr, controlPtr); } tempPtr = (IntPtr)((long)modArray + IntPtr.Size * i); Marshal.WriteIntPtr(tempPtr, IntPtr.Zero); if (request is AddRequest) { error = LdapPal.AddDirectoryEntry( _ldapHandle, ((AddRequest)request).DistinguishedName, modArray, serverControlArray, clientControlArray, ref messageID); } else { error = LdapPal.ModifyDirectoryEntry( _ldapHandle, ((ModifyRequest)request).DistinguishedName, modArray, serverControlArray, clientControlArray, ref messageID); } } else if (request is ExtendedRequest extendedRequest) { string name = extendedRequest.RequestName; byte[] val = extendedRequest.RequestValue; // process the requestvalue if (val != null && val.Length != 0) { berValuePtr = new BerVal() { bv_len = val.Length, bv_val = Marshal.AllocHGlobal(val.Length) }; Marshal.Copy(val, 0, berValuePtr.bv_val, val.Length); } error = LdapPal.ExtendedDirectoryOperation( _ldapHandle, name, berValuePtr, serverControlArray, clientControlArray, ref messageID); } else if (request is SearchRequest searchRequest) { // Process the filter. object filter = searchRequest.Filter; if (filter != null) { // LdapConnection only supports ldap filter. if (filter is XmlDocument) { throw new ArgumentException(SR.InvalidLdapSearchRequestFilter); } } string searchRequestFilter = (string)filter; // Process the attributes. attributeCount = (searchRequest.Attributes == null ? 0 : searchRequest.Attributes.Count); if (attributeCount != 0) { searchAttributes = Utility.AllocHGlobalIntPtrArray(attributeCount + 1); int i = 0; for (i = 0; i < attributeCount; i++) { IntPtr controlPtr = LdapPal.StringToPtr(searchRequest.Attributes[i]); tempPtr = (IntPtr)((long)searchAttributes + IntPtr.Size * i); Marshal.WriteIntPtr(tempPtr, controlPtr); } tempPtr = (IntPtr)((long)searchAttributes + IntPtr.Size * i); Marshal.WriteIntPtr(tempPtr, IntPtr.Zero); } // Process the scope. int searchScope = (int)searchRequest.Scope; // Process the timelimit. int searchTimeLimit = (int)(searchRequest.TimeLimit.Ticks / TimeSpan.TicksPerSecond); // Process the alias. DereferenceAlias searchAliases = SessionOptions.DerefAlias; SessionOptions.DerefAlias = searchRequest.Aliases; try { error = LdapPal.SearchDirectory( _ldapHandle, searchRequest.DistinguishedName, searchScope, searchRequestFilter, searchAttributes, searchRequest.TypesOnly, serverControlArray, clientControlArray, searchTimeLimit, searchRequest.SizeLimit, ref messageID); } finally { // Revert back. SessionOptions.DerefAlias = searchAliases; } } else { throw new NotSupportedException(SR.InvliadRequestType); } // The asynchronous call itself timeout, this actually means that we time out the // LDAP_OPT_SEND_TIMEOUT specified in the session option wldap32 does not differentiate // that, but the application caller actually needs this information to determin what to // do with the error code if (error == (int)LdapError.TimeOut) { error = (int)LdapError.SendTimeOut; } return error; } finally { GC.KeepAlive(modifications); if (serverControlArray != IntPtr.Zero) { // Release the memory from the heap. for (int i = 0; i < managedServerControls.Length; i++) { IntPtr tempPtr = Marshal.ReadIntPtr(serverControlArray, IntPtr.Size * i); if (tempPtr != IntPtr.Zero) { Marshal.FreeHGlobal(tempPtr); } } Marshal.FreeHGlobal(serverControlArray); } if (managedServerControls != null) { for (int i = 0; i < managedServerControls.Length; i++) { if (managedServerControls[i].ldctl_oid != IntPtr.Zero) { Marshal.FreeHGlobal(managedServerControls[i].ldctl_oid); } if (managedServerControls[i].ldctl_value != null) { if (managedServerControls[i].ldctl_value.bv_val != IntPtr.Zero) { Marshal.FreeHGlobal(managedServerControls[i].ldctl_value.bv_val); } } } } if (clientControlArray != IntPtr.Zero) { // Release the memory from the heap. for (int i = 0; i < managedClientControls.Length; i++) { IntPtr tempPtr = Marshal.ReadIntPtr(clientControlArray, IntPtr.Size * i); if (tempPtr != IntPtr.Zero) { Marshal.FreeHGlobal(tempPtr); } } Marshal.FreeHGlobal(clientControlArray); } if (managedClientControls != null) { for (int i = 0; i < managedClientControls.Length; i++) { if (managedClientControls[i].ldctl_oid != IntPtr.Zero) { Marshal.FreeHGlobal(managedClientControls[i].ldctl_oid); } if (managedClientControls[i].ldctl_value != null) { if (managedClientControls[i].ldctl_value.bv_val != IntPtr.Zero) { Marshal.FreeHGlobal(managedClientControls[i].ldctl_value.bv_val); } } } } if (modArray != IntPtr.Zero) { // release the memory from the heap for (int i = 0; i < addModCount - 1; i++) { IntPtr tempPtr = Marshal.ReadIntPtr(modArray, IntPtr.Size * i); if (tempPtr != IntPtr.Zero) { Marshal.FreeHGlobal(tempPtr); } } Marshal.FreeHGlobal(modArray); } // Free the pointers. for (int x = 0; x < ptrToFree.Count; x++) { IntPtr tempPtr = (IntPtr)ptrToFree[x]; Marshal.FreeHGlobal(tempPtr); } if (berValuePtr != null && berValuePtr.bv_val != IntPtr.Zero) { Marshal.FreeHGlobal(berValuePtr.bv_val); } if (searchAttributes != IntPtr.Zero) { for (int i = 0; i < attributeCount; i++) { IntPtr tempPtr = Marshal.ReadIntPtr(searchAttributes, IntPtr.Size * i); if (tempPtr != IntPtr.Zero) { Marshal.FreeHGlobal(tempPtr); } } Marshal.FreeHGlobal(searchAttributes); } } } private bool ProcessClientCertificate(IntPtr ldapHandle, IntPtr CAs, ref IntPtr certificate) { int count = ClientCertificates == null ? 0 : ClientCertificates.Count; if (count == 0 && SessionOptions._clientCertificateDelegate == null) { return false; } // If the user specify certificate through property and not though option, we don't need to check the certificate authority. if (SessionOptions._clientCertificateDelegate == null) { certificate = ClientCertificates[0].Handle; return true; } // Processing the certificate authority. var list = new ArrayList(); if (CAs != IntPtr.Zero) { SecPkgContext_IssuerListInfoEx trustedCAs = (SecPkgContext_IssuerListInfoEx)Marshal.PtrToStructure(CAs, typeof(SecPkgContext_IssuerListInfoEx)); int issuerNumber = trustedCAs.cIssuers; for (int i = 0; i < issuerNumber; i++) { IntPtr tempPtr = (IntPtr)((long)trustedCAs.aIssuers + Marshal.SizeOf(typeof(CRYPTOAPI_BLOB)) * i); CRYPTOAPI_BLOB info = (CRYPTOAPI_BLOB)Marshal.PtrToStructure(tempPtr, typeof(CRYPTOAPI_BLOB)); int dataLength = info.cbData; byte[] context = new byte[dataLength]; Marshal.Copy(info.pbData, context, 0, dataLength); list.Add(context); } } byte[][] certAuthorities = null; if (list.Count != 0) { certAuthorities = new byte[list.Count][]; for (int i = 0; i < list.Count; i++) { certAuthorities[i] = (byte[])list[i]; } } X509Certificate cert = SessionOptions._clientCertificateDelegate(this, certAuthorities); if (cert != null) { certificate = cert.Handle; return true; } certificate = IntPtr.Zero; return false; } private void Connect() { //Ccurrently ldap does not accept more than one certificate. if (ClientCertificates.Count > 1) { throw new InvalidOperationException(SR.InvalidClientCertificates); } // Set the certificate callback routine here if user adds the certifcate to the certificate collection. if (ClientCertificates.Count != 0) { int certError = LdapPal.SetClientCertOption(_ldapHandle, LdapOption.LDAP_OPT_CLIENT_CERTIFICATE, _clientCertificateRoutine); if (certError != (int)ResultCode.Success) { if (LdapErrorMappings.IsLdapError(certError)) { string certerrorMessage = LdapErrorMappings.MapResultCode(certError); throw new LdapException(certError, certerrorMessage); } throw new LdapException(certError); } // When certificate is specified, automatic bind is disabled. AutoBind = false; } // Set the LDAP_OPT_AREC_EXCLUSIVE flag if necessary. if (((LdapDirectoryIdentifier)Directory).FullyQualifiedDnsHostName && !_setFQDNDone) { SessionOptions.SetFqdnRequired(); _setFQDNDone = true; } int error = InternalConnectToServer(); // Failed, throw an exception. if (error != (int)ResultCode.Success) { if (LdapErrorMappings.IsLdapError(error)) { string errorMessage = LdapErrorMappings.MapResultCode(error); throw new LdapException(error, errorMessage); } throw new LdapException(error); } } public void Bind() => BindHelper(_directoryCredential, needSetCredential: false); public void Bind(NetworkCredential newCredential) => BindHelper(newCredential, needSetCredential: true); private void BindHelper(NetworkCredential newCredential, bool needSetCredential) { if (_disposed) { throw new ObjectDisposedException(GetType().Name); } // Throw if user wants to do anonymous bind but specifies credentials. if (AuthType == AuthType.Anonymous && (newCredential != null && (!string.IsNullOrEmpty(newCredential.Password) || string.IsNullOrEmpty(newCredential.UserName)))) { throw new InvalidOperationException(SR.InvalidAuthCredential); } // Set the credential. NetworkCredential tempCredential; if (needSetCredential) { _directoryCredential = tempCredential = (newCredential != null ? new NetworkCredential(newCredential.UserName, newCredential.Password, newCredential.Domain) : null); } else { tempCredential = _directoryCredential; } // Connect to the server first. if (!_connected) { Connect(); _connected = true; } // Bind to the server. string username; string domainName; string password; if (tempCredential != null && tempCredential.UserName.Length == 0 && tempCredential.Password.Length == 0 && tempCredential.Domain.Length == 0) { // Default credentials. username = null; domainName = null; password = null; } else { username = tempCredential?.UserName; domainName = tempCredential?.Domain; password = tempCredential?.Password; } int error; if (AuthType == AuthType.Anonymous) { error = LdapPal.BindToDirectory(_ldapHandle, null, null); } else if (AuthType == AuthType.Basic) { var tempDomainName = new StringBuilder(100); if (domainName != null && domainName.Length != 0) { tempDomainName.Append(domainName); tempDomainName.Append('\\'); } tempDomainName.Append(username); error = LdapPal.BindToDirectory(_ldapHandle, tempDomainName.ToString(), password); } else { var cred = new SEC_WINNT_AUTH_IDENTITY_EX() { version = Interop.SEC_WINNT_AUTH_IDENTITY_VERSION, length = Marshal.SizeOf(typeof(SEC_WINNT_AUTH_IDENTITY_EX)), flags = Interop.SEC_WINNT_AUTH_IDENTITY_UNICODE }; if (AuthType == AuthType.Kerberos) { cred.packageList = Interop.MICROSOFT_KERBEROS_NAME_W; cred.packageListLength = cred.packageList.Length; } if (tempCredential != null) { cred.user = username; cred.userLength = (username == null ? 0 : username.Length); cred.domain = domainName; cred.domainLength = (domainName == null ? 0 : domainName.Length); cred.password = password; cred.passwordLength = (password == null ? 0 : password.Length); } BindMethod method = BindMethod.LDAP_AUTH_NEGOTIATE; switch (AuthType) { case AuthType.Negotiate: method = BindMethod.LDAP_AUTH_NEGOTIATE; break; case AuthType.Kerberos: method = BindMethod.LDAP_AUTH_NEGOTIATE; break; case AuthType.Ntlm: method = BindMethod.LDAP_AUTH_NTLM; break; case AuthType.Digest: method = BindMethod.LDAP_AUTH_DIGEST; break; case AuthType.Sicily: method = BindMethod.LDAP_AUTH_SICILY; break; case AuthType.Dpa: method = BindMethod.LDAP_AUTH_DPA; break; case AuthType.Msn: method = BindMethod.LDAP_AUTH_MSN; break; case AuthType.External: method = BindMethod.LDAP_AUTH_EXTERNAL; break; } error = InternalBind(tempCredential, cred, method); } // Failed, throw exception. if (error != (int)ResultCode.Success) { if (Utility.IsResultCode((ResultCode)error)) { string errorMessage = OperationErrorMappings.MapResultCode(error); throw new DirectoryOperationException(null, errorMessage); } else if (LdapErrorMappings.IsLdapError(error)) { string errorMessage = LdapErrorMappings.MapResultCode(error); string serverErrorMessage = SessionOptions.ServerErrorMessage; if (!string.IsNullOrEmpty(serverErrorMessage)) { throw new LdapException(error, errorMessage, serverErrorMessage); } throw new LdapException(error, errorMessage); } throw new LdapException(error); } // We successfully bound to the server. _bounded = true; // Rebind has been done. _needRebind = false; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { // We need to remove the handle from the handle table. lock (s_objectLock) { if (_ldapHandle != null) { s_handleTable.Remove(_ldapHandle.DangerousGetHandle()); } } } // Close the ldap connection. if (_needDispose && _ldapHandle != null && !_ldapHandle.IsInvalid) { _ldapHandle.Dispose(); } _ldapHandle = null; _disposed = true; } internal LdapControl[] BuildControlArray(DirectoryControlCollection controls, bool serverControl) { LdapControl[] managedControls = null; if (controls != null && controls.Count != 0) { var controlList = new ArrayList(); foreach (DirectoryControl col in controls) { if (serverControl == true) { if (col.ServerSide) { controlList.Add(col); } } else if (!col.ServerSide) { controlList.Add(col); } } if (controlList.Count != 0) { int count = controlList.Count; managedControls = new LdapControl[count]; for (int i = 0; i < count; i++) { managedControls[i] = new LdapControl() { // Get the control type. ldctl_oid = LdapPal.StringToPtr(((DirectoryControl)controlList[i]).Type), // Get the control cricality. ldctl_iscritical = ((DirectoryControl)controlList[i]).IsCritical }; // Get the control value. DirectoryControl tempControl = (DirectoryControl)controlList[i]; byte[] byteControlValue = tempControl.GetValue(); if (byteControlValue == null || byteControlValue.Length == 0) { // Treat the control value as null. managedControls[i].ldctl_value = new BerVal { bv_len = 0, bv_val = IntPtr.Zero }; } else { managedControls[i].ldctl_value = new BerVal { bv_len = byteControlValue.Length, bv_val = Marshal.AllocHGlobal(sizeof(byte) * byteControlValue.Length) }; Marshal.Copy(byteControlValue, 0, managedControls[i].ldctl_value.bv_val, managedControls[i].ldctl_value.bv_len); } } } } return managedControls; } internal LdapMod[] BuildAttributes(CollectionBase directoryAttributes, ArrayList ptrToFree) { LdapMod[] attributes = null; if (directoryAttributes != null && directoryAttributes.Count != 0) { var encoder = new UTF8Encoding(); DirectoryAttributeModificationCollection modificationCollection = null; DirectoryAttributeCollection attributeCollection = null; if (directoryAttributes is DirectoryAttributeModificationCollection) { modificationCollection = (DirectoryAttributeModificationCollection)directoryAttributes; } else { attributeCollection = (DirectoryAttributeCollection)directoryAttributes; } attributes = new LdapMod[directoryAttributes.Count]; for (int i = 0; i < directoryAttributes.Count; i++) { // Get the managed attribute first. DirectoryAttribute modAttribute; if (attributeCollection != null) { modAttribute = attributeCollection[i]; } else { modAttribute = modificationCollection[i]; } attributes[i] = new LdapMod(); // Write the operation type. if (modAttribute is DirectoryAttributeModification) { attributes[i].type = (int)((DirectoryAttributeModification)modAttribute).Operation; } else { attributes[i].type = (int)DirectoryAttributeOperation.Add; } // We treat all the values as binary attributes[i].type |= LDAP_MOD_BVALUES; // Write the attribute name. attributes[i].attribute = LdapPal.StringToPtr(modAttribute.Name); // Write the values. int valuesCount = 0; BerVal[] berValues = null; if (modAttribute.Count > 0) { valuesCount = modAttribute.Count; berValues = new BerVal[valuesCount]; for (int j = 0; j < valuesCount; j++) { byte[] byteArray; if (modAttribute[j] is string) { byteArray = encoder.GetBytes((string)modAttribute[j]); } else if (modAttribute[j] is Uri) { byteArray = encoder.GetBytes(((Uri)modAttribute[j]).ToString()); } else { byteArray = (byte[])modAttribute[j]; } berValues[j] = new BerVal() { bv_len = byteArray.Length, bv_val = Marshal.AllocHGlobal(byteArray.Length) }; // need to free the memory allocated on the heap when we are done ptrToFree.Add(berValues[j].bv_val); Marshal.Copy(byteArray, 0, berValues[j].bv_val, berValues[j].bv_len); } } attributes[i].values = Utility.AllocHGlobalIntPtrArray(valuesCount + 1); int structSize = Marshal.SizeOf(typeof(BerVal)); IntPtr controlPtr; IntPtr tempPtr; int m; for (m = 0; m < valuesCount; m++) { controlPtr = Marshal.AllocHGlobal(structSize); // Need to free the memory allocated on the heap when we are done. ptrToFree.Add(controlPtr); Marshal.StructureToPtr(berValues[m], controlPtr, false); tempPtr = (IntPtr)((long)attributes[i].values + IntPtr.Size * m); Marshal.WriteIntPtr(tempPtr, controlPtr); } tempPtr = (IntPtr)((long)attributes[i].values + IntPtr.Size * m); Marshal.WriteIntPtr(tempPtr, IntPtr.Zero); } } return attributes; } internal async ValueTask<DirectoryResponse> ConstructResponseAsync(int messageId, LdapOperation operation, ResultAll resultType, TimeSpan requestTimeOut, bool exceptionOnTimeOut, bool sync) { var timeout = new LDAP_TIMEVAL() { tv_sec = (int)(requestTimeOut.Ticks / TimeSpan.TicksPerSecond) }; IntPtr ldapResult = IntPtr.Zero; DirectoryResponse response = null; IntPtr requestName = IntPtr.Zero; IntPtr requestValue = IntPtr.Zero; IntPtr entryMessage; bool needAbandon = true; // processing for the partial results retrieval if (resultType != ResultAll.LDAP_MSG_ALL) { // we need to have 0 timeout as we are polling for the results and don't want to wait timeout.tv_sec = 0; timeout.tv_usec = 0; if (resultType == ResultAll.LDAP_MSG_POLLINGALL) { resultType = ResultAll.LDAP_MSG_ALL; } // when doing partial results retrieving, if ldap_result failed, we don't do ldap_abandon here. needAbandon = false; } int error; if (sync) { error = LdapPal.GetResultFromAsyncOperation(_ldapHandle, messageId, (int)resultType, timeout, ref ldapResult); } else { timeout.tv_sec = 0; timeout.tv_usec = 0; int iterationDelay = 1; // Underlying native libraries don't support callback-based function, so we will instead use polling and // use a Stopwatch to track the timeout manually. Stopwatch watch = Stopwatch.StartNew(); while (true) { error = LdapPal.GetResultFromAsyncOperation(_ldapHandle, messageId, (int)resultType, timeout, ref ldapResult); if (error != 0 || (requestTimeOut != Threading.Timeout.InfiniteTimeSpan && watch.Elapsed > requestTimeOut)) { break; } await Task.Delay(Math.Min(iterationDelay, 100)).ConfigureAwait(false); if (iterationDelay < 100) { iterationDelay *= 2; } } watch.Stop(); } if (error != -1 && error != 0) { // parsing the result int serverError = 0; try { int resultError = 0; string responseDn = null; string responseMessage = null; Uri[] responseReferral = null; DirectoryControl[] responseControl = null; // ldap_parse_result skips over messages of type LDAP_RES_SEARCH_ENTRY and LDAP_RES_SEARCH_REFERRAL if (error != (int)LdapResult.LDAP_RES_SEARCH_ENTRY && error != (int)LdapResult.LDAP_RES_REFERRAL) { resultError = ConstructParsedResult(ldapResult, ref serverError, ref responseDn, ref responseMessage, ref responseReferral, ref responseControl); } if (resultError == 0) { resultError = serverError; if (error == (int)LdapResult.LDAP_RES_ADD) { response = new AddResponse(responseDn, responseControl, (ResultCode)resultError, responseMessage, responseReferral); } else if (error == (int)LdapResult.LDAP_RES_MODIFY) { response = new ModifyResponse(responseDn, responseControl, (ResultCode)resultError, responseMessage, responseReferral); } else if (error == (int)LdapResult.LDAP_RES_DELETE) { response = new DeleteResponse(responseDn, responseControl, (ResultCode)resultError, responseMessage, responseReferral); } else if (error == (int)LdapResult.LDAP_RES_MODRDN) { response = new ModifyDNResponse(responseDn, responseControl, (ResultCode)resultError, responseMessage, responseReferral); } else if (error == (int)LdapResult.LDAP_RES_COMPARE) { response = new CompareResponse(responseDn, responseControl, (ResultCode)resultError, responseMessage, responseReferral); } else if (error == (int)LdapResult.LDAP_RES_EXTENDED) { response = new ExtendedResponse(responseDn, responseControl, (ResultCode)resultError, responseMessage, responseReferral); if (resultError == (int)ResultCode.Success) { resultError = LdapPal.ParseExtendedResult(_ldapHandle, ldapResult, ref requestName, ref requestValue, 0 /*not free it*/); if (resultError == 0) { string name = null; if (requestName != IntPtr.Zero) { name = LdapPal.PtrToString(requestName); } BerVal val = null; byte[] requestValueArray = null; if (requestValue != IntPtr.Zero) { val = new BerVal(); Marshal.PtrToStructure(requestValue, val); if (val.bv_len != 0 && val.bv_val != IntPtr.Zero) { requestValueArray = new byte[val.bv_len]; Marshal.Copy(val.bv_val, requestValueArray, 0, val.bv_len); } } ((ExtendedResponse)response).ResponseName = name; ((ExtendedResponse)response).ResponseValue = requestValueArray; } } } else if (error == (int)LdapResult.LDAP_RES_SEARCH_RESULT || error == (int)LdapResult.LDAP_RES_SEARCH_ENTRY || error == (int)LdapResult.LDAP_RES_REFERRAL) { response = new SearchResponse(responseDn, responseControl, (ResultCode)resultError, responseMessage, responseReferral); //set the flag here so our partial result processor knows whether the search is done or not if (error == (int)LdapResult.LDAP_RES_SEARCH_RESULT) { ((SearchResponse)response).searchDone = true; } SearchResultEntryCollection searchResultEntries = new SearchResultEntryCollection(); SearchResultReferenceCollection searchResultReferences = new SearchResultReferenceCollection(); // parsing the resultentry entryMessage = LdapPal.GetFirstEntryFromResult(_ldapHandle, ldapResult); int entrycount = 0; while (entryMessage != IntPtr.Zero) { SearchResultEntry entry = ConstructEntry(entryMessage); if (entry != null) { searchResultEntries.Add(entry); } entrycount++; entryMessage = LdapPal.GetNextEntryFromResult(_ldapHandle, entryMessage); } // Parse the reference. IntPtr referenceMessage = LdapPal.GetFirstReferenceFromResult(_ldapHandle, ldapResult); while (referenceMessage != IntPtr.Zero) { SearchResultReference reference = ConstructReference(referenceMessage); if (reference != null) { searchResultReferences.Add(reference); } referenceMessage = LdapPal.GetNextReferenceFromResult(_ldapHandle, referenceMessage); } ((SearchResponse)response).Entries = searchResultEntries; ((SearchResponse)response).References = searchResultReferences; } if (resultError != (int)ResultCode.Success && resultError != (int)ResultCode.CompareFalse && resultError != (int)ResultCode.CompareTrue && resultError != (int)ResultCode.Referral && resultError != (int)ResultCode.ReferralV2) { // Throw operation exception. if (Utility.IsResultCode((ResultCode)resultError)) { throw new DirectoryOperationException(response, OperationErrorMappings.MapResultCode(resultError)); } else { // This should not occur. throw new DirectoryOperationException(response); } } return response; } else { // Fall through, throw the exception beow. error = resultError; } } finally { if (requestName != IntPtr.Zero) { LdapPal.FreeMemory(requestName); } if (requestValue != IntPtr.Zero) { LdapPal.FreeMemory(requestValue); } if (ldapResult != IntPtr.Zero) { LdapPal.FreeMessage(ldapResult); } } } else { // ldap_result failed if (error == 0) { if (exceptionOnTimeOut) { // Client side timeout. error = (int)LdapError.TimeOut; } else { // If we don't throw exception on time out (notification search for example), we // just return an empty response. return null; } } else { error = LdapPal.GetLastErrorFromConnection(_ldapHandle); } // Abandon the request. if (needAbandon) { LdapPal.CancelDirectoryAsyncOperation(_ldapHandle, messageId); } } // Throw the proper exception here. throw ConstructException(error, operation); } internal unsafe int ConstructParsedResult(IntPtr ldapResult, ref int serverError, ref string responseDn, ref string responseMessage, ref Uri[] responseReferral, ref DirectoryControl[] responseControl) { IntPtr dn = IntPtr.Zero; IntPtr message = IntPtr.Zero; IntPtr referral = IntPtr.Zero; IntPtr control = IntPtr.Zero; try { int resultError = LdapPal.ParseResult(_ldapHandle, ldapResult, ref serverError, ref dn, ref message, ref referral, ref control, 0 /* not free it */); if (resultError == 0) { // Parse the dn. responseDn = LdapPal.PtrToString(dn); // Parse the message. responseMessage = LdapPal.PtrToString(message); // Parse the referral. if (referral != IntPtr.Zero) { char** tempPtr = (char**)referral; char* singleReferral = tempPtr[0]; int i = 0; var referralList = new ArrayList(); while (singleReferral != null) { string s = LdapPal.PtrToString((IntPtr)singleReferral); referralList.Add(s); i++; singleReferral = tempPtr[i]; } if (referralList.Count > 0) { responseReferral = new Uri[referralList.Count]; for (int j = 0; j < referralList.Count; j++) { responseReferral[j] = new Uri((string)referralList[j]); } } } // Parse the control. if (control != IntPtr.Zero) { int i = 0; IntPtr tempControlPtr = control; IntPtr singleControl = Marshal.ReadIntPtr(tempControlPtr, 0); var controlList = new ArrayList(); while (singleControl != IntPtr.Zero) { DirectoryControl directoryControl = ConstructControl(singleControl); controlList.Add(directoryControl); i++; singleControl = Marshal.ReadIntPtr(tempControlPtr, i * IntPtr.Size); } responseControl = new DirectoryControl[controlList.Count]; controlList.CopyTo(responseControl); } } else { // we need to take care of one special case, when can't connect to the server, ldap_parse_result fails with local error if (resultError == (int)LdapError.LocalError) { int tmpResult = LdapPal.ResultToErrorCode(_ldapHandle, ldapResult, 0 /* not free it */); if (tmpResult != 0) { resultError = tmpResult; } } } return resultError; } finally { if (dn != IntPtr.Zero) { LdapPal.FreeMemory(dn); } if (message != IntPtr.Zero) { LdapPal.FreeMemory(message); } if (referral != IntPtr.Zero) { LdapPal.FreeValue(referral); } if (control != IntPtr.Zero) { LdapPal.FreeDirectoryControls(control); } } } internal SearchResultEntry ConstructEntry(IntPtr entryMessage) { IntPtr dn = IntPtr.Zero; IntPtr attribute = IntPtr.Zero; IntPtr address = IntPtr.Zero; try { // Get the dn. string entryDn = null; dn = LdapPal.GetDistinguishedName(_ldapHandle, entryMessage); if (dn != IntPtr.Zero) { entryDn = LdapPal.PtrToString(dn); LdapPal.FreeMemory(dn); dn = IntPtr.Zero; } SearchResultEntry resultEntry = new SearchResultEntry(entryDn); SearchResultAttributeCollection attributes = resultEntry.Attributes; // Get attributes. attribute = LdapPal.GetFirstAttributeFromEntry(_ldapHandle, entryMessage, ref address); int tempcount = 0; while (attribute != IntPtr.Zero) { DirectoryAttribute attr = ConstructAttribute(entryMessage, attribute); attributes.Add(attr.Name, attr); LdapPal.FreeMemory(attribute); tempcount++; attribute = LdapPal.GetNextAttributeFromResult(_ldapHandle, entryMessage, address); } if (address != IntPtr.Zero) { BerPal.FreeBerElement(address, 0); address = IntPtr.Zero; } return resultEntry; } finally { if (dn != IntPtr.Zero) { LdapPal.FreeMemory(dn); } if (attribute != IntPtr.Zero) { LdapPal.FreeMemory(attribute); } if (address != IntPtr.Zero) { BerPal.FreeBerElement(address, 0); } } } internal DirectoryAttribute ConstructAttribute(IntPtr entryMessage, IntPtr attributeName) { var attribute = new DirectoryAttribute() { _isSearchResult = true }; string name = LdapPal.PtrToString(attributeName); attribute.Name = name; IntPtr valuesArray = LdapPal.GetValuesFromAttribute(_ldapHandle, entryMessage, name); try { if (valuesArray != IntPtr.Zero) { int count = 0; IntPtr tempPtr = Marshal.ReadIntPtr(valuesArray, IntPtr.Size * count); while (tempPtr != IntPtr.Zero) { BerVal bervalue = new BerVal(); Marshal.PtrToStructure(tempPtr, bervalue); byte[] byteArray; if (bervalue.bv_len > 0 && bervalue.bv_val != IntPtr.Zero) { byteArray = new byte[bervalue.bv_len]; Marshal.Copy(bervalue.bv_val, byteArray, 0, bervalue.bv_len); attribute.Add(byteArray); } count++; tempPtr = Marshal.ReadIntPtr(valuesArray, IntPtr.Size * count); } } } finally { if (valuesArray != IntPtr.Zero) { LdapPal.FreeAttributes(valuesArray); } } return attribute; } internal SearchResultReference ConstructReference(IntPtr referenceMessage) { IntPtr referenceArray = IntPtr.Zero; int error = LdapPal.ParseReference(_ldapHandle, referenceMessage, ref referenceArray); try { if (error == 0) { var referralList = new ArrayList(); IntPtr tempPtr; int count = 0; if (referenceArray != IntPtr.Zero) { tempPtr = Marshal.ReadIntPtr(referenceArray, IntPtr.Size * count); while (tempPtr != IntPtr.Zero) { string s = LdapPal.PtrToString(tempPtr); referralList.Add(s); count++; tempPtr = Marshal.ReadIntPtr(referenceArray, IntPtr.Size * count); } LdapPal.FreeValue(referenceArray); referenceArray = IntPtr.Zero; } if (referralList.Count > 0) { Uri[] uris = new Uri[referralList.Count]; for (int i = 0; i < referralList.Count; i++) { uris[i] = new Uri((string)referralList[i]); } return new SearchResultReference(uris); } } } finally { if (referenceArray != IntPtr.Zero) { LdapPal.FreeValue(referenceArray); } } return null; } private DirectoryException ConstructException(int error, LdapOperation operation) { DirectoryResponse response = null; if (Utility.IsResultCode((ResultCode)error)) { if (operation == LdapOperation.LdapAdd) { response = new AddResponse(null, null, (ResultCode)error, OperationErrorMappings.MapResultCode(error), null); } else if (operation == LdapOperation.LdapModify) { response = new ModifyResponse(null, null, (ResultCode)error, OperationErrorMappings.MapResultCode(error), null); } else if (operation == LdapOperation.LdapDelete) { response = new DeleteResponse(null, null, (ResultCode)error, OperationErrorMappings.MapResultCode(error), null); } else if (operation == LdapOperation.LdapModifyDn) { response = new ModifyDNResponse(null, null, (ResultCode)error, OperationErrorMappings.MapResultCode(error), null); } else if (operation == LdapOperation.LdapCompare) { response = new CompareResponse(null, null, (ResultCode)error, OperationErrorMappings.MapResultCode(error), null); } else if (operation == LdapOperation.LdapSearch) { response = new SearchResponse(null, null, (ResultCode)error, OperationErrorMappings.MapResultCode(error), null); } else if (operation == LdapOperation.LdapExtendedRequest) { response = new ExtendedResponse(null, null, (ResultCode)error, OperationErrorMappings.MapResultCode(error), null); } string errorMessage = OperationErrorMappings.MapResultCode(error); return new DirectoryOperationException(response, errorMessage); } else { if (LdapErrorMappings.IsLdapError(error)) { string errorMessage = LdapErrorMappings.MapResultCode(error); string serverErrorMessage = SessionOptions.ServerErrorMessage; if (!string.IsNullOrEmpty(serverErrorMessage)) { throw new LdapException(error, errorMessage, serverErrorMessage); } return new LdapException(error, errorMessage); } return new LdapException(error); } } private DirectoryControl ConstructControl(IntPtr controlPtr) { LdapControl control = new LdapControl(); Marshal.PtrToStructure(controlPtr, control); Debug.Assert(control.ldctl_oid != IntPtr.Zero); string controlType = LdapPal.PtrToString(control.ldctl_oid); byte[] bytes = new byte[control.ldctl_value.bv_len]; Marshal.Copy(control.ldctl_value.bv_val, bytes, 0, control.ldctl_value.bv_len); bool criticality = control.ldctl_iscritical; return new DirectoryControl(controlType, bytes, criticality, true); } private bool SameCredential(NetworkCredential oldCredential, NetworkCredential newCredential) { if (oldCredential == null && newCredential == null) { return true; } else if (oldCredential == null && newCredential != null) { return false; } else if (oldCredential != null && newCredential == null) { return false; } else { if (oldCredential.Domain == newCredential.Domain && oldCredential.UserName == newCredential.UserName && oldCredential.Password == newCredential.Password) { return true; } else { return false; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections; using System.ComponentModel; using System.Diagnostics; using System.Net; using System.Runtime.InteropServices; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml; namespace System.DirectoryServices.Protocols { internal delegate DirectoryResponse GetLdapResponseCallback(int messageId, LdapOperation operation, ResultAll resultType, TimeSpan requestTimeout, bool exceptionOnTimeOut); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate bool QUERYCLIENTCERT(IntPtr Connection, IntPtr trusted_CAs, ref IntPtr certificateHandle); public partial class LdapConnection : DirectoryConnection, IDisposable { internal enum LdapResult { LDAP_RES_SEARCH_RESULT = 0x65, LDAP_RES_SEARCH_ENTRY = 0x64, LDAP_RES_MODIFY = 0x67, LDAP_RES_ADD = 0x69, LDAP_RES_DELETE = 0x6b, LDAP_RES_MODRDN = 0x6d, LDAP_RES_COMPARE = 0x6f, LDAP_RES_REFERRAL = 0x73, LDAP_RES_EXTENDED = 0x78 } private const int LDAP_MOD_BVALUES = 0x80; internal static readonly object s_objectLock = new object(); internal static readonly Hashtable s_handleTable = new Hashtable(); private static readonly Hashtable s_asyncResultTable = Hashtable.Synchronized(new Hashtable()); private static readonly ManualResetEvent s_waitHandle = new ManualResetEvent(false); private static readonly LdapPartialResultsProcessor s_partialResultsProcessor = new LdapPartialResultsProcessor(s_waitHandle); private AuthType _connectionAuthType = AuthType.Negotiate; internal bool _needDispose = true; internal ConnectionHandle _ldapHandle; internal bool _disposed; private bool _bounded; private bool _needRebind; private bool _connected; internal QUERYCLIENTCERT _clientCertificateRoutine; public LdapConnection(string server) : this(new LdapDirectoryIdentifier(server)) { } public LdapConnection(LdapDirectoryIdentifier identifier) : this(identifier, null, AuthType.Negotiate) { } public LdapConnection(LdapDirectoryIdentifier identifier, NetworkCredential credential) : this(identifier, credential, AuthType.Negotiate) { } public LdapConnection(LdapDirectoryIdentifier identifier, NetworkCredential credential, AuthType authType) { _directoryIdentifier = identifier; _directoryCredential = (credential != null) ? new NetworkCredential(credential.UserName, credential.Password, credential.Domain) : null; _connectionAuthType = authType; if (authType < AuthType.Anonymous || authType > AuthType.Kerberos) { throw new InvalidEnumArgumentException(nameof(authType), (int)authType, typeof(AuthType)); } // Throw if user wants to do anonymous bind but specifies credentials. if (AuthType == AuthType.Anonymous && (_directoryCredential != null && (!string.IsNullOrEmpty(_directoryCredential.Password) || !string.IsNullOrEmpty(_directoryCredential.UserName)))) { throw new ArgumentException(SR.InvalidAuthCredential); } Init(); SessionOptions = new LdapSessionOptions(this); _clientCertificateRoutine = new QUERYCLIENTCERT(ProcessClientCertificate); } internal LdapConnection(LdapDirectoryIdentifier identifier, NetworkCredential credential, AuthType authType, IntPtr handle) { _directoryIdentifier = identifier; _needDispose = false; _ldapHandle = new ConnectionHandle(handle, _needDispose); _directoryCredential = credential; _connectionAuthType = authType; SessionOptions = new LdapSessionOptions(this); _clientCertificateRoutine = new QUERYCLIENTCERT(ProcessClientCertificate); } ~LdapConnection() => Dispose(false); public override TimeSpan Timeout { get => _connectionTimeOut; set { if (value < TimeSpan.Zero) { throw new ArgumentException(SR.NoNegativeTimeLimit, nameof(value)); } // Prevent integer overflow. if (value.TotalSeconds > int.MaxValue) { throw new ArgumentException(SR.TimespanExceedMax, nameof(value)); } _connectionTimeOut = value; } } public AuthType AuthType { get => _connectionAuthType; set { if (value < AuthType.Anonymous || value > AuthType.Kerberos) { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(AuthType)); } // If the change is made after we have bound to the server and value is really // changed, set the flag to indicate the need to do rebind. if (_bounded && (value != _connectionAuthType)) { _needRebind = true; } _connectionAuthType = value; } } public LdapSessionOptions SessionOptions { get; } public override NetworkCredential Credential { set { if (_bounded && !SameCredential(_directoryCredential, value)) { _needRebind = true; } _directoryCredential = (value != null) ? new NetworkCredential(value.UserName, value.Password, value.Domain) : null; } } public bool AutoBind { get; set; } = true; internal bool NeedDispose { get => _needDispose; set { if (_ldapHandle != null) { _ldapHandle._needDispose = value; } _needDispose = value; } } internal void Init() { string hostname = null; string[] servers = ((LdapDirectoryIdentifier)_directoryIdentifier)?.Servers; if (servers != null && servers.Length != 0) { var temp = new StringBuilder(200); for (int i = 0; i < servers.Length; i++) { if (servers[i] != null) { temp.Append(servers[i]); if (i < servers.Length - 1) { temp.Append(' '); } } } if (temp.Length != 0) { hostname = temp.ToString(); } } InternalInitConnectionHandle(hostname); // Create a WeakReference object with the target of ldapHandle and put it into our handle table. lock (s_objectLock) { if (s_handleTable[_ldapHandle.DangerousGetHandle()] != null) { s_handleTable.Remove(_ldapHandle.DangerousGetHandle()); } s_handleTable.Add(_ldapHandle.DangerousGetHandle(), new WeakReference(this)); } } public override DirectoryResponse SendRequest(DirectoryRequest request) { // No request specific timeout is specified, use the connection timeout. return SendRequest(request, _connectionTimeOut); } public DirectoryResponse SendRequest(DirectoryRequest request, TimeSpan requestTimeout) { if (_disposed) { throw new ObjectDisposedException(GetType().Name); } if (request == null) { throw new ArgumentNullException(nameof(request)); } if (request is DsmlAuthRequest) { throw new NotSupportedException(SR.DsmlAuthRequestNotSupported); } int messageID = 0; int error = SendRequestHelper(request, ref messageID); LdapOperation operation = LdapOperation.LdapSearch; if (request is DeleteRequest) { operation = LdapOperation.LdapDelete; } else if (request is AddRequest) { operation = LdapOperation.LdapAdd; } else if (request is ModifyRequest) { operation = LdapOperation.LdapModify; } else if (request is SearchRequest) { operation = LdapOperation.LdapSearch; } else if (request is ModifyDNRequest) { operation = LdapOperation.LdapModifyDn; } else if (request is CompareRequest) { operation = LdapOperation.LdapCompare; } else if (request is ExtendedRequest) { operation = LdapOperation.LdapExtendedRequest; } if (error == 0 && messageID != -1) { ValueTask<DirectoryResponse> vt = ConstructResponseAsync(messageID, operation, ResultAll.LDAP_MSG_ALL, requestTimeout, true, sync: true); Debug.Assert(vt.IsCompleted); return vt.GetAwaiter().GetResult(); } else { if (error == 0) { // Success code but message is -1, unexpected. error = LdapPal.GetLastErrorFromConnection(_ldapHandle); } throw ConstructException(error, operation); } } public IAsyncResult BeginSendRequest(DirectoryRequest request, PartialResultProcessing partialMode, AsyncCallback callback, object state) { return BeginSendRequest(request, _connectionTimeOut, partialMode, callback, state); } public IAsyncResult BeginSendRequest(DirectoryRequest request, TimeSpan requestTimeout, PartialResultProcessing partialMode, AsyncCallback callback, object state) { if (_disposed) { throw new ObjectDisposedException(GetType().Name); } if (request == null) { throw new ArgumentNullException(nameof(request)); } if (partialMode < PartialResultProcessing.NoPartialResultSupport || partialMode > PartialResultProcessing.ReturnPartialResultsAndNotifyCallback) { throw new InvalidEnumArgumentException(nameof(partialMode), (int)partialMode, typeof(PartialResultProcessing)); } if (partialMode != PartialResultProcessing.NoPartialResultSupport && !(request is SearchRequest)) { throw new NotSupportedException(SR.PartialResultsNotSupported); } if (partialMode == PartialResultProcessing.ReturnPartialResultsAndNotifyCallback && callback == null) { throw new ArgumentException(SR.CallBackIsNull, nameof(callback)); } int messageID = 0; int error = SendRequestHelper(request, ref messageID); LdapOperation operation = LdapOperation.LdapSearch; if (request is DeleteRequest) { operation = LdapOperation.LdapDelete; } else if (request is AddRequest) { operation = LdapOperation.LdapAdd; } else if (request is ModifyRequest) { operation = LdapOperation.LdapModify; } else if (request is SearchRequest) { operation = LdapOperation.LdapSearch; } else if (request is ModifyDNRequest) { operation = LdapOperation.LdapModifyDn; } else if (request is CompareRequest) { operation = LdapOperation.LdapCompare; } else if (request is ExtendedRequest) { operation = LdapOperation.LdapExtendedRequest; } if (error == 0 && messageID != -1) { if (partialMode == PartialResultProcessing.NoPartialResultSupport) { var requestState = new LdapRequestState(); var asyncResult = new LdapAsyncResult(callback, state, false); requestState._ldapAsync = asyncResult; asyncResult._resultObject = requestState; s_asyncResultTable.Add(asyncResult, messageID); _ = ResponseCallback(ConstructResponseAsync(messageID, operation, ResultAll.LDAP_MSG_ALL, requestTimeout, true, sync: false), requestState); static async Task ResponseCallback(ValueTask<DirectoryResponse> vt, LdapRequestState requestState) { try { DirectoryResponse response = await vt.ConfigureAwait(false); requestState._response = response; } catch (Exception e) { requestState._exception = e; requestState._response = null; } // Signal waitable object, indicate operation completed and fire callback. requestState._ldapAsync._manualResetEvent.Set(); requestState._ldapAsync._completed = true; if (requestState._ldapAsync._callback != null && !requestState._abortCalled) { requestState._ldapAsync._callback(requestState._ldapAsync); } } return asyncResult; } else { // the user registers to retrieve partial results bool partialCallback = partialMode == PartialResultProcessing.ReturnPartialResultsAndNotifyCallback; var asyncResult = new LdapPartialAsyncResult(messageID, callback, state, true, this, partialCallback, requestTimeout); s_partialResultsProcessor.Add(asyncResult); return asyncResult; } } if (error == 0) { // Success code but message is -1, unexpected. error = LdapPal.GetLastErrorFromConnection(_ldapHandle); } throw ConstructException(error, operation); } public void Abort(IAsyncResult asyncResult) { if (_disposed) { throw new ObjectDisposedException(GetType().Name); } if (asyncResult == null) { throw new ArgumentNullException(nameof(asyncResult)); } if (!(asyncResult is LdapAsyncResult)) { throw new ArgumentException(SR.Format(SR.NotReturnedAsyncResult, nameof(asyncResult))); } int messageId; LdapAsyncResult result = (LdapAsyncResult)asyncResult; if (!result._partialResults) { if (!s_asyncResultTable.Contains(asyncResult)) { throw new ArgumentException(SR.InvalidAsyncResult); } messageId = (int)(s_asyncResultTable[asyncResult]); // remove the asyncResult from our connection table s_asyncResultTable.Remove(asyncResult); } else { s_partialResultsProcessor.Remove((LdapPartialAsyncResult)asyncResult); messageId = ((LdapPartialAsyncResult)asyncResult)._messageID; } // Cancel the request. LdapPal.CancelDirectoryAsyncOperation(_ldapHandle, messageId); LdapRequestState resultObject = result._resultObject; if (resultObject != null) { resultObject._abortCalled = true; } } public PartialResultsCollection GetPartialResults(IAsyncResult asyncResult) { if (_disposed) { throw new ObjectDisposedException(GetType().Name); } if (asyncResult == null) { throw new ArgumentNullException(nameof(asyncResult)); } if (!(asyncResult is LdapAsyncResult)) { throw new ArgumentException(SR.Format(SR.NotReturnedAsyncResult, nameof(asyncResult))); } if (!(asyncResult is LdapPartialAsyncResult)) { throw new InvalidOperationException(SR.NoPartialResults); } return s_partialResultsProcessor.GetPartialResults((LdapPartialAsyncResult)asyncResult); } public DirectoryResponse EndSendRequest(IAsyncResult asyncResult) { if (_disposed) { throw new ObjectDisposedException(GetType().Name); } if (asyncResult == null) { throw new ArgumentNullException(nameof(asyncResult)); } if (!(asyncResult is LdapAsyncResult)) { throw new ArgumentException(SR.Format(SR.NotReturnedAsyncResult, nameof(asyncResult))); } LdapAsyncResult result = (LdapAsyncResult)asyncResult; if (!result._partialResults) { // Not a partial results. if (!s_asyncResultTable.Contains(asyncResult)) { throw new ArgumentException(SR.InvalidAsyncResult); } // Remove the asyncResult from our connection table. s_asyncResultTable.Remove(asyncResult); asyncResult.AsyncWaitHandle.WaitOne(); if (result._resultObject._exception != null) { throw result._resultObject._exception; } return result._resultObject._response; } // Deal with partial results. s_partialResultsProcessor.NeedCompleteResult((LdapPartialAsyncResult)asyncResult); asyncResult.AsyncWaitHandle.WaitOne(); return s_partialResultsProcessor.GetCompleteResult((LdapPartialAsyncResult)asyncResult); } private int SendRequestHelper(DirectoryRequest request, ref int messageID) { IntPtr serverControlArray = IntPtr.Zero; LdapControl[] managedServerControls = null; IntPtr clientControlArray = IntPtr.Zero; LdapControl[] managedClientControls = null; var ptrToFree = new ArrayList(); LdapMod[] modifications = null; IntPtr modArray = IntPtr.Zero; int addModCount = 0; BerVal berValuePtr = null; IntPtr searchAttributes = IntPtr.Zero; int attributeCount = 0; int error = 0; // Connect to the server first if have not done so. if (!_connected) { Connect(); _connected = true; } // Bind if user has not turned off automatic bind, have not done so or there is a need // to do rebind, also connectionless LDAP does not need to do bind. if (AutoBind && (!_bounded || _needRebind) && ((LdapDirectoryIdentifier)Directory).Connectionless != true) { Debug.WriteLine("rebind occurs\n"); Bind(); } try { IntPtr tempPtr = IntPtr.Zero; // Build server control. managedServerControls = BuildControlArray(request.Controls, true); int structSize = Marshal.SizeOf(typeof(LdapControl)); if (managedServerControls != null) { serverControlArray = Utility.AllocHGlobalIntPtrArray(managedServerControls.Length + 1); for (int i = 0; i < managedServerControls.Length; i++) { IntPtr controlPtr = Marshal.AllocHGlobal(structSize); Marshal.StructureToPtr(managedServerControls[i], controlPtr, false); tempPtr = (IntPtr)((long)serverControlArray + IntPtr.Size * i); Marshal.WriteIntPtr(tempPtr, controlPtr); } tempPtr = (IntPtr)((long)serverControlArray + IntPtr.Size * managedServerControls.Length); Marshal.WriteIntPtr(tempPtr, IntPtr.Zero); } // build client control managedClientControls = BuildControlArray(request.Controls, false); if (managedClientControls != null) { clientControlArray = Utility.AllocHGlobalIntPtrArray(managedClientControls.Length + 1); for (int i = 0; i < managedClientControls.Length; i++) { IntPtr controlPtr = Marshal.AllocHGlobal(structSize); Marshal.StructureToPtr(managedClientControls[i], controlPtr, false); tempPtr = (IntPtr)((long)clientControlArray + IntPtr.Size * i); Marshal.WriteIntPtr(tempPtr, controlPtr); } tempPtr = (IntPtr)((long)clientControlArray + IntPtr.Size * managedClientControls.Length); Marshal.WriteIntPtr(tempPtr, IntPtr.Zero); } if (request is DeleteRequest) { // It is an delete operation. error = LdapPal.DeleteDirectoryEntry(_ldapHandle, ((DeleteRequest)request).DistinguishedName, serverControlArray, clientControlArray, ref messageID); } else if (request is ModifyDNRequest) { // It is a modify dn operation error = LdapPal.RenameDirectoryEntry( _ldapHandle, ((ModifyDNRequest)request).DistinguishedName, ((ModifyDNRequest)request).NewName, ((ModifyDNRequest)request).NewParentDistinguishedName, ((ModifyDNRequest)request).DeleteOldRdn ? 1 : 0, serverControlArray, clientControlArray, ref messageID); } else if (request is CompareRequest compareRequest) { // It is a compare request. DirectoryAttribute assertion = compareRequest.Assertion; if (assertion == null) { throw new ArgumentException(SR.WrongAssertionCompare); } if (assertion.Count != 1) { throw new ArgumentException(SR.WrongNumValuesCompare); } // Process the attribute. string stringValue = null; if (assertion[0] is byte[] byteArray) { if (byteArray != null && byteArray.Length != 0) { berValuePtr = new BerVal { bv_len = byteArray.Length, bv_val = Marshal.AllocHGlobal(byteArray.Length) }; Marshal.Copy(byteArray, 0, berValuePtr.bv_val, byteArray.Length); } } else { stringValue = assertion[0].ToString(); } // It is a compare request. error = LdapPal.CompareDirectoryEntries( _ldapHandle, ((CompareRequest)request).DistinguishedName, assertion.Name, stringValue, berValuePtr, serverControlArray, clientControlArray, ref messageID); } else if (request is AddRequest || request is ModifyRequest) { // Build the attributes. if (request is AddRequest) { modifications = BuildAttributes(((AddRequest)request).Attributes, ptrToFree); } else { modifications = BuildAttributes(((ModifyRequest)request).Modifications, ptrToFree); } addModCount = (modifications == null ? 1 : modifications.Length + 1); modArray = Utility.AllocHGlobalIntPtrArray(addModCount); int modStructSize = Marshal.SizeOf(typeof(LdapMod)); int i = 0; for (i = 0; i < addModCount - 1; i++) { IntPtr controlPtr = Marshal.AllocHGlobal(modStructSize); Marshal.StructureToPtr(modifications[i], controlPtr, false); tempPtr = (IntPtr)((long)modArray + IntPtr.Size * i); Marshal.WriteIntPtr(tempPtr, controlPtr); } tempPtr = (IntPtr)((long)modArray + IntPtr.Size * i); Marshal.WriteIntPtr(tempPtr, IntPtr.Zero); if (request is AddRequest) { error = LdapPal.AddDirectoryEntry( _ldapHandle, ((AddRequest)request).DistinguishedName, modArray, serverControlArray, clientControlArray, ref messageID); } else { error = LdapPal.ModifyDirectoryEntry( _ldapHandle, ((ModifyRequest)request).DistinguishedName, modArray, serverControlArray, clientControlArray, ref messageID); } } else if (request is ExtendedRequest extendedRequest) { string name = extendedRequest.RequestName; byte[] val = extendedRequest.RequestValue; // process the requestvalue if (val != null && val.Length != 0) { berValuePtr = new BerVal() { bv_len = val.Length, bv_val = Marshal.AllocHGlobal(val.Length) }; Marshal.Copy(val, 0, berValuePtr.bv_val, val.Length); } error = LdapPal.ExtendedDirectoryOperation( _ldapHandle, name, berValuePtr, serverControlArray, clientControlArray, ref messageID); } else if (request is SearchRequest searchRequest) { // Process the filter. object filter = searchRequest.Filter; if (filter != null) { // LdapConnection only supports ldap filter. if (filter is XmlDocument) { throw new ArgumentException(SR.InvalidLdapSearchRequestFilter); } } string searchRequestFilter = (string)filter; // Process the attributes. attributeCount = (searchRequest.Attributes == null ? 0 : searchRequest.Attributes.Count); if (attributeCount != 0) { searchAttributes = Utility.AllocHGlobalIntPtrArray(attributeCount + 1); int i = 0; for (i = 0; i < attributeCount; i++) { IntPtr controlPtr = LdapPal.StringToPtr(searchRequest.Attributes[i]); tempPtr = (IntPtr)((long)searchAttributes + IntPtr.Size * i); Marshal.WriteIntPtr(tempPtr, controlPtr); } tempPtr = (IntPtr)((long)searchAttributes + IntPtr.Size * i); Marshal.WriteIntPtr(tempPtr, IntPtr.Zero); } // Process the scope. int searchScope = (int)searchRequest.Scope; // Process the timelimit. int searchTimeLimit = (int)(searchRequest.TimeLimit.Ticks / TimeSpan.TicksPerSecond); // Process the alias. DereferenceAlias searchAliases = SessionOptions.DerefAlias; SessionOptions.DerefAlias = searchRequest.Aliases; try { error = LdapPal.SearchDirectory( _ldapHandle, searchRequest.DistinguishedName, searchScope, searchRequestFilter, searchAttributes, searchRequest.TypesOnly, serverControlArray, clientControlArray, searchTimeLimit, searchRequest.SizeLimit, ref messageID); } finally { // Revert back. SessionOptions.DerefAlias = searchAliases; } } else { throw new NotSupportedException(SR.InvliadRequestType); } // The asynchronous call itself timeout, this actually means that we time out the // LDAP_OPT_SEND_TIMEOUT specified in the session option wldap32 does not differentiate // that, but the application caller actually needs this information to determin what to // do with the error code if (error == (int)LdapError.TimeOut) { error = (int)LdapError.SendTimeOut; } return error; } finally { GC.KeepAlive(modifications); if (serverControlArray != IntPtr.Zero) { // Release the memory from the heap. for (int i = 0; i < managedServerControls.Length; i++) { IntPtr tempPtr = Marshal.ReadIntPtr(serverControlArray, IntPtr.Size * i); if (tempPtr != IntPtr.Zero) { Marshal.FreeHGlobal(tempPtr); } } Marshal.FreeHGlobal(serverControlArray); } if (managedServerControls != null) { for (int i = 0; i < managedServerControls.Length; i++) { if (managedServerControls[i].ldctl_oid != IntPtr.Zero) { Marshal.FreeHGlobal(managedServerControls[i].ldctl_oid); } if (managedServerControls[i].ldctl_value != null) { if (managedServerControls[i].ldctl_value.bv_val != IntPtr.Zero) { Marshal.FreeHGlobal(managedServerControls[i].ldctl_value.bv_val); } } } } if (clientControlArray != IntPtr.Zero) { // Release the memory from the heap. for (int i = 0; i < managedClientControls.Length; i++) { IntPtr tempPtr = Marshal.ReadIntPtr(clientControlArray, IntPtr.Size * i); if (tempPtr != IntPtr.Zero) { Marshal.FreeHGlobal(tempPtr); } } Marshal.FreeHGlobal(clientControlArray); } if (managedClientControls != null) { for (int i = 0; i < managedClientControls.Length; i++) { if (managedClientControls[i].ldctl_oid != IntPtr.Zero) { Marshal.FreeHGlobal(managedClientControls[i].ldctl_oid); } if (managedClientControls[i].ldctl_value != null) { if (managedClientControls[i].ldctl_value.bv_val != IntPtr.Zero) { Marshal.FreeHGlobal(managedClientControls[i].ldctl_value.bv_val); } } } } if (modArray != IntPtr.Zero) { // release the memory from the heap for (int i = 0; i < addModCount - 1; i++) { IntPtr tempPtr = Marshal.ReadIntPtr(modArray, IntPtr.Size * i); if (tempPtr != IntPtr.Zero) { Marshal.FreeHGlobal(tempPtr); } } Marshal.FreeHGlobal(modArray); } // Free the pointers. for (int x = 0; x < ptrToFree.Count; x++) { IntPtr tempPtr = (IntPtr)ptrToFree[x]; Marshal.FreeHGlobal(tempPtr); } if (berValuePtr != null && berValuePtr.bv_val != IntPtr.Zero) { Marshal.FreeHGlobal(berValuePtr.bv_val); } if (searchAttributes != IntPtr.Zero) { for (int i = 0; i < attributeCount; i++) { IntPtr tempPtr = Marshal.ReadIntPtr(searchAttributes, IntPtr.Size * i); if (tempPtr != IntPtr.Zero) { Marshal.FreeHGlobal(tempPtr); } } Marshal.FreeHGlobal(searchAttributes); } } } private bool ProcessClientCertificate(IntPtr ldapHandle, IntPtr CAs, ref IntPtr certificate) { int count = ClientCertificates == null ? 0 : ClientCertificates.Count; if (count == 0 && SessionOptions._clientCertificateDelegate == null) { return false; } // If the user specify certificate through property and not though option, we don't need to check the certificate authority. if (SessionOptions._clientCertificateDelegate == null) { certificate = ClientCertificates[0].Handle; return true; } // Processing the certificate authority. var list = new ArrayList(); if (CAs != IntPtr.Zero) { SecPkgContext_IssuerListInfoEx trustedCAs = (SecPkgContext_IssuerListInfoEx)Marshal.PtrToStructure(CAs, typeof(SecPkgContext_IssuerListInfoEx)); int issuerNumber = trustedCAs.cIssuers; for (int i = 0; i < issuerNumber; i++) { IntPtr tempPtr = (IntPtr)((long)trustedCAs.aIssuers + Marshal.SizeOf(typeof(CRYPTOAPI_BLOB)) * i); CRYPTOAPI_BLOB info = (CRYPTOAPI_BLOB)Marshal.PtrToStructure(tempPtr, typeof(CRYPTOAPI_BLOB)); int dataLength = info.cbData; byte[] context = new byte[dataLength]; Marshal.Copy(info.pbData, context, 0, dataLength); list.Add(context); } } byte[][] certAuthorities = null; if (list.Count != 0) { certAuthorities = new byte[list.Count][]; for (int i = 0; i < list.Count; i++) { certAuthorities[i] = (byte[])list[i]; } } X509Certificate cert = SessionOptions._clientCertificateDelegate(this, certAuthorities); if (cert != null) { certificate = cert.Handle; return true; } certificate = IntPtr.Zero; return false; } private void Connect() { //Ccurrently ldap does not accept more than one certificate. if (ClientCertificates.Count > 1) { throw new InvalidOperationException(SR.InvalidClientCertificates); } // Set the certificate callback routine here if user adds the certifcate to the certificate collection. if (ClientCertificates.Count != 0) { int certError = LdapPal.SetClientCertOption(_ldapHandle, LdapOption.LDAP_OPT_CLIENT_CERTIFICATE, _clientCertificateRoutine); if (certError != (int)ResultCode.Success) { if (LdapErrorMappings.IsLdapError(certError)) { string certerrorMessage = LdapErrorMappings.MapResultCode(certError); throw new LdapException(certError, certerrorMessage); } throw new LdapException(certError); } // When certificate is specified, automatic bind is disabled. AutoBind = false; } // Set the LDAP_OPT_AREC_EXCLUSIVE flag if necessary. if (((LdapDirectoryIdentifier)Directory).FullyQualifiedDnsHostName && !_setFQDNDone) { SessionOptions.SetFqdnRequired(); _setFQDNDone = true; } int error = InternalConnectToServer(); // Failed, throw an exception. if (error != (int)ResultCode.Success) { if (LdapErrorMappings.IsLdapError(error)) { string errorMessage = LdapErrorMappings.MapResultCode(error); throw new LdapException(error, errorMessage); } throw new LdapException(error); } } public void Bind() => BindHelper(_directoryCredential, needSetCredential: false); public void Bind(NetworkCredential newCredential) => BindHelper(newCredential, needSetCredential: true); private void BindHelper(NetworkCredential newCredential, bool needSetCredential) { if (_disposed) { throw new ObjectDisposedException(GetType().Name); } // Throw if user wants to do anonymous bind but specifies credentials. if (AuthType == AuthType.Anonymous && (newCredential != null && (!string.IsNullOrEmpty(newCredential.Password) || string.IsNullOrEmpty(newCredential.UserName)))) { throw new InvalidOperationException(SR.InvalidAuthCredential); } // Set the credential. NetworkCredential tempCredential; if (needSetCredential) { _directoryCredential = tempCredential = (newCredential != null ? new NetworkCredential(newCredential.UserName, newCredential.Password, newCredential.Domain) : null); } else { tempCredential = _directoryCredential; } // Connect to the server first. if (!_connected) { Connect(); _connected = true; } // Bind to the server. string username; string domainName; string password; if (tempCredential != null && tempCredential.UserName.Length == 0 && tempCredential.Password.Length == 0 && tempCredential.Domain.Length == 0) { // Default credentials. username = null; domainName = null; password = null; } else { username = tempCredential?.UserName; domainName = tempCredential?.Domain; password = tempCredential?.Password; } int error; if (AuthType == AuthType.Anonymous) { error = LdapPal.BindToDirectory(_ldapHandle, null, null); } else if (AuthType == AuthType.Basic) { var tempDomainName = new StringBuilder(100); if (domainName != null && domainName.Length != 0) { tempDomainName.Append(domainName); tempDomainName.Append('\\'); } tempDomainName.Append(username); error = LdapPal.BindToDirectory(_ldapHandle, tempDomainName.ToString(), password); } else { var cred = new SEC_WINNT_AUTH_IDENTITY_EX() { version = Interop.SEC_WINNT_AUTH_IDENTITY_VERSION, length = Marshal.SizeOf(typeof(SEC_WINNT_AUTH_IDENTITY_EX)), flags = Interop.SEC_WINNT_AUTH_IDENTITY_UNICODE }; if (AuthType == AuthType.Kerberos) { cred.packageList = Interop.MICROSOFT_KERBEROS_NAME_W; cred.packageListLength = cred.packageList.Length; } if (tempCredential != null) { cred.user = username; cred.userLength = (username == null ? 0 : username.Length); cred.domain = domainName; cred.domainLength = (domainName == null ? 0 : domainName.Length); cred.password = password; cred.passwordLength = (password == null ? 0 : password.Length); } BindMethod method = BindMethod.LDAP_AUTH_NEGOTIATE; switch (AuthType) { case AuthType.Negotiate: method = BindMethod.LDAP_AUTH_NEGOTIATE; break; case AuthType.Kerberos: method = BindMethod.LDAP_AUTH_NEGOTIATE; break; case AuthType.Ntlm: method = BindMethod.LDAP_AUTH_NTLM; break; case AuthType.Digest: method = BindMethod.LDAP_AUTH_DIGEST; break; case AuthType.Sicily: method = BindMethod.LDAP_AUTH_SICILY; break; case AuthType.Dpa: method = BindMethod.LDAP_AUTH_DPA; break; case AuthType.Msn: method = BindMethod.LDAP_AUTH_MSN; break; case AuthType.External: method = BindMethod.LDAP_AUTH_EXTERNAL; break; } error = InternalBind(tempCredential, cred, method); } // Failed, throw exception. if (error != (int)ResultCode.Success) { if (Utility.IsResultCode((ResultCode)error)) { string errorMessage = OperationErrorMappings.MapResultCode(error); throw new DirectoryOperationException(null, errorMessage); } else if (LdapErrorMappings.IsLdapError(error)) { string errorMessage = LdapErrorMappings.MapResultCode(error); string serverErrorMessage = SessionOptions.ServerErrorMessage; if (!string.IsNullOrEmpty(serverErrorMessage)) { throw new LdapException(error, errorMessage, serverErrorMessage); } throw new LdapException(error, errorMessage); } throw new LdapException(error); } // We successfully bound to the server. _bounded = true; // Rebind has been done. _needRebind = false; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { // We need to remove the handle from the handle table. lock (s_objectLock) { if (_ldapHandle != null) { s_handleTable.Remove(_ldapHandle.DangerousGetHandle()); } } } // Close the ldap connection. if (_needDispose && _ldapHandle != null && !_ldapHandle.IsInvalid) { _ldapHandle.Dispose(); } _ldapHandle = null; _disposed = true; } internal LdapControl[] BuildControlArray(DirectoryControlCollection controls, bool serverControl) { LdapControl[] managedControls = null; if (controls != null && controls.Count != 0) { var controlList = new ArrayList(); foreach (DirectoryControl col in controls) { if (serverControl == true) { if (col.ServerSide) { controlList.Add(col); } } else if (!col.ServerSide) { controlList.Add(col); } } if (controlList.Count != 0) { int count = controlList.Count; managedControls = new LdapControl[count]; for (int i = 0; i < count; i++) { managedControls[i] = new LdapControl() { // Get the control type. ldctl_oid = LdapPal.StringToPtr(((DirectoryControl)controlList[i]).Type), // Get the control cricality. ldctl_iscritical = ((DirectoryControl)controlList[i]).IsCritical }; // Get the control value. DirectoryControl tempControl = (DirectoryControl)controlList[i]; byte[] byteControlValue = tempControl.GetValue(); if (byteControlValue == null || byteControlValue.Length == 0) { // Treat the control value as null. managedControls[i].ldctl_value = new BerVal { bv_len = 0, bv_val = IntPtr.Zero }; } else { managedControls[i].ldctl_value = new BerVal { bv_len = byteControlValue.Length, bv_val = Marshal.AllocHGlobal(sizeof(byte) * byteControlValue.Length) }; Marshal.Copy(byteControlValue, 0, managedControls[i].ldctl_value.bv_val, managedControls[i].ldctl_value.bv_len); } } } } return managedControls; } internal LdapMod[] BuildAttributes(CollectionBase directoryAttributes, ArrayList ptrToFree) { LdapMod[] attributes = null; if (directoryAttributes != null && directoryAttributes.Count != 0) { var encoder = new UTF8Encoding(); DirectoryAttributeModificationCollection modificationCollection = null; DirectoryAttributeCollection attributeCollection = null; if (directoryAttributes is DirectoryAttributeModificationCollection) { modificationCollection = (DirectoryAttributeModificationCollection)directoryAttributes; } else { attributeCollection = (DirectoryAttributeCollection)directoryAttributes; } attributes = new LdapMod[directoryAttributes.Count]; for (int i = 0; i < directoryAttributes.Count; i++) { // Get the managed attribute first. DirectoryAttribute modAttribute; if (attributeCollection != null) { modAttribute = attributeCollection[i]; } else { modAttribute = modificationCollection[i]; } attributes[i] = new LdapMod(); // Write the operation type. if (modAttribute is DirectoryAttributeModification) { attributes[i].type = (int)((DirectoryAttributeModification)modAttribute).Operation; } else { attributes[i].type = (int)DirectoryAttributeOperation.Add; } // We treat all the values as binary attributes[i].type |= LDAP_MOD_BVALUES; // Write the attribute name. attributes[i].attribute = LdapPal.StringToPtr(modAttribute.Name); // Write the values. int valuesCount = 0; BerVal[] berValues = null; if (modAttribute.Count > 0) { valuesCount = modAttribute.Count; berValues = new BerVal[valuesCount]; for (int j = 0; j < valuesCount; j++) { byte[] byteArray; if (modAttribute[j] is string) { byteArray = encoder.GetBytes((string)modAttribute[j]); } else if (modAttribute[j] is Uri) { byteArray = encoder.GetBytes(((Uri)modAttribute[j]).ToString()); } else { byteArray = (byte[])modAttribute[j]; } berValues[j] = new BerVal() { bv_len = byteArray.Length, bv_val = Marshal.AllocHGlobal(byteArray.Length) }; // need to free the memory allocated on the heap when we are done ptrToFree.Add(berValues[j].bv_val); Marshal.Copy(byteArray, 0, berValues[j].bv_val, berValues[j].bv_len); } } attributes[i].values = Utility.AllocHGlobalIntPtrArray(valuesCount + 1); int structSize = Marshal.SizeOf(typeof(BerVal)); IntPtr controlPtr; IntPtr tempPtr; int m; for (m = 0; m < valuesCount; m++) { controlPtr = Marshal.AllocHGlobal(structSize); // Need to free the memory allocated on the heap when we are done. ptrToFree.Add(controlPtr); Marshal.StructureToPtr(berValues[m], controlPtr, false); tempPtr = (IntPtr)((long)attributes[i].values + IntPtr.Size * m); Marshal.WriteIntPtr(tempPtr, controlPtr); } tempPtr = (IntPtr)((long)attributes[i].values + IntPtr.Size * m); Marshal.WriteIntPtr(tempPtr, IntPtr.Zero); } } return attributes; } internal async ValueTask<DirectoryResponse> ConstructResponseAsync(int messageId, LdapOperation operation, ResultAll resultType, TimeSpan requestTimeOut, bool exceptionOnTimeOut, bool sync) { var timeout = new LDAP_TIMEVAL() { tv_sec = (int)(requestTimeOut.Ticks / TimeSpan.TicksPerSecond) }; IntPtr ldapResult = IntPtr.Zero; DirectoryResponse response = null; IntPtr requestName = IntPtr.Zero; IntPtr requestValue = IntPtr.Zero; IntPtr entryMessage; bool needAbandon = true; // processing for the partial results retrieval if (resultType != ResultAll.LDAP_MSG_ALL) { // we need to have 0 timeout as we are polling for the results and don't want to wait timeout.tv_sec = 0; timeout.tv_usec = 0; if (resultType == ResultAll.LDAP_MSG_POLLINGALL) { resultType = ResultAll.LDAP_MSG_ALL; } // when doing partial results retrieving, if ldap_result failed, we don't do ldap_abandon here. needAbandon = false; } int error; if (sync) { error = LdapPal.GetResultFromAsyncOperation(_ldapHandle, messageId, (int)resultType, timeout, ref ldapResult); } else { timeout.tv_sec = 0; timeout.tv_usec = 0; int iterationDelay = 1; // Underlying native libraries don't support callback-based function, so we will instead use polling and // use a Stopwatch to track the timeout manually. Stopwatch watch = Stopwatch.StartNew(); while (true) { error = LdapPal.GetResultFromAsyncOperation(_ldapHandle, messageId, (int)resultType, timeout, ref ldapResult); if (error != 0 || (requestTimeOut != Threading.Timeout.InfiniteTimeSpan && watch.Elapsed > requestTimeOut)) { break; } await Task.Delay(Math.Min(iterationDelay, 100)).ConfigureAwait(false); if (iterationDelay < 100) { iterationDelay *= 2; } } watch.Stop(); } if (error != -1 && error != 0) { // parsing the result int serverError = 0; try { int resultError = 0; string responseDn = null; string responseMessage = null; Uri[] responseReferral = null; DirectoryControl[] responseControl = null; // ldap_parse_result skips over messages of type LDAP_RES_SEARCH_ENTRY and LDAP_RES_SEARCH_REFERRAL if (error != (int)LdapResult.LDAP_RES_SEARCH_ENTRY && error != (int)LdapResult.LDAP_RES_REFERRAL) { resultError = ConstructParsedResult(ldapResult, ref serverError, ref responseDn, ref responseMessage, ref responseReferral, ref responseControl); } if (resultError == 0) { resultError = serverError; if (error == (int)LdapResult.LDAP_RES_ADD) { response = new AddResponse(responseDn, responseControl, (ResultCode)resultError, responseMessage, responseReferral); } else if (error == (int)LdapResult.LDAP_RES_MODIFY) { response = new ModifyResponse(responseDn, responseControl, (ResultCode)resultError, responseMessage, responseReferral); } else if (error == (int)LdapResult.LDAP_RES_DELETE) { response = new DeleteResponse(responseDn, responseControl, (ResultCode)resultError, responseMessage, responseReferral); } else if (error == (int)LdapResult.LDAP_RES_MODRDN) { response = new ModifyDNResponse(responseDn, responseControl, (ResultCode)resultError, responseMessage, responseReferral); } else if (error == (int)LdapResult.LDAP_RES_COMPARE) { response = new CompareResponse(responseDn, responseControl, (ResultCode)resultError, responseMessage, responseReferral); } else if (error == (int)LdapResult.LDAP_RES_EXTENDED) { response = new ExtendedResponse(responseDn, responseControl, (ResultCode)resultError, responseMessage, responseReferral); if (resultError == (int)ResultCode.Success) { resultError = LdapPal.ParseExtendedResult(_ldapHandle, ldapResult, ref requestName, ref requestValue, 0 /*not free it*/); if (resultError == 0) { string name = null; if (requestName != IntPtr.Zero) { name = LdapPal.PtrToString(requestName); } BerVal val = null; byte[] requestValueArray = null; if (requestValue != IntPtr.Zero) { val = new BerVal(); Marshal.PtrToStructure(requestValue, val); if (val.bv_len != 0 && val.bv_val != IntPtr.Zero) { requestValueArray = new byte[val.bv_len]; Marshal.Copy(val.bv_val, requestValueArray, 0, val.bv_len); } } ((ExtendedResponse)response).ResponseName = name; ((ExtendedResponse)response).ResponseValue = requestValueArray; } } } else if (error == (int)LdapResult.LDAP_RES_SEARCH_RESULT || error == (int)LdapResult.LDAP_RES_SEARCH_ENTRY || error == (int)LdapResult.LDAP_RES_REFERRAL) { response = new SearchResponse(responseDn, responseControl, (ResultCode)resultError, responseMessage, responseReferral); //set the flag here so our partial result processor knows whether the search is done or not if (error == (int)LdapResult.LDAP_RES_SEARCH_RESULT) { ((SearchResponse)response).searchDone = true; } SearchResultEntryCollection searchResultEntries = new SearchResultEntryCollection(); SearchResultReferenceCollection searchResultReferences = new SearchResultReferenceCollection(); // parsing the resultentry entryMessage = LdapPal.GetFirstEntryFromResult(_ldapHandle, ldapResult); int entrycount = 0; while (entryMessage != IntPtr.Zero) { SearchResultEntry entry = ConstructEntry(entryMessage); if (entry != null) { searchResultEntries.Add(entry); } entrycount++; entryMessage = LdapPal.GetNextEntryFromResult(_ldapHandle, entryMessage); } // Parse the reference. IntPtr referenceMessage = LdapPal.GetFirstReferenceFromResult(_ldapHandle, ldapResult); while (referenceMessage != IntPtr.Zero) { SearchResultReference reference = ConstructReference(referenceMessage); if (reference != null) { searchResultReferences.Add(reference); } referenceMessage = LdapPal.GetNextReferenceFromResult(_ldapHandle, referenceMessage); } ((SearchResponse)response).Entries = searchResultEntries; ((SearchResponse)response).References = searchResultReferences; } if (resultError != (int)ResultCode.Success && resultError != (int)ResultCode.CompareFalse && resultError != (int)ResultCode.CompareTrue && resultError != (int)ResultCode.Referral && resultError != (int)ResultCode.ReferralV2) { // Throw operation exception. if (Utility.IsResultCode((ResultCode)resultError)) { throw new DirectoryOperationException(response, OperationErrorMappings.MapResultCode(resultError)); } else { // This should not occur. throw new DirectoryOperationException(response); } } return response; } else { // Fall through, throw the exception beow. error = resultError; } } finally { if (requestName != IntPtr.Zero) { LdapPal.FreeMemory(requestName); } if (requestValue != IntPtr.Zero) { LdapPal.FreeMemory(requestValue); } if (ldapResult != IntPtr.Zero) { LdapPal.FreeMessage(ldapResult); } } } else { // ldap_result failed if (error == 0) { if (exceptionOnTimeOut) { // Client side timeout. error = (int)LdapError.TimeOut; } else { // If we don't throw exception on time out (notification search for example), we // just return an empty response. return null; } } else { error = LdapPal.GetLastErrorFromConnection(_ldapHandle); } // Abandon the request. if (needAbandon) { LdapPal.CancelDirectoryAsyncOperation(_ldapHandle, messageId); } } // Throw the proper exception here. throw ConstructException(error, operation); } internal unsafe int ConstructParsedResult(IntPtr ldapResult, ref int serverError, ref string responseDn, ref string responseMessage, ref Uri[] responseReferral, ref DirectoryControl[] responseControl) { IntPtr dn = IntPtr.Zero; IntPtr message = IntPtr.Zero; IntPtr referral = IntPtr.Zero; IntPtr control = IntPtr.Zero; try { int resultError = LdapPal.ParseResult(_ldapHandle, ldapResult, ref serverError, ref dn, ref message, ref referral, ref control, 0 /* not free it */); if (resultError == 0) { // Parse the dn. responseDn = LdapPal.PtrToString(dn); // Parse the message. responseMessage = LdapPal.PtrToString(message); // Parse the referral. if (referral != IntPtr.Zero) { char** tempPtr = (char**)referral; char* singleReferral = tempPtr[0]; int i = 0; var referralList = new ArrayList(); while (singleReferral != null) { string s = LdapPal.PtrToString((IntPtr)singleReferral); referralList.Add(s); i++; singleReferral = tempPtr[i]; } if (referralList.Count > 0) { responseReferral = new Uri[referralList.Count]; for (int j = 0; j < referralList.Count; j++) { responseReferral[j] = new Uri((string)referralList[j]); } } } // Parse the control. if (control != IntPtr.Zero) { int i = 0; IntPtr tempControlPtr = control; IntPtr singleControl = Marshal.ReadIntPtr(tempControlPtr, 0); var controlList = new ArrayList(); while (singleControl != IntPtr.Zero) { DirectoryControl directoryControl = ConstructControl(singleControl); controlList.Add(directoryControl); i++; singleControl = Marshal.ReadIntPtr(tempControlPtr, i * IntPtr.Size); } responseControl = new DirectoryControl[controlList.Count]; controlList.CopyTo(responseControl); } } else { // we need to take care of one special case, when can't connect to the server, ldap_parse_result fails with local error if (resultError == (int)LdapError.LocalError) { int tmpResult = LdapPal.ResultToErrorCode(_ldapHandle, ldapResult, 0 /* not free it */); if (tmpResult != 0) { resultError = tmpResult; } } } return resultError; } finally { if (dn != IntPtr.Zero) { LdapPal.FreeMemory(dn); } if (message != IntPtr.Zero) { LdapPal.FreeMemory(message); } if (referral != IntPtr.Zero) { LdapPal.FreeValue(referral); } if (control != IntPtr.Zero) { LdapPal.FreeDirectoryControls(control); } } } internal SearchResultEntry ConstructEntry(IntPtr entryMessage) { IntPtr dn = IntPtr.Zero; IntPtr attribute = IntPtr.Zero; IntPtr address = IntPtr.Zero; try { // Get the dn. string entryDn = null; dn = LdapPal.GetDistinguishedName(_ldapHandle, entryMessage); if (dn != IntPtr.Zero) { entryDn = LdapPal.PtrToString(dn); LdapPal.FreeMemory(dn); dn = IntPtr.Zero; } SearchResultEntry resultEntry = new SearchResultEntry(entryDn); SearchResultAttributeCollection attributes = resultEntry.Attributes; // Get attributes. attribute = LdapPal.GetFirstAttributeFromEntry(_ldapHandle, entryMessage, ref address); int tempcount = 0; while (attribute != IntPtr.Zero) { DirectoryAttribute attr = ConstructAttribute(entryMessage, attribute); attributes.Add(attr.Name, attr); LdapPal.FreeMemory(attribute); tempcount++; attribute = LdapPal.GetNextAttributeFromResult(_ldapHandle, entryMessage, address); } if (address != IntPtr.Zero) { BerPal.FreeBerElement(address, 0); address = IntPtr.Zero; } return resultEntry; } finally { if (dn != IntPtr.Zero) { LdapPal.FreeMemory(dn); } if (attribute != IntPtr.Zero) { LdapPal.FreeMemory(attribute); } if (address != IntPtr.Zero) { BerPal.FreeBerElement(address, 0); } } } internal DirectoryAttribute ConstructAttribute(IntPtr entryMessage, IntPtr attributeName) { var attribute = new DirectoryAttribute() { _isSearchResult = true }; string name = LdapPal.PtrToString(attributeName); attribute.Name = name; IntPtr valuesArray = LdapPal.GetValuesFromAttribute(_ldapHandle, entryMessage, name); try { if (valuesArray != IntPtr.Zero) { int count = 0; IntPtr tempPtr = Marshal.ReadIntPtr(valuesArray, IntPtr.Size * count); while (tempPtr != IntPtr.Zero) { BerVal bervalue = new BerVal(); Marshal.PtrToStructure(tempPtr, bervalue); byte[] byteArray; if (bervalue.bv_len > 0 && bervalue.bv_val != IntPtr.Zero) { byteArray = new byte[bervalue.bv_len]; Marshal.Copy(bervalue.bv_val, byteArray, 0, bervalue.bv_len); attribute.Add(byteArray); } count++; tempPtr = Marshal.ReadIntPtr(valuesArray, IntPtr.Size * count); } } } finally { if (valuesArray != IntPtr.Zero) { LdapPal.FreeAttributes(valuesArray); } } return attribute; } internal SearchResultReference ConstructReference(IntPtr referenceMessage) { IntPtr referenceArray = IntPtr.Zero; int error = LdapPal.ParseReference(_ldapHandle, referenceMessage, ref referenceArray); try { if (error == 0) { var referralList = new ArrayList(); IntPtr tempPtr; int count = 0; if (referenceArray != IntPtr.Zero) { tempPtr = Marshal.ReadIntPtr(referenceArray, IntPtr.Size * count); while (tempPtr != IntPtr.Zero) { string s = LdapPal.PtrToString(tempPtr); referralList.Add(s); count++; tempPtr = Marshal.ReadIntPtr(referenceArray, IntPtr.Size * count); } LdapPal.FreeValue(referenceArray); referenceArray = IntPtr.Zero; } if (referralList.Count > 0) { Uri[] uris = new Uri[referralList.Count]; for (int i = 0; i < referralList.Count; i++) { uris[i] = new Uri((string)referralList[i]); } return new SearchResultReference(uris); } } } finally { if (referenceArray != IntPtr.Zero) { LdapPal.FreeValue(referenceArray); } } return null; } private DirectoryException ConstructException(int error, LdapOperation operation) { DirectoryResponse response = null; if (Utility.IsResultCode((ResultCode)error)) { if (operation == LdapOperation.LdapAdd) { response = new AddResponse(null, null, (ResultCode)error, OperationErrorMappings.MapResultCode(error), null); } else if (operation == LdapOperation.LdapModify) { response = new ModifyResponse(null, null, (ResultCode)error, OperationErrorMappings.MapResultCode(error), null); } else if (operation == LdapOperation.LdapDelete) { response = new DeleteResponse(null, null, (ResultCode)error, OperationErrorMappings.MapResultCode(error), null); } else if (operation == LdapOperation.LdapModifyDn) { response = new ModifyDNResponse(null, null, (ResultCode)error, OperationErrorMappings.MapResultCode(error), null); } else if (operation == LdapOperation.LdapCompare) { response = new CompareResponse(null, null, (ResultCode)error, OperationErrorMappings.MapResultCode(error), null); } else if (operation == LdapOperation.LdapSearch) { response = new SearchResponse(null, null, (ResultCode)error, OperationErrorMappings.MapResultCode(error), null); } else if (operation == LdapOperation.LdapExtendedRequest) { response = new ExtendedResponse(null, null, (ResultCode)error, OperationErrorMappings.MapResultCode(error), null); } string errorMessage = OperationErrorMappings.MapResultCode(error); return new DirectoryOperationException(response, errorMessage); } else { if (LdapErrorMappings.IsLdapError(error)) { string errorMessage = LdapErrorMappings.MapResultCode(error); string serverErrorMessage = SessionOptions.ServerErrorMessage; if (!string.IsNullOrEmpty(serverErrorMessage)) { throw new LdapException(error, errorMessage, serverErrorMessage); } return new LdapException(error, errorMessage); } return new LdapException(error); } } private DirectoryControl ConstructControl(IntPtr controlPtr) { LdapControl control = new LdapControl(); Marshal.PtrToStructure(controlPtr, control); Debug.Assert(control.ldctl_oid != IntPtr.Zero); string controlType = LdapPal.PtrToString(control.ldctl_oid); byte[] bytes = new byte[control.ldctl_value.bv_len]; Marshal.Copy(control.ldctl_value.bv_val, bytes, 0, control.ldctl_value.bv_len); bool criticality = control.ldctl_iscritical; return new DirectoryControl(controlType, bytes, criticality, true); } private bool SameCredential(NetworkCredential oldCredential, NetworkCredential newCredential) { if (oldCredential == null && newCredential == null) { return true; } else if (oldCredential == null && newCredential != null) { return false; } else if (oldCredential != null && newCredential == null) { return false; } else { if (oldCredential.Domain == newCredential.Domain && oldCredential.UserName == newCredential.UserName && oldCredential.Password == newCredential.Password) { return true; } else { return false; } } } } }
-1
dotnet/runtime
66,462
Support using the system version of brotli
This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
omajid
2022-03-10T17:19:11Z
2022-03-23T03:49:50Z
c3e1d21c2fb30436ae24ef7ef4f458e3270bb7e3
5ca9223639700750ff12bb1fed9fa6e397062b78
Support using the system version of brotli . This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
./src/tests/baseservices/threading/generics/WaitCallback/thread07.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="thread07.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="thread07.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,462
Support using the system version of brotli
This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
omajid
2022-03-10T17:19:11Z
2022-03-23T03:49:50Z
c3e1d21c2fb30436ae24ef7ef4f458e3270bb7e3
5ca9223639700750ff12bb1fed9fa6e397062b78
Support using the system version of brotli . This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
./src/coreclr/tools/Common/Internal/Metadata/NativeFormat/Generator/NativeFormatGen.csproj
<Project ToolsVersion="15.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> <PropertyGroup> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>NativeFormatGen</RootNamespace> <AssemblyName>NativeFormatGen</AssemblyName> <TargetFrameworkVersion>v4.6</TargetFrameworkVersion> <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PlatformTarget>AnyCPU</PlatformTarget> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <PlatformTarget>AnyCPU</PlatformTarget> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="System" /> <Reference Include="System.Core" /> <Reference Include="Microsoft.CSharp" /> </ItemGroup> <ItemGroup> <Compile Include="CsWriter.cs" /> <Compile Include="MdBinaryReaderGen.cs" /> <Compile Include="MdBinaryWriterGen.cs" /> <Compile Include="Program.cs" /> <Compile Include="PublicGen.cs" /> <Compile Include="ReaderGen.cs" /> <Compile Include="SchemaDef.cs" /> <Compile Include="WriterGen.cs" /> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project>
<Project ToolsVersion="15.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> <PropertyGroup> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>NativeFormatGen</RootNamespace> <AssemblyName>NativeFormatGen</AssemblyName> <TargetFrameworkVersion>v4.6</TargetFrameworkVersion> <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PlatformTarget>AnyCPU</PlatformTarget> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <PlatformTarget>AnyCPU</PlatformTarget> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="System" /> <Reference Include="System.Core" /> <Reference Include="Microsoft.CSharp" /> </ItemGroup> <ItemGroup> <Compile Include="CsWriter.cs" /> <Compile Include="MdBinaryReaderGen.cs" /> <Compile Include="MdBinaryWriterGen.cs" /> <Compile Include="Program.cs" /> <Compile Include="PublicGen.cs" /> <Compile Include="ReaderGen.cs" /> <Compile Include="SchemaDef.cs" /> <Compile Include="WriterGen.cs" /> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project>
-1
dotnet/runtime
66,462
Support using the system version of brotli
This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
omajid
2022-03-10T17:19:11Z
2022-03-23T03:49:50Z
c3e1d21c2fb30436ae24ef7ef4f458e3270bb7e3
5ca9223639700750ff12bb1fed9fa6e397062b78
Support using the system version of brotli . This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
./src/tests/Loader/classloader/v1/Beta1/Layout/Matrix/cs/L-2-11-1.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. ////////////////////////////////////////////////////////// // L-1-11-1.cs - Beta1 Layout Test - RDawson // // Tests layout of classes two unrelated classes in // the same assembly and module // // See ReadMe.txt in the same project as this source for // further details about these tests. // using System; class Test{ public static int Main(){ int mi_RetCode = 100; A a = new A(); B b = new B(); if(a.Test(b) != 100) mi_RetCode = 0; if(b.Test(a) != 100) mi_RetCode = 0; if(mi_RetCode == 100) Console.WriteLine("Pass"); else Console.WriteLine("FAIL"); return mi_RetCode; } } struct A{ public int Test(B b){ int mi_RetCode = 100; ///////////////////////////////// // Test instance field access b.FldPubInst = 100; if(b.FldPubInst != 100) mi_RetCode = 0; //@csharp - Note that C# will not compile an illegal access of b.FldPrivInst //So there is no negative test here, it should be covered elsewhere and //should throw a FielAccessException within the runtime. (IL sources is //the most logical, only?, choice) //@csharp - C# Won't compile illegal family access from non-family members b.FldAsmInst = 100; if(b.FldAsmInst != 100) mi_RetCode = 0; ///////////////////////////////// // Test static field access B.FldPubStat = 100; if(B.FldPubStat != 100) mi_RetCode = 0; //@csharp - Again, note C# won't do private field access //@csharp - C# Won't compile illegal family access from non-family members B.FldAsmStat = 100; if(B.FldAsmStat != 100) mi_RetCode = 0; ///////////////////////////////// // Test instance b.Method access if(b.MethPubInst() != 100) mi_RetCode = 0; //@csharp - C# won't do private b.Method access //@csharp - C# Won't compile illegal family access from non-family members if(b.MethAsmInst() != 100) mi_RetCode = 0; ///////////////////////////////// // Test static b.Method access if(B.MethPubStat() != 100) mi_RetCode = 0; //@csharp - C# won't do private b.Method access //@csharp - C# Won't compile illegal family access from non-family members if(B.MethAsmStat() != 100) mi_RetCode = 0; return mi_RetCode; } ////////////////////////////// // Instance Fields public int FldPubInst; private int FldPrivInst; internal int FldAsmInst; //Translates to "assembly" ////////////////////////////// // Static Fields public static int FldPubStat; private static int FldPrivStat; internal static int FldAsmStat; //assembly ////////////////////////////// // Instance Methods public int MethPubInst(){ Console.WriteLine("A::MethPubInst()"); return 100; } private int MethPrivInst(){ Console.WriteLine("A::MethPrivInst()"); return 100; } internal int MethAsmInst(){ Console.WriteLine("A::MethAsmInst()"); return 100; } ////////////////////////////// // Static Methods public static int MethPubStat(){ Console.WriteLine("A::MethPubStat()"); return 100; } private static int MethPrivStat(){ Console.WriteLine("A::MethPrivStat()"); return 100; } internal static int MethAsmStat(){ Console.WriteLine("A::MethAsmStat()"); return 100; } } struct B{ public int Test(A a){ int mi_RetCode = 100; ///////////////////////////////// // Test instance field access a.FldPubInst = 100; if(a.FldPubInst != 100) mi_RetCode = 0; //@csharp - Note that C# will not compile an illegal access of a.FldPrivInst //So there is no negative test here, it should be covered elsewhere and //should throw a FielAccessException within the runtime. (IL sources is //the most logical, only?, choice) //@csharp - C# Won't compile illegal family access from non-family members a.FldAsmInst = 100; if(a.FldAsmInst != 100) mi_RetCode = 0; ///////////////////////////////// // Test static field access A.FldPubStat = 100; if(A.FldPubStat != 100) mi_RetCode = 0; //@csharp - Again, note C# won't do private field access //@csharp - C# Won't compile illegal family access from non-family members A.FldAsmStat = 100; if(A.FldAsmStat != 100) mi_RetCode = 0; ///////////////////////////////// // Test instance a.Method access if(a.MethPubInst() != 100) mi_RetCode = 0; //@csharp - C# won't do private a.Method access //@csharp - C# Won't compile illegal family access from non-family members if(a.MethAsmInst() != 100) mi_RetCode = 0; ///////////////////////////////// // Test static a.Method access if(A.MethPubStat() != 100) mi_RetCode = 0; //@csharp - C# won't do private a.Method access //@csharp - C# Won't compile illegal family access from non-family members if(A.MethAsmStat() != 100) mi_RetCode = 0; return mi_RetCode; } ////////////////////////////// // Instance Fields public int FldPubInst; private int FldPrivInst; internal int FldAsmInst; //Translates to "assembly" ////////////////////////////// // Static Fields public static int FldPubStat; private static int FldPrivStat; internal static int FldAsmStat; //assembly ////////////////////////////// // Instance Methods public int MethPubInst(){ Console.WriteLine("B::MethPubInst()"); return 100; } private int MethPrivInst(){ Console.WriteLine("B::MethPrivInst()"); return 100; } internal int MethAsmInst(){ Console.WriteLine("B::MethAsmInst()"); return 100; } ////////////////////////////// // Static Methods public static int MethPubStat(){ Console.WriteLine("B::MethPubStat()"); return 100; } private static int MethPrivStat(){ Console.WriteLine("B::MethPrivStat()"); return 100; } internal static int MethAsmStat(){ Console.WriteLine("B::MethAsmStat()"); return 100; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. ////////////////////////////////////////////////////////// // L-1-11-1.cs - Beta1 Layout Test - RDawson // // Tests layout of classes two unrelated classes in // the same assembly and module // // See ReadMe.txt in the same project as this source for // further details about these tests. // using System; class Test{ public static int Main(){ int mi_RetCode = 100; A a = new A(); B b = new B(); if(a.Test(b) != 100) mi_RetCode = 0; if(b.Test(a) != 100) mi_RetCode = 0; if(mi_RetCode == 100) Console.WriteLine("Pass"); else Console.WriteLine("FAIL"); return mi_RetCode; } } struct A{ public int Test(B b){ int mi_RetCode = 100; ///////////////////////////////// // Test instance field access b.FldPubInst = 100; if(b.FldPubInst != 100) mi_RetCode = 0; //@csharp - Note that C# will not compile an illegal access of b.FldPrivInst //So there is no negative test here, it should be covered elsewhere and //should throw a FielAccessException within the runtime. (IL sources is //the most logical, only?, choice) //@csharp - C# Won't compile illegal family access from non-family members b.FldAsmInst = 100; if(b.FldAsmInst != 100) mi_RetCode = 0; ///////////////////////////////// // Test static field access B.FldPubStat = 100; if(B.FldPubStat != 100) mi_RetCode = 0; //@csharp - Again, note C# won't do private field access //@csharp - C# Won't compile illegal family access from non-family members B.FldAsmStat = 100; if(B.FldAsmStat != 100) mi_RetCode = 0; ///////////////////////////////// // Test instance b.Method access if(b.MethPubInst() != 100) mi_RetCode = 0; //@csharp - C# won't do private b.Method access //@csharp - C# Won't compile illegal family access from non-family members if(b.MethAsmInst() != 100) mi_RetCode = 0; ///////////////////////////////// // Test static b.Method access if(B.MethPubStat() != 100) mi_RetCode = 0; //@csharp - C# won't do private b.Method access //@csharp - C# Won't compile illegal family access from non-family members if(B.MethAsmStat() != 100) mi_RetCode = 0; return mi_RetCode; } ////////////////////////////// // Instance Fields public int FldPubInst; private int FldPrivInst; internal int FldAsmInst; //Translates to "assembly" ////////////////////////////// // Static Fields public static int FldPubStat; private static int FldPrivStat; internal static int FldAsmStat; //assembly ////////////////////////////// // Instance Methods public int MethPubInst(){ Console.WriteLine("A::MethPubInst()"); return 100; } private int MethPrivInst(){ Console.WriteLine("A::MethPrivInst()"); return 100; } internal int MethAsmInst(){ Console.WriteLine("A::MethAsmInst()"); return 100; } ////////////////////////////// // Static Methods public static int MethPubStat(){ Console.WriteLine("A::MethPubStat()"); return 100; } private static int MethPrivStat(){ Console.WriteLine("A::MethPrivStat()"); return 100; } internal static int MethAsmStat(){ Console.WriteLine("A::MethAsmStat()"); return 100; } } struct B{ public int Test(A a){ int mi_RetCode = 100; ///////////////////////////////// // Test instance field access a.FldPubInst = 100; if(a.FldPubInst != 100) mi_RetCode = 0; //@csharp - Note that C# will not compile an illegal access of a.FldPrivInst //So there is no negative test here, it should be covered elsewhere and //should throw a FielAccessException within the runtime. (IL sources is //the most logical, only?, choice) //@csharp - C# Won't compile illegal family access from non-family members a.FldAsmInst = 100; if(a.FldAsmInst != 100) mi_RetCode = 0; ///////////////////////////////// // Test static field access A.FldPubStat = 100; if(A.FldPubStat != 100) mi_RetCode = 0; //@csharp - Again, note C# won't do private field access //@csharp - C# Won't compile illegal family access from non-family members A.FldAsmStat = 100; if(A.FldAsmStat != 100) mi_RetCode = 0; ///////////////////////////////// // Test instance a.Method access if(a.MethPubInst() != 100) mi_RetCode = 0; //@csharp - C# won't do private a.Method access //@csharp - C# Won't compile illegal family access from non-family members if(a.MethAsmInst() != 100) mi_RetCode = 0; ///////////////////////////////// // Test static a.Method access if(A.MethPubStat() != 100) mi_RetCode = 0; //@csharp - C# won't do private a.Method access //@csharp - C# Won't compile illegal family access from non-family members if(A.MethAsmStat() != 100) mi_RetCode = 0; return mi_RetCode; } ////////////////////////////// // Instance Fields public int FldPubInst; private int FldPrivInst; internal int FldAsmInst; //Translates to "assembly" ////////////////////////////// // Static Fields public static int FldPubStat; private static int FldPrivStat; internal static int FldAsmStat; //assembly ////////////////////////////// // Instance Methods public int MethPubInst(){ Console.WriteLine("B::MethPubInst()"); return 100; } private int MethPrivInst(){ Console.WriteLine("B::MethPrivInst()"); return 100; } internal int MethAsmInst(){ Console.WriteLine("B::MethAsmInst()"); return 100; } ////////////////////////////// // Static Methods public static int MethPubStat(){ Console.WriteLine("B::MethPubStat()"); return 100; } private static int MethPrivStat(){ Console.WriteLine("B::MethPrivStat()"); return 100; } internal static int MethAsmStat(){ Console.WriteLine("B::MethAsmStat()"); return 100; } }
-1
dotnet/runtime
66,462
Support using the system version of brotli
This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
omajid
2022-03-10T17:19:11Z
2022-03-23T03:49:50Z
c3e1d21c2fb30436ae24ef7ef4f458e3270bb7e3
5ca9223639700750ff12bb1fed9fa6e397062b78
Support using the system version of brotli . This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
./src/coreclr/utilcode/CMakeLists.txt
set(CMAKE_INCLUDE_CURRENT_DIR ON) set(UTILCODE_COMMON_SOURCES clrhost_nodependencies.cpp ccomprc.cpp ex.cpp sbuffer.cpp sstring_com.cpp fstring.cpp namespaceutil.cpp makepath.cpp splitpath.cpp clrconfig.cpp configuration.cpp collections.cpp posterror.cpp fstream.cpp clrhelpers.cpp stgpool.cpp stgpooli.cpp stgpoolreadonly.cpp utsem.cpp check.cpp log.cpp arraylist.cpp bitvector.cpp comex.cpp guidfromname.cpp memorypool.cpp iallocator.cpp loaderheap.cpp outstring.cpp ilformatter.cpp opinfo.cpp corimage.cpp format1.cpp prettyprintsig.cpp sha1.cpp sigbuilder.cpp sigparser.cpp sstring.cpp util_nodependencies.cpp utilmessagebox.cpp safewrap.cpp clrhost.cpp cycletimer.cpp md5.cpp util.cpp stresslog.cpp debug.cpp pedecoder.cpp winfix.cpp longfilepathwrappers.cpp yieldprocessornormalized.cpp ) # These source file do not yet compile on Linux. # They should be moved out from here into the declaration # of UTILCODE_SOURCES above after fixing compiler errors. if(CLR_CMAKE_TARGET_WIN32) list(APPEND UTILCODE_COMMON_SOURCES dacutil.cpp dlwrap.cpp securitywrapper.cpp securityutil.cpp stacktrace.cpp ) endif(CLR_CMAKE_TARGET_WIN32) set(UTILCODE_SOURCES ${UTILCODE_COMMON_SOURCES} executableallocator.cpp ) set(UTILCODE_DAC_SOURCES ${UTILCODE_COMMON_SOURCES} hostimpl.cpp ) set(UTILCODE_STATICNOHOST_SOURCES ${UTILCODE_COMMON_SOURCES} hostimpl.cpp ) set (UTILCODE_DEPENDENCIES eventing_headers) convert_to_absolute_path(UTILCODE_SOURCES ${UTILCODE_SOURCES}) convert_to_absolute_path(UTILCODE_DAC_SOURCES ${UTILCODE_DAC_SOURCES}) convert_to_absolute_path(UTILCODE_STATICNOHOST_SOURCES ${UTILCODE_STATICNOHOST_SOURCES}) add_library_clr(utilcode_dac STATIC ${UTILCODE_DAC_SOURCES}) add_library_clr(utilcode_obj OBJECT ${UTILCODE_SOURCES}) add_library(utilcode INTERFACE) target_sources(utilcode INTERFACE $<TARGET_OBJECTS:utilcode_obj>) add_library_clr(utilcodestaticnohost STATIC ${UTILCODE_STATICNOHOST_SOURCES}) if(CLR_CMAKE_HOST_UNIX) target_link_libraries(utilcodestaticnohost nativeresourcestring) target_link_libraries(utilcode_dac nativeresourcestring) target_link_libraries(utilcode INTERFACE nativeresourcestring) add_dependencies(utilcode_dac coreclrpal) add_dependencies(utilcode_obj coreclrpal) endif(CLR_CMAKE_HOST_UNIX) if(CLR_CMAKE_HOST_WIN32) target_compile_definitions(utilcodestaticnohost PRIVATE _CRTIMP=) # use static version of crt link_natvis_sources_for_target(utilcodestaticnohost INTERFACE utilcode.natvis) link_natvis_sources_for_target(utilcode_dac INTERFACE utilcode.natvis) link_natvis_sources_for_target(utilcode INTERFACE utilcode.natvis) endif(CLR_CMAKE_HOST_WIN32) set_target_properties(utilcode_dac PROPERTIES DAC_COMPONENT TRUE) target_compile_definitions(utilcode_dac PRIVATE SELF_NO_HOST) target_compile_definitions(utilcodestaticnohost PRIVATE SELF_NO_HOST) add_dependencies(utilcode_dac ${UTILCODE_DEPENDENCIES}) add_dependencies(utilcode_obj ${UTILCODE_DEPENDENCIES}) add_dependencies(utilcodestaticnohost ${UTILCODE_DEPENDENCIES}) target_precompile_headers(utilcode_dac PRIVATE [["stdafx.h"]]) target_precompile_headers(utilcode_obj PRIVATE [["stdafx.h"]]) target_precompile_headers(utilcodestaticnohost PRIVATE [["stdafx.h"]])
set(CMAKE_INCLUDE_CURRENT_DIR ON) set(UTILCODE_COMMON_SOURCES clrhost_nodependencies.cpp ccomprc.cpp ex.cpp sbuffer.cpp sstring_com.cpp fstring.cpp namespaceutil.cpp makepath.cpp splitpath.cpp clrconfig.cpp configuration.cpp collections.cpp posterror.cpp fstream.cpp clrhelpers.cpp stgpool.cpp stgpooli.cpp stgpoolreadonly.cpp utsem.cpp check.cpp log.cpp arraylist.cpp bitvector.cpp comex.cpp guidfromname.cpp memorypool.cpp iallocator.cpp loaderheap.cpp outstring.cpp ilformatter.cpp opinfo.cpp corimage.cpp format1.cpp prettyprintsig.cpp sha1.cpp sigbuilder.cpp sigparser.cpp sstring.cpp util_nodependencies.cpp utilmessagebox.cpp safewrap.cpp clrhost.cpp cycletimer.cpp md5.cpp util.cpp stresslog.cpp debug.cpp pedecoder.cpp winfix.cpp longfilepathwrappers.cpp yieldprocessornormalized.cpp ) # These source file do not yet compile on Linux. # They should be moved out from here into the declaration # of UTILCODE_SOURCES above after fixing compiler errors. if(CLR_CMAKE_TARGET_WIN32) list(APPEND UTILCODE_COMMON_SOURCES dacutil.cpp dlwrap.cpp securitywrapper.cpp securityutil.cpp stacktrace.cpp ) endif(CLR_CMAKE_TARGET_WIN32) set(UTILCODE_SOURCES ${UTILCODE_COMMON_SOURCES} executableallocator.cpp ) set(UTILCODE_DAC_SOURCES ${UTILCODE_COMMON_SOURCES} hostimpl.cpp ) set(UTILCODE_STATICNOHOST_SOURCES ${UTILCODE_COMMON_SOURCES} hostimpl.cpp ) set (UTILCODE_DEPENDENCIES eventing_headers) convert_to_absolute_path(UTILCODE_SOURCES ${UTILCODE_SOURCES}) convert_to_absolute_path(UTILCODE_DAC_SOURCES ${UTILCODE_DAC_SOURCES}) convert_to_absolute_path(UTILCODE_STATICNOHOST_SOURCES ${UTILCODE_STATICNOHOST_SOURCES}) add_library_clr(utilcode_dac STATIC ${UTILCODE_DAC_SOURCES}) add_library_clr(utilcode_obj OBJECT ${UTILCODE_SOURCES}) add_library(utilcode INTERFACE) target_sources(utilcode INTERFACE $<TARGET_OBJECTS:utilcode_obj>) add_library_clr(utilcodestaticnohost STATIC ${UTILCODE_STATICNOHOST_SOURCES}) if(CLR_CMAKE_HOST_UNIX) target_link_libraries(utilcodestaticnohost nativeresourcestring) target_link_libraries(utilcode_dac nativeresourcestring) target_link_libraries(utilcode INTERFACE nativeresourcestring) add_dependencies(utilcode_dac coreclrpal) add_dependencies(utilcode_obj coreclrpal) endif(CLR_CMAKE_HOST_UNIX) if(CLR_CMAKE_HOST_WIN32) target_compile_definitions(utilcodestaticnohost PRIVATE _CRTIMP=) # use static version of crt link_natvis_sources_for_target(utilcodestaticnohost INTERFACE utilcode.natvis) link_natvis_sources_for_target(utilcode_dac INTERFACE utilcode.natvis) link_natvis_sources_for_target(utilcode INTERFACE utilcode.natvis) endif(CLR_CMAKE_HOST_WIN32) set_target_properties(utilcode_dac PROPERTIES DAC_COMPONENT TRUE) target_compile_definitions(utilcode_dac PRIVATE SELF_NO_HOST) target_compile_definitions(utilcodestaticnohost PRIVATE SELF_NO_HOST) add_dependencies(utilcode_dac ${UTILCODE_DEPENDENCIES}) add_dependencies(utilcode_obj ${UTILCODE_DEPENDENCIES}) add_dependencies(utilcodestaticnohost ${UTILCODE_DEPENDENCIES}) target_precompile_headers(utilcode_dac PRIVATE [["stdafx.h"]]) target_precompile_headers(utilcode_obj PRIVATE [["stdafx.h"]]) target_precompile_headers(utilcodestaticnohost PRIVATE [["stdafx.h"]])
-1
dotnet/runtime
66,462
Support using the system version of brotli
This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
omajid
2022-03-10T17:19:11Z
2022-03-23T03:49:50Z
c3e1d21c2fb30436ae24ef7ef4f458e3270bb7e3
5ca9223639700750ff12bb1fed9fa6e397062b78
Support using the system version of brotli . This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
./src/mono/mono/utils/mono-networkinterfaces.h
/** * \file */ #ifndef __MONO_NETWORK_INTERFACES_H__ #define __MONO_NETWORK_INTERFACES_H__ /* * Utility functions to access network information. */ #include <glib.h> #include <mono/utils/mono-compiler.h> /* never remove or reorder these enums values: they are used in corlib/System */ typedef enum { MONO_NETWORK_BYTESREC, MONO_NETWORK_BYTESSENT, MONO_NETWORK_BYTESTOTAL } MonoNetworkData; typedef enum { MONO_NETWORK_ERROR_NONE, /* no error happened */ MONO_NETWORK_ERROR_NOT_FOUND, /* adapter name invalid */ MONO_NETWORK_ERROR_OTHER } MonoNetworkError; gpointer *mono_networkinterface_list (int *size); gint64 mono_network_get_data (char* name, MonoNetworkData data, MonoNetworkError *error); #endif /* __MONO_NETWORK_INTERFACES_H__ */
/** * \file */ #ifndef __MONO_NETWORK_INTERFACES_H__ #define __MONO_NETWORK_INTERFACES_H__ /* * Utility functions to access network information. */ #include <glib.h> #include <mono/utils/mono-compiler.h> /* never remove or reorder these enums values: they are used in corlib/System */ typedef enum { MONO_NETWORK_BYTESREC, MONO_NETWORK_BYTESSENT, MONO_NETWORK_BYTESTOTAL } MonoNetworkData; typedef enum { MONO_NETWORK_ERROR_NONE, /* no error happened */ MONO_NETWORK_ERROR_NOT_FOUND, /* adapter name invalid */ MONO_NETWORK_ERROR_OTHER } MonoNetworkError; gpointer *mono_networkinterface_list (int *size); gint64 mono_network_get_data (char* name, MonoNetworkData data, MonoNetworkError *error); #endif /* __MONO_NETWORK_INTERFACES_H__ */
-1
dotnet/runtime
66,462
Support using the system version of brotli
This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
omajid
2022-03-10T17:19:11Z
2022-03-23T03:49:50Z
c3e1d21c2fb30436ae24ef7ef4f458e3270bb7e3
5ca9223639700750ff12bb1fed9fa6e397062b78
Support using the system version of brotli . This is mainly motivated by the March 2022 release of .NET 5. .NET 5 was found to be vulnerable to CVE-2020-8927, which was caused by the older version of brotli built into .NET. .NET was vulernable even in environments where a system-wide version of brotli was present and had already received fixes for this CVE. We could have avoided a Remove Code Execution vulnerability in such environments by using the system's version of brotli. This is similar to the existing support for disabling distro-agnostic OpenSSL (except no OpenSSL is embedded) and libunwind (a copy of libunwind is embedded this repo).
./src/installer/managed/Microsoft.NET.HostModel/ComHost/ComHost.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; using System.Text; namespace Microsoft.NET.HostModel.ComHost { public class ComHost { private const int E_INVALIDARG = unchecked((int)0x80070057); // These need to match RESOURCEID_CLSIDMAP and RESOURCETYPE_CLSIDMAP defined in comhost.h. private const int ClsidmapResourceId = 64; private const int ClsidmapResourceType = 1024; /// <summary> /// Create a ComHost with an embedded CLSIDMap file to map CLSIDs to .NET Classes. /// </summary> /// <param name="comHostSourceFilePath">The path of Apphost template, which has the place holder</param> /// <param name="comHostDestinationFilePath">The destination path for desired location to place, including the file name</param> /// <param name="clsidmapFilePath">The path to the *.clsidmap file.</param> /// <param name="typeLibraries">Resource ids for tlbs and paths to the tlb files to be embedded.</param> public static void Create( string comHostSourceFilePath, string comHostDestinationFilePath, string clsidmapFilePath, IReadOnlyDictionary<int, string> typeLibraries = null) { var destinationDirectory = new FileInfo(comHostDestinationFilePath).Directory.FullName; if (!Directory.Exists(destinationDirectory)) { Directory.CreateDirectory(destinationDirectory); } // Copy apphost to destination path so it inherits the same attributes/permissions. File.Copy(comHostSourceFilePath, comHostDestinationFilePath, overwrite: true); if (!ResourceUpdater.IsSupportedOS()) { throw new ComHostCustomizationUnsupportedOSException(); } string clsidMap = File.ReadAllText(clsidmapFilePath); byte[] clsidMapBytes = Encoding.UTF8.GetBytes(clsidMap); using (ResourceUpdater updater = new ResourceUpdater(comHostDestinationFilePath)) { updater.AddResource(clsidMapBytes, (IntPtr)ClsidmapResourceType, (IntPtr)ClsidmapResourceId); if (typeLibraries is not null) { foreach (var typeLibrary in typeLibraries) { if (!ResourceUpdater.IsIntResource((IntPtr)typeLibrary.Key)) { throw new InvalidTypeLibraryIdException(typeLibrary.Value, typeLibrary.Key); } try { byte[] tlbFileBytes = File.ReadAllBytes(typeLibrary.Value); updater.AddResource(tlbFileBytes, "typelib", (IntPtr)typeLibrary.Key); } catch (FileNotFoundException ex) { throw new TypeLibraryDoesNotExistException(typeLibrary.Value, ex); } catch (HResultException hr) when (hr.Win32HResult == E_INVALIDARG) { throw new InvalidTypeLibraryException(typeLibrary.Value, hr); } } } updater.Update(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; using System.Text; namespace Microsoft.NET.HostModel.ComHost { public class ComHost { private const int E_INVALIDARG = unchecked((int)0x80070057); // These need to match RESOURCEID_CLSIDMAP and RESOURCETYPE_CLSIDMAP defined in comhost.h. private const int ClsidmapResourceId = 64; private const int ClsidmapResourceType = 1024; /// <summary> /// Create a ComHost with an embedded CLSIDMap file to map CLSIDs to .NET Classes. /// </summary> /// <param name="comHostSourceFilePath">The path of Apphost template, which has the place holder</param> /// <param name="comHostDestinationFilePath">The destination path for desired location to place, including the file name</param> /// <param name="clsidmapFilePath">The path to the *.clsidmap file.</param> /// <param name="typeLibraries">Resource ids for tlbs and paths to the tlb files to be embedded.</param> public static void Create( string comHostSourceFilePath, string comHostDestinationFilePath, string clsidmapFilePath, IReadOnlyDictionary<int, string> typeLibraries = null) { var destinationDirectory = new FileInfo(comHostDestinationFilePath).Directory.FullName; if (!Directory.Exists(destinationDirectory)) { Directory.CreateDirectory(destinationDirectory); } // Copy apphost to destination path so it inherits the same attributes/permissions. File.Copy(comHostSourceFilePath, comHostDestinationFilePath, overwrite: true); if (!ResourceUpdater.IsSupportedOS()) { throw new ComHostCustomizationUnsupportedOSException(); } string clsidMap = File.ReadAllText(clsidmapFilePath); byte[] clsidMapBytes = Encoding.UTF8.GetBytes(clsidMap); using (ResourceUpdater updater = new ResourceUpdater(comHostDestinationFilePath)) { updater.AddResource(clsidMapBytes, (IntPtr)ClsidmapResourceType, (IntPtr)ClsidmapResourceId); if (typeLibraries is not null) { foreach (var typeLibrary in typeLibraries) { if (!ResourceUpdater.IsIntResource((IntPtr)typeLibrary.Key)) { throw new InvalidTypeLibraryIdException(typeLibrary.Value, typeLibrary.Key); } try { byte[] tlbFileBytes = File.ReadAllBytes(typeLibrary.Value); updater.AddResource(tlbFileBytes, "typelib", (IntPtr)typeLibrary.Key); } catch (FileNotFoundException ex) { throw new TypeLibraryDoesNotExistException(typeLibrary.Value, ex); } catch (HResultException hr) when (hr.Win32HResult == E_INVALIDARG) { throw new InvalidTypeLibraryException(typeLibrary.Value, hr); } } } updater.Update(); } } } }
-1
dotnet/runtime
66,452
[mono] Stop setting time_date_stamp field in MonoImage
We never read that field in the runtime and it was causing unnecessary disk IO during startup (5ms on my iOS device). It was also never set on Windows already.
akoeplinger
2022-03-10T15:49:37Z
2022-03-10T21:47:58Z
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
d2826308964e4ee4496d6884e09811e1f709005e
[mono] Stop setting time_date_stamp field in MonoImage. We never read that field in the runtime and it was causing unnecessary disk IO during startup (5ms on my iOS device). It was also never set on Windows already.
./src/mono/mono/metadata/image.c
/** * \file * Routines for manipulating an image stored in an * extended PE/COFF file. * * Authors: * Miguel de Icaza ([email protected]) * Paolo Molaro ([email protected]) * * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com) * Copyright 2004-2009 Novell, Inc (http://www.novell.com) * * Licensed under the MIT license. See LICENSE file in the project root for full license information. */ #include <config.h> #include <stdio.h> #include <glib.h> #include <errno.h> #include <time.h> #include <string.h> #include <mono/metadata/image.h> #include "cil-coff.h" #include "mono-endian.h" #include "tabledefs.h" #include <mono/metadata/tokentype.h> #include "metadata-internals.h" #include "metadata-update.h" #include "profiler-private.h" #include <mono/metadata/loader.h> #include "marshal.h" #include "coree.h" #include <mono/metadata/exception-internals.h> #include <mono/utils/checked-build.h> #include <mono/utils/mono-logger-internals.h> #include <mono/utils/mono-errno.h> #include <mono/utils/mono-path.h> #include <mono/utils/mono-mmap.h> #include <mono/utils/atomic.h> #include <mono/utils/mono-proclib.h> #include <mono/metadata/class-internals.h> #include <mono/metadata/assembly.h> #include <mono/metadata/object-internals.h> #include <mono/metadata/verify.h> #include <mono/metadata/image-internals.h> #include <mono/metadata/loaded-images-internals.h> #include <mono/metadata/metadata-update.h> #include <mono/metadata/debug-internals.h> #include <mono/metadata/mono-private-unstable.h> #include <sys/types.h> #include <sys/stat.h> #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #include <mono/metadata/w32error.h> #define INVALID_ADDRESS 0xffffffff // Amount initially reserved in each image's mempool. // FIXME: This number is arbitrary, a more practical number should be found #define INITIAL_IMAGE_SIZE 512 // Change the assembly set in `image` to the assembly set in `assemblyImage`. Halt if overwriting is attempted. // Can be used on modules loaded through either the "file" or "module" mechanism static gboolean assign_assembly_parent_for_netmodule (MonoImage *image, MonoImage *assemblyImage, MonoError *error) { // Assembly to assign MonoAssembly *assembly = assemblyImage->assembly; while (1) { // Assembly currently assigned MonoAssembly *assemblyOld = image->assembly; if (assemblyOld) { if (assemblyOld == assembly) return TRUE; mono_error_set_bad_image (error, assemblyImage, "Attempted to load module %s which has already been loaded by assembly %s. This is not supported in Mono.", image->name, assemblyOld->image->name); return FALSE; } gpointer result = mono_atomic_xchg_ptr((gpointer *)&image->assembly, assembly); if (result == assembly) return TRUE; } } static gboolean debug_assembly_unload = FALSE; #define mono_images_storage_lock() do { if (mutex_inited) mono_os_mutex_lock (&images_storage_mutex); } while (0) #define mono_images_storage_unlock() do { if (mutex_inited) mono_os_mutex_unlock (&images_storage_mutex); } while (0) static gboolean mutex_inited; static mono_mutex_t images_mutex; static mono_mutex_t images_storage_mutex; void mono_images_lock (void) { if (mutex_inited) mono_os_mutex_lock (&images_mutex); } void mono_images_unlock(void) { if (mutex_inited) mono_os_mutex_unlock (&images_mutex); } static MonoImage * mono_image_open_a_lot_parameterized (MonoLoadedImages *li, MonoAssemblyLoadContext *alc, const char *fname, MonoImageOpenStatus *status); /* Maps string keys to MonoImageStorage values. * * The MonoImageStorage in the hash owns the key. */ static GHashTable *images_storage_hash; static void install_pe_loader (void); typedef struct ImageUnloadHook ImageUnloadHook; struct ImageUnloadHook { MonoImageUnloadFunc func; gpointer user_data; }; static GSList *image_unload_hooks; void mono_install_image_unload_hook (MonoImageUnloadFunc func, gpointer user_data) { ImageUnloadHook *hook; g_return_if_fail (func != NULL); hook = g_new0 (ImageUnloadHook, 1); hook->func = func; hook->user_data = user_data; image_unload_hooks = g_slist_prepend (image_unload_hooks, hook); } void mono_remove_image_unload_hook (MonoImageUnloadFunc func, gpointer user_data) { GSList *l; ImageUnloadHook *hook; for (l = image_unload_hooks; l; l = l->next) { hook = (ImageUnloadHook *)l->data; if (hook->func == func && hook->user_data == user_data) { g_free (hook); image_unload_hooks = g_slist_delete_link (image_unload_hooks, l); break; } } } static void mono_image_invoke_unload_hook (MonoImage *image) { GSList *l; ImageUnloadHook *hook; for (l = image_unload_hooks; l; l = l->next) { hook = (ImageUnloadHook *)l->data; hook->func (image, hook->user_data); } } static GSList *image_loaders; void mono_install_image_loader (const MonoImageLoader *loader) { image_loaders = g_slist_prepend (image_loaders, (MonoImageLoader*)loader); } /* returns offset relative to image->raw_data */ guint32 mono_cli_rva_image_map (MonoImage *image, guint32 addr) { MonoCLIImageInfo *iinfo = image->image_info; const int top = iinfo->cli_section_count; MonoSectionTable *tables = iinfo->cli_section_tables; int i; if (image->metadata_only) return addr; for (i = 0; i < top; i++){ if ((addr >= tables->st_virtual_address) && (addr < tables->st_virtual_address + tables->st_raw_data_size)){ #ifdef HOST_WIN32 if (m_image_is_module_handle (image)) return addr; #endif return addr - tables->st_virtual_address + tables->st_raw_data_ptr; } tables++; } return INVALID_ADDRESS; } /** * mono_image_rva_map: * \param image a \c MonoImage * \param addr relative virtual address (RVA) * * This is a low-level routine used by the runtime to map relative * virtual address (RVA) into their location in memory. * * \returns the address in memory for the given RVA, or NULL if the * RVA is not valid for this image. */ char * mono_image_rva_map (MonoImage *image, guint32 addr) { MonoCLIImageInfo *iinfo = image->image_info; const int top = iinfo->cli_section_count; MonoSectionTable *tables = iinfo->cli_section_tables; int i; #ifdef HOST_WIN32 if (m_image_is_module_handle (image)) { if (addr && addr < image->raw_data_len) return image->raw_data + addr; else return NULL; } #endif for (i = 0; i < top; i++){ if ((addr >= tables->st_virtual_address) && (addr < tables->st_virtual_address + tables->st_raw_data_size)){ if (!iinfo->cli_sections [i]) { if (!mono_image_ensure_section_idx (image, i)) return NULL; } return (char*)iinfo->cli_sections [i] + (addr - tables->st_virtual_address); } tables++; } return NULL; } /** * mono_images_init: * * Initialize the global variables used by this module. */ void mono_images_init (void) { mono_os_mutex_init (&images_storage_mutex); mono_os_mutex_init_recursive (&images_mutex); images_storage_hash = g_hash_table_new (g_str_hash, g_str_equal); debug_assembly_unload = g_hasenv ("MONO_DEBUG_ASSEMBLY_UNLOAD"); install_pe_loader (); mutex_inited = TRUE; } /** * mono_images_cleanup: * * Free all resources used by this module. */ void mono_images_cleanup (void) { } /** * mono_image_ensure_section_idx: * \param image The image we are operating on * \param section section number that we will load/map into memory * * This routine makes sure that we have an in-memory copy of * an image section (<code>.text</code>, <code>.rsrc</code>, <code>.data</code>). * * \returns TRUE on success */ int mono_image_ensure_section_idx (MonoImage *image, int section) { MonoCLIImageInfo *iinfo = image->image_info; MonoSectionTable *sect; g_return_val_if_fail (section < iinfo->cli_section_count, FALSE); if (iinfo->cli_sections [section] != NULL) return TRUE; sect = &iinfo->cli_section_tables [section]; if (sect->st_raw_data_ptr + sect->st_raw_data_size > image->raw_data_len) return FALSE; #ifdef HOST_WIN32 if (m_image_is_module_handle (image)) iinfo->cli_sections [section] = image->raw_data + sect->st_virtual_address; else #endif /* FIXME: we ignore the writable flag since we don't patch the binary */ iinfo->cli_sections [section] = image->raw_data + sect->st_raw_data_ptr; return TRUE; } /** * mono_image_ensure_section: * \param image The image we are operating on * \param section section name that we will load/map into memory * * This routine makes sure that we have an in-memory copy of * an image section (.text, .rsrc, .data). * * \returns TRUE on success */ int mono_image_ensure_section (MonoImage *image, const char *section) { MonoCLIImageInfo *ii = image->image_info; int i; for (i = 0; i < ii->cli_section_count; i++){ if (strncmp (ii->cli_section_tables [i].st_name, section, 8) != 0) continue; return mono_image_ensure_section_idx (image, i); } return FALSE; } static int load_section_tables (MonoImage *image, MonoCLIImageInfo *iinfo, guint32 offset) { const int top = iinfo->cli_header.coff.coff_sections; int i; iinfo->cli_section_count = top; iinfo->cli_section_tables = g_new0 (MonoSectionTable, top); iinfo->cli_sections = g_new0 (void *, top); for (i = 0; i < top; i++){ MonoSectionTable *t = &iinfo->cli_section_tables [i]; if (offset + sizeof (MonoSectionTable) > image->raw_data_len) return FALSE; memcpy (t, image->raw_data + offset, sizeof (MonoSectionTable)); offset += sizeof (MonoSectionTable); #if G_BYTE_ORDER != G_LITTLE_ENDIAN t->st_virtual_size = GUINT32_FROM_LE (t->st_virtual_size); t->st_virtual_address = GUINT32_FROM_LE (t->st_virtual_address); t->st_raw_data_size = GUINT32_FROM_LE (t->st_raw_data_size); t->st_raw_data_ptr = GUINT32_FROM_LE (t->st_raw_data_ptr); t->st_reloc_ptr = GUINT32_FROM_LE (t->st_reloc_ptr); t->st_lineno_ptr = GUINT32_FROM_LE (t->st_lineno_ptr); t->st_reloc_count = GUINT16_FROM_LE (t->st_reloc_count); t->st_line_count = GUINT16_FROM_LE (t->st_line_count); t->st_flags = GUINT32_FROM_LE (t->st_flags); #endif /* consistency checks here */ } return TRUE; } gboolean mono_image_load_cli_header (MonoImage *image, MonoCLIImageInfo *iinfo) { guint32 offset; offset = mono_cli_rva_image_map (image, iinfo->cli_header.datadir.pe_cli_header.rva); if (offset == INVALID_ADDRESS) return FALSE; if (offset + sizeof (MonoCLIHeader) > image->raw_data_len) return FALSE; memcpy (&iinfo->cli_cli_header, image->raw_data + offset, sizeof (MonoCLIHeader)); #if G_BYTE_ORDER != G_LITTLE_ENDIAN #define SWAP32(x) (x) = GUINT32_FROM_LE ((x)) #define SWAP16(x) (x) = GUINT16_FROM_LE ((x)) #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0) SWAP32 (iinfo->cli_cli_header.ch_size); SWAP32 (iinfo->cli_cli_header.ch_flags); SWAP32 (iinfo->cli_cli_header.ch_entry_point); SWAP16 (iinfo->cli_cli_header.ch_runtime_major); SWAP16 (iinfo->cli_cli_header.ch_runtime_minor); SWAPPDE (iinfo->cli_cli_header.ch_metadata); SWAPPDE (iinfo->cli_cli_header.ch_resources); SWAPPDE (iinfo->cli_cli_header.ch_strong_name); SWAPPDE (iinfo->cli_cli_header.ch_code_manager_table); SWAPPDE (iinfo->cli_cli_header.ch_vtable_fixups); SWAPPDE (iinfo->cli_cli_header.ch_export_address_table_jumps); SWAPPDE (iinfo->cli_cli_header.ch_eeinfo_table); SWAPPDE (iinfo->cli_cli_header.ch_helper_table); SWAPPDE (iinfo->cli_cli_header.ch_dynamic_info); SWAPPDE (iinfo->cli_cli_header.ch_delay_load_info); SWAPPDE (iinfo->cli_cli_header.ch_module_image); SWAPPDE (iinfo->cli_cli_header.ch_external_fixups); SWAPPDE (iinfo->cli_cli_header.ch_ridmap); SWAPPDE (iinfo->cli_cli_header.ch_debug_map); SWAPPDE (iinfo->cli_cli_header.ch_ip_map); #undef SWAP32 #undef SWAP16 #undef SWAPPDE #endif /* Catch new uses of the fields that are supposed to be zero */ if ((iinfo->cli_cli_header.ch_eeinfo_table.rva != 0) || (iinfo->cli_cli_header.ch_helper_table.rva != 0) || (iinfo->cli_cli_header.ch_dynamic_info.rva != 0) || (iinfo->cli_cli_header.ch_delay_load_info.rva != 0) || (iinfo->cli_cli_header.ch_module_image.rva != 0) || (iinfo->cli_cli_header.ch_external_fixups.rva != 0) || (iinfo->cli_cli_header.ch_ridmap.rva != 0) || (iinfo->cli_cli_header.ch_debug_map.rva != 0) || (iinfo->cli_cli_header.ch_ip_map.rva != 0)){ /* * No need to scare people who are testing this, I am just * labelling this as a LAMESPEC */ /* g_warning ("Some fields in the CLI header which should have been zero are not zero"); */ } return TRUE; } /** * mono_metadata_module_mvid: * * Return the module mvid GUID or NULL if the image doesn't have a module table. */ static const guint8 * mono_metadata_module_mvid (MonoImage *image) { if (!image->tables [MONO_TABLE_MODULE].base) return NULL; guint32 module_cols [MONO_MODULE_SIZE]; mono_metadata_decode_row (&image->tables [MONO_TABLE_MODULE], 0, module_cols, MONO_MODULE_SIZE); return (const guint8*) mono_metadata_guid_heap (image, module_cols [MONO_MODULE_MVID]); } static gboolean load_metadata_ptrs (MonoImage *image, MonoCLIImageInfo *iinfo) { guint32 offset, size; guint16 streams; int i; guint32 pad; char *ptr; offset = mono_cli_rva_image_map (image, iinfo->cli_cli_header.ch_metadata.rva); if (offset == INVALID_ADDRESS) return FALSE; size = iinfo->cli_cli_header.ch_metadata.size; if (offset + size > image->raw_data_len) return FALSE; image->raw_metadata = image->raw_data + offset; /* 24.2.1: Metadata root starts here */ ptr = image->raw_metadata; if (strncmp (ptr, "BSJB", 4) == 0){ guint32 version_string_len; ptr += 4; image->md_version_major = read16 (ptr); ptr += 2; image->md_version_minor = read16 (ptr); ptr += 6; version_string_len = read32 (ptr); ptr += 4; image->version = g_strndup (ptr, version_string_len); ptr += version_string_len; pad = ptr - image->raw_metadata; if (pad % 4) ptr += 4 - (pad % 4); } else return FALSE; /* skip over flags */ ptr += 2; streams = read16 (ptr); ptr += 2; for (i = 0; i < streams; i++){ if (strncmp (ptr + 8, "#~", 3) == 0){ image->heap_tables.data = image->raw_metadata + read32 (ptr); image->heap_tables.size = read32 (ptr + 4); ptr += 8 + 3; } else if (strncmp (ptr + 8, "#Strings", 9) == 0){ image->heap_strings.data = image->raw_metadata + read32 (ptr); image->heap_strings.size = read32 (ptr + 4); ptr += 8 + 9; } else if (strncmp (ptr + 8, "#US", 4) == 0){ image->heap_us.data = image->raw_metadata + read32 (ptr); image->heap_us.size = read32 (ptr + 4); ptr += 8 + 4; } else if (strncmp (ptr + 8, "#Blob", 6) == 0){ image->heap_blob.data = image->raw_metadata + read32 (ptr); image->heap_blob.size = read32 (ptr + 4); ptr += 8 + 6; } else if (strncmp (ptr + 8, "#GUID", 6) == 0){ image->heap_guid.data = image->raw_metadata + read32 (ptr); image->heap_guid.size = read32 (ptr + 4); ptr += 8 + 6; } else if (strncmp (ptr + 8, "#-", 3) == 0) { image->heap_tables.data = image->raw_metadata + read32 (ptr); image->heap_tables.size = read32 (ptr + 4); ptr += 8 + 3; image->uncompressed_metadata = TRUE; mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_ASSEMBLY, "Assembly '%s' has the non-standard metadata heap #-.\nRecompile it correctly (without the /incremental switch or in Release mode).", image->name); } else if (strncmp (ptr + 8, "#Pdb", 5) == 0) { image->heap_pdb.data = image->raw_metadata + read32 (ptr); image->heap_pdb.size = read32 (ptr + 4); ptr += 8 + 5; } else if (strncmp (ptr + 8, "#JTD", 5) == 0) { // See https://github.com/dotnet/runtime/blob/110282c71b3f7e1f91ea339953f4a0eba362a62c/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReader.cs#L165-L175 // skip read32(ptr) and read32(ptr + 4) // ignore the content of this stream image->minimal_delta = TRUE; mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_METADATA_UPDATE, "Image '%s' has a minimal delta marker", image->name); ptr += 8 + 5; } else { g_message ("Unknown heap type: %s\n", ptr + 8); ptr += 8 + strlen (ptr + 8) + 1; } pad = ptr - image->raw_metadata; if (pad % 4) ptr += 4 - (pad % 4); } { /* Compute the precise size of the string heap by walking back over the trailing nul padding. * * ENC minimal delta images require the precise size of the base image string heap to be known. */ const char *p; p = image->heap_strings.data + image->heap_strings.size - 1; pad = 0; while (p [0] == '\0' && p [-1] == '\0') { p--; pad++; } image->heap_strings.size -= pad; } i = ((MonoImageLoader*)image->loader)->load_tables (image); if (!image->metadata_only) { g_assert (image->heap_guid.data); g_assert (image->heap_guid.size >= 16); image->guid = mono_guid_to_string ((guint8*)image->heap_guid.data); } else { const guint8 *guid = mono_metadata_module_mvid (image); if (guid) image->guid = mono_guid_to_string (guid); else { /* PPDB files have no guid */ guint8 empty_guid [16]; memset (empty_guid, 0, sizeof (empty_guid)); image->guid = mono_guid_to_string (empty_guid); } } return i; } /* * Load representation of logical metadata tables, from the "#~" or "#-" stream */ static gboolean load_tables (MonoImage *image) { const char *heap_tables = image->heap_tables.data; const guint32 *rows; guint64 valid_mask; int valid = 0, table; int heap_sizes; heap_sizes = heap_tables [6]; image->idx_string_wide = ((heap_sizes & 0x01) == 1); image->idx_guid_wide = ((heap_sizes & 0x02) == 2); image->idx_blob_wide = ((heap_sizes & 0x04) == 4); if (G_UNLIKELY (image->minimal_delta)) { /* sanity check */ g_assert (image->idx_string_wide); g_assert (image->idx_guid_wide); g_assert (image->idx_blob_wide); } valid_mask = read64 (heap_tables + 8); rows = (const guint32 *) (heap_tables + 24); for (table = 0; table < 64; table++){ if ((valid_mask & ((guint64) 1 << table)) == 0){ if (table > MONO_TABLE_LAST) continue; image->tables [table].rows_ = 0; continue; } if (table > MONO_TABLE_LAST) { g_warning("bits in valid must be zero above 0x37 (II - 23.1.6)"); } else { image->tables [table].rows_ = read32 (rows); } rows++; valid++; } image->tables_base = (heap_tables + 24) + (4 * valid); /* They must be the same */ g_assert ((const void *) image->tables_base == (const void *) rows); if (image->heap_pdb.size) { /* * Obtain token sizes from the pdb stream. */ /* 24 = guid + entry point */ int pos = 24; image->referenced_tables = read64 (image->heap_pdb.data + pos); pos += 8; image->referenced_table_rows = g_new0 (int, 64); for (int i = 0; i < 64; ++i) { if (image->referenced_tables & ((guint64)1 << i)) { image->referenced_table_rows [i] = read32 (image->heap_pdb.data + pos); pos += 4; } } } mono_metadata_compute_table_bases (image); return TRUE; } gboolean mono_image_load_metadata (MonoImage *image, MonoCLIImageInfo *iinfo) { if (!load_metadata_ptrs (image, iinfo)) return FALSE; return load_tables (image); } void mono_image_check_for_module_cctor (MonoImage *image) { MonoTableInfo *t, *mt; t = &image->tables [MONO_TABLE_TYPEDEF]; mt = &image->tables [MONO_TABLE_METHOD]; if (image_is_dynamic (image)) { /* FIXME: */ image->checked_module_cctor = TRUE; return; } if (table_info_get_rows (t) >= 1) { guint32 nameidx = mono_metadata_decode_row_col (t, 0, MONO_TYPEDEF_NAME); const char *name = mono_metadata_string_heap (image, nameidx); if (strcmp (name, "<Module>") == 0) { guint32 first_method = mono_metadata_decode_row_col (t, 0, MONO_TYPEDEF_METHOD_LIST) - 1; guint32 last_method; if (table_info_get_rows (t) > 1) last_method = mono_metadata_decode_row_col (t, 1, MONO_TYPEDEF_METHOD_LIST) - 1; else last_method = table_info_get_rows (mt); for (; first_method < last_method; first_method++) { nameidx = mono_metadata_decode_row_col (mt, first_method, MONO_METHOD_NAME); name = mono_metadata_string_heap (image, nameidx); if (strcmp (name, ".cctor") == 0) { image->has_module_cctor = TRUE; image->checked_module_cctor = TRUE; return; } } } } image->has_module_cctor = FALSE; image->checked_module_cctor = TRUE; } /** * mono_image_load_module_checked: * * Load the module with the one-based index IDX from IMAGE and return it. Return NULL if * it cannot be loaded. NULL without MonoError being set will be interpreted as "not found". */ MonoImage* mono_image_load_module_checked (MonoImage *image, int idx, MonoError *error) { error_init (error); if ((image->module_count == 0) || (idx > image->module_count || idx <= 0)) return NULL; if (image->modules_loaded [idx - 1]) return image->modules [idx - 1]; /* SRE still uses image->modules, but they are not loaded from files, so the rest of this function is dead code for netcore */ g_assert_not_reached (); } /** * mono_image_load_module: */ MonoImage* mono_image_load_module (MonoImage *image, int idx) { ERROR_DECL (error); MonoImage *result = mono_image_load_module_checked (image, idx, error); mono_error_assert_ok (error); return result; } static gpointer class_key_extract (gpointer value) { MonoClass *klass = (MonoClass *)value; return GUINT_TO_POINTER (m_class_get_type_token (klass)); } static gpointer* class_next_value (gpointer value) { MonoClassDef *klass = (MonoClassDef *)value; return (gpointer*)m_classdef_get_next_class_cache (klass); } /** * mono_image_init: */ void mono_image_init (MonoImage *image) { mono_os_mutex_init_recursive (&image->lock); mono_os_mutex_init_recursive (&image->szarray_cache_lock); image->mempool = mono_mempool_new_size (INITIAL_IMAGE_SIZE); mono_internal_hash_table_init (&image->class_cache, g_direct_hash, class_key_extract, class_next_value); image->field_cache = mono_conc_hashtable_new (NULL, NULL); image->typespec_cache = mono_conc_hashtable_new (NULL, NULL); image->memberref_signatures = g_hash_table_new (NULL, NULL); image->method_signatures = g_hash_table_new (NULL, NULL); image->property_hash = mono_property_hash_new (); } #if G_BYTE_ORDER != G_LITTLE_ENDIAN #define SWAP64(x) (x) = GUINT64_FROM_LE ((x)) #define SWAP32(x) (x) = GUINT32_FROM_LE ((x)) #define SWAP16(x) (x) = GUINT16_FROM_LE ((x)) #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0) #else #define SWAP64(x) #define SWAP32(x) #define SWAP16(x) #define SWAPPDE(x) #endif static int do_load_header_internal (const char *raw_data, guint32 raw_data_len, MonoDotNetHeader *header, int offset, gboolean image_is_module_handle) { MonoDotNetHeader64 header64; #ifdef HOST_WIN32 if (!image_is_module_handle) #endif if (offset + sizeof (MonoDotNetHeader32) > raw_data_len) return -1; memcpy (header, raw_data + offset, sizeof (MonoDotNetHeader)); if (header->pesig [0] != 'P' || header->pesig [1] != 'E' || header->pesig [2] || header->pesig [3]) return -1; /* endian swap the fields common between PE and PE+ */ SWAP32 (header->coff.coff_time); SWAP32 (header->coff.coff_symptr); SWAP32 (header->coff.coff_symcount); SWAP16 (header->coff.coff_machine); SWAP16 (header->coff.coff_sections); SWAP16 (header->coff.coff_opt_header_size); SWAP16 (header->coff.coff_attributes); /* MonoPEHeader */ SWAP32 (header->pe.pe_code_size); SWAP32 (header->pe.pe_uninit_data_size); SWAP32 (header->pe.pe_rva_entry_point); SWAP32 (header->pe.pe_rva_code_base); SWAP32 (header->pe.pe_rva_data_base); SWAP16 (header->pe.pe_magic); /* now we are ready for the basic tests */ if (header->pe.pe_magic == 0x10B) { offset += sizeof (MonoDotNetHeader); SWAP32 (header->pe.pe_data_size); if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader) - sizeof (MonoCOFFHeader) - 4)) return -1; SWAP32 (header->nt.pe_image_base); /* must be 0x400000 */ SWAP32 (header->nt.pe_stack_reserve); SWAP32 (header->nt.pe_stack_commit); SWAP32 (header->nt.pe_heap_reserve); SWAP32 (header->nt.pe_heap_commit); } else if (header->pe.pe_magic == 0x20B) { /* PE32+ file format */ if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader64) - sizeof (MonoCOFFHeader) - 4)) return -1; memcpy (&header64, raw_data + offset, sizeof (MonoDotNetHeader64)); offset += sizeof (MonoDotNetHeader64); /* copy the fields already swapped. the last field, pe_data_size, is missing */ memcpy (&header64, header, sizeof (MonoDotNetHeader) - 4); /* FIXME: we lose bits here, but we don't use this stuff internally, so we don't care much. * will be fixed when we change MonoDotNetHeader to not match the 32 bit variant */ SWAP64 (header64.nt.pe_image_base); header->nt.pe_image_base = header64.nt.pe_image_base; SWAP64 (header64.nt.pe_stack_reserve); header->nt.pe_stack_reserve = header64.nt.pe_stack_reserve; SWAP64 (header64.nt.pe_stack_commit); header->nt.pe_stack_commit = header64.nt.pe_stack_commit; SWAP64 (header64.nt.pe_heap_reserve); header->nt.pe_heap_reserve = header64.nt.pe_heap_reserve; SWAP64 (header64.nt.pe_heap_commit); header->nt.pe_heap_commit = header64.nt.pe_heap_commit; header->nt.pe_section_align = header64.nt.pe_section_align; header->nt.pe_file_alignment = header64.nt.pe_file_alignment; header->nt.pe_os_major = header64.nt.pe_os_major; header->nt.pe_os_minor = header64.nt.pe_os_minor; header->nt.pe_user_major = header64.nt.pe_user_major; header->nt.pe_user_minor = header64.nt.pe_user_minor; header->nt.pe_subsys_major = header64.nt.pe_subsys_major; header->nt.pe_subsys_minor = header64.nt.pe_subsys_minor; header->nt.pe_reserved_1 = header64.nt.pe_reserved_1; header->nt.pe_image_size = header64.nt.pe_image_size; header->nt.pe_header_size = header64.nt.pe_header_size; header->nt.pe_checksum = header64.nt.pe_checksum; header->nt.pe_subsys_required = header64.nt.pe_subsys_required; header->nt.pe_dll_flags = header64.nt.pe_dll_flags; header->nt.pe_loader_flags = header64.nt.pe_loader_flags; header->nt.pe_data_dir_count = header64.nt.pe_data_dir_count; /* copy the datadir */ memcpy (&header->datadir, &header64.datadir, sizeof (MonoPEDatadir)); } else { return -1; } /* MonoPEHeaderNT: not used yet */ SWAP32 (header->nt.pe_section_align); /* must be 8192 */ SWAP32 (header->nt.pe_file_alignment); /* must be 512 or 4096 */ SWAP16 (header->nt.pe_os_major); /* must be 4 */ SWAP16 (header->nt.pe_os_minor); /* must be 0 */ SWAP16 (header->nt.pe_user_major); SWAP16 (header->nt.pe_user_minor); SWAP16 (header->nt.pe_subsys_major); SWAP16 (header->nt.pe_subsys_minor); SWAP32 (header->nt.pe_reserved_1); SWAP32 (header->nt.pe_image_size); SWAP32 (header->nt.pe_header_size); SWAP32 (header->nt.pe_checksum); SWAP16 (header->nt.pe_subsys_required); SWAP16 (header->nt.pe_dll_flags); SWAP32 (header->nt.pe_loader_flags); SWAP32 (header->nt.pe_data_dir_count); /* MonoDotNetHeader: mostly unused */ SWAPPDE (header->datadir.pe_export_table); SWAPPDE (header->datadir.pe_import_table); SWAPPDE (header->datadir.pe_resource_table); SWAPPDE (header->datadir.pe_exception_table); SWAPPDE (header->datadir.pe_certificate_table); SWAPPDE (header->datadir.pe_reloc_table); SWAPPDE (header->datadir.pe_debug); SWAPPDE (header->datadir.pe_copyright); SWAPPDE (header->datadir.pe_global_ptr); SWAPPDE (header->datadir.pe_tls_table); SWAPPDE (header->datadir.pe_load_config_table); SWAPPDE (header->datadir.pe_bound_import); SWAPPDE (header->datadir.pe_iat); SWAPPDE (header->datadir.pe_delay_import_desc); SWAPPDE (header->datadir.pe_cli_header); SWAPPDE (header->datadir.pe_reserved); return offset; } /* * Returns < 0 to indicate an error. */ static int do_load_header (MonoImage *image, MonoDotNetHeader *header, int offset) { offset = do_load_header_internal (image->raw_data, image->raw_data_len, header, offset, #ifdef HOST_WIN32 m_image_is_module_handle (image)); #else FALSE); #endif #ifdef HOST_WIN32 if (m_image_is_module_handle (image)) image->storage->raw_data_len = header->nt.pe_image_size; #endif return offset; } mono_bool mono_has_pdb_checksum (char *raw_data, uint32_t raw_data_len) { MonoDotNetHeader cli_header; MonoMSDOSHeader msdos; int idx; guint8 *data; int offset = 0; memcpy (&msdos, raw_data + offset, sizeof (msdos)); if (!(msdos.msdos_sig [0] == 'M' && msdos.msdos_sig [1] == 'Z')) { return FALSE; } msdos.pe_offset = GUINT32_FROM_LE (msdos.pe_offset); offset = msdos.pe_offset; int ret = do_load_header_internal (raw_data, raw_data_len, &cli_header, offset, FALSE); if ( ret >= 0 ) { MonoPEDirEntry *debug_dir_entry = (MonoPEDirEntry *) &cli_header.datadir.pe_debug; ImageDebugDirectory debug_dir; if (!debug_dir_entry->size) return FALSE; else { const int top = cli_header.coff.coff_sections; int addr = debug_dir_entry->rva; int i = 0; for (i = 0; i < top; i++){ MonoSectionTable t; if (ret + sizeof (MonoSectionTable) > raw_data_len) { return FALSE; } memcpy (&t, raw_data + ret, sizeof (MonoSectionTable)); ret += sizeof (MonoSectionTable); #if G_BYTE_ORDER != G_LITTLE_ENDIAN t.st_virtual_address = GUINT32_FROM_LE (t.st_virtual_address); t.st_raw_data_size = GUINT32_FROM_LE (t.st_raw_data_size); t.st_raw_data_ptr = GUINT32_FROM_LE (t.st_raw_data_ptr); #endif /* consistency checks here */ if ((addr >= t.st_virtual_address) && (addr < t.st_virtual_address + t.st_raw_data_size)){ addr = addr - t.st_virtual_address + t.st_raw_data_ptr; break; } } for (idx = 0; idx < debug_dir_entry->size / sizeof (ImageDebugDirectory); ++idx) { data = (guint8 *) ((ImageDebugDirectory *) (raw_data + addr) + idx); debug_dir.characteristics = read32(data); debug_dir.time_date_stamp = read32(data + 4); debug_dir.major_version = read16(data + 8); debug_dir.minor_version = read16(data + 10); debug_dir.type = read32(data + 12); if (debug_dir.type == DEBUG_DIR_PDB_CHECKSUM || debug_dir.type == DEBUG_DIR_REPRODUCIBLE) return TRUE; } } } return FALSE; } gboolean mono_image_load_pe_data (MonoImage *image) { return ((MonoImageLoader*)image->loader)->load_pe_data (image); } static gboolean pe_image_load_pe_data (MonoImage *image) { MonoCLIImageInfo *iinfo; MonoDotNetHeader *header; MonoMSDOSHeader msdos; gint32 offset = 0; iinfo = image->image_info; header = &iinfo->cli_header; #ifdef HOST_WIN32 if (!m_image_is_module_handle (image)) #endif if (offset + sizeof (msdos) > image->raw_data_len) goto invalid_image; memcpy (&msdos, image->raw_data + offset, sizeof (msdos)); if (!(msdos.msdos_sig [0] == 'M' && msdos.msdos_sig [1] == 'Z')) goto invalid_image; msdos.pe_offset = GUINT32_FROM_LE (msdos.pe_offset); offset = msdos.pe_offset; offset = do_load_header (image, header, offset); if (offset < 0) goto invalid_image; /* * this tests for a x86 machine type, but itanium, amd64 and others could be used, too. * we skip this test. if (header->coff.coff_machine != 0x14c) goto invalid_image; */ #if 0 /* * The spec says that this field should contain 6.0, but Visual Studio includes a new compiler, * which produces binaries with 7.0. From Sergey: * * The reason is that MSVC7 uses traditional compile/link * sequence for CIL executables, and VS.NET (and Framework * SDK) includes linker version 7, that puts 7.0 in this * field. That's why it's currently not possible to load VC * binaries with Mono. This field is pretty much meaningless * anyway (what linker?). */ if (header->pe.pe_major != 6 || header->pe.pe_minor != 0) goto invalid_image; #endif /* * FIXME: byte swap all addresses here for header. */ if (!load_section_tables (image, iinfo, offset)) goto invalid_image; return TRUE; invalid_image: return FALSE; } gboolean mono_image_load_cli_data (MonoImage *image) { return ((MonoImageLoader*)image->loader)->load_cli_data (image); } static gboolean pe_image_load_cli_data (MonoImage *image) { MonoCLIImageInfo *iinfo; iinfo = image->image_info; /* Load the CLI header */ if (!mono_image_load_cli_header (image, iinfo)) return FALSE; if (!mono_image_load_metadata (image, iinfo)) return FALSE; return TRUE; } static void mono_image_load_time_date_stamp (MonoImage *image) { image->time_date_stamp = 0; #ifndef HOST_WIN32 if (!image->filename) return; gunichar2 *uni_name = g_utf8_to_utf16 (image->filename, -1, NULL, NULL, NULL); mono_pe_file_time_date_stamp (uni_name, &image->time_date_stamp); g_free (uni_name); #endif } void mono_image_load_names (MonoImage *image) { /* modules don't have an assembly table row */ if (table_info_get_rows (&image->tables [MONO_TABLE_ASSEMBLY])) { image->assembly_name = mono_metadata_string_heap (image, mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY], 0, MONO_ASSEMBLY_NAME)); } /* Portable pdb images don't have a MODULE row */ /* Minimal ENC delta images index the combined string heap of the base and delta image, * so the module index is out of bounds here. */ if (table_info_get_rows (&image->tables [MONO_TABLE_MODULE]) && !image->minimal_delta) { image->module_name = mono_metadata_string_heap (image, mono_metadata_decode_row_col (&image->tables [MONO_TABLE_MODULE], 0, MONO_MODULE_NAME)); } } static gboolean pe_image_load_tables (MonoImage *image) { return TRUE; } static gboolean pe_image_match (MonoImage *image) { if (image->raw_data [0] == 'M' && image->raw_data [1] == 'Z') return TRUE; return FALSE; } static const MonoImageLoader pe_loader = { pe_image_match, pe_image_load_pe_data, pe_image_load_cli_data, pe_image_load_tables, }; static void install_pe_loader (void) { mono_install_image_loader (&pe_loader); } /* Equivalent C# code: static void Main () { string str = "..."; int h = 5381; for (int i = 0; i < str.Length; ++i) h = ((h << 5) + h) ^ str[i]; Console.WriteLine ("{0:X}", h); } */ static int hash_guid (const char *str) { int h = 5381; while (*str) { h = ((h << 5) + h) ^ *str; ++str; } return h; } static void dump_encmap (MonoImage *image) { MonoTableInfo *encmap = &image->tables [MONO_TABLE_ENCMAP]; if (!encmap || !table_info_get_rows (encmap)) return; if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE)) { mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "ENCMAP for %s", image->filename); for (int i = 0; i < table_info_get_rows (encmap); ++i) { guint32 cols [MONO_ENCMAP_SIZE]; mono_metadata_decode_row (encmap, i, cols, MONO_ENCMAP_SIZE); int token = cols [MONO_ENCMAP_TOKEN]; mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "\t0x%08x: 0x%08x table: %s", i+1, token, mono_meta_table_name (mono_metadata_token_table (token))); } } } static MonoImage * do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status, gboolean care_about_cli, gboolean care_about_pecoff) { ERROR_DECL (error); GSList *l; MONO_PROFILER_RAISE (image_loading, (image)); mono_image_init (image); if (!image->metadata_only) { for (l = image_loaders; l; l = l->next) { MonoImageLoader *loader = (MonoImageLoader *)l->data; if (loader->match (image)) { image->loader = loader; break; } } if (!image->loader) { if (status) *status = MONO_IMAGE_IMAGE_INVALID; goto invalid_image; } if (status) *status = MONO_IMAGE_IMAGE_INVALID; if (care_about_pecoff == FALSE) goto done; if (!mono_image_load_pe_data (image)) goto invalid_image; } else { image->loader = (MonoImageLoader*)&pe_loader; } if (care_about_cli == FALSE) { goto done; } if (!mono_image_load_cli_data (image)) goto invalid_image; dump_encmap (image); mono_image_load_names (image); mono_image_load_time_date_stamp (image); done: MONO_PROFILER_RAISE (image_loaded, (image)); if (status) *status = MONO_IMAGE_OK; return image; invalid_image: if (!is_ok (error)) { mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_ASSEMBLY, "Could not load image %s due to %s", image->name, mono_error_get_message (error)); mono_error_cleanup (error); } MONO_PROFILER_RAISE (image_failed, (image)); mono_image_close (image); return NULL; } static gboolean mono_image_storage_trypublish (MonoImageStorage *candidate, MonoImageStorage **out_storage) { gboolean result; mono_images_storage_lock (); MonoImageStorage *val = (MonoImageStorage *)g_hash_table_lookup (images_storage_hash, candidate->key); if (val && !mono_refcount_tryinc (val)) { // We raced against a mono_image_storage_dtor in progress. val = NULL; } if (val) { *out_storage = val; result = FALSE; } else { g_hash_table_insert (images_storage_hash, candidate->key, candidate); result = TRUE; } mono_images_storage_unlock (); return result; } static void mono_image_storage_unpublish (MonoImageStorage *storage) { mono_images_storage_lock (); g_assert (storage->ref.ref == 0); MonoImageStorage *published = (MonoImageStorage *)g_hash_table_lookup (images_storage_hash, storage->key); if (published == storage) { g_hash_table_remove (images_storage_hash, storage->key); } mono_images_storage_unlock (); } static gboolean mono_image_storage_tryaddref (const char *key, MonoImageStorage **found) { gboolean result = FALSE; mono_images_storage_lock (); MonoImageStorage *val = (MonoImageStorage *)g_hash_table_lookup (images_storage_hash, key); if (val && !mono_refcount_tryinc (val)) { // We raced against a mono_image_storage_dtor in progress. val = NULL; } if (val) { *found = val; result = TRUE; } mono_images_storage_unlock (); return result; } static void mono_image_storage_dtor (gpointer self) { MonoImageStorage *storage = (MonoImageStorage *)self; mono_image_storage_unpublish (storage); #ifdef HOST_WIN32 if (storage->is_module_handle && !storage->has_entry_point) { mono_images_lock (); FreeLibrary ((HMODULE) storage->raw_data); mono_images_unlock (); } #endif if (storage->raw_buffer_used) { if (storage->raw_data != NULL) { #ifndef HOST_WIN32 if (storage->fileio_used) mono_file_unmap_fileio (storage->raw_data, storage->raw_data_handle); else #endif mono_file_unmap (storage->raw_data, storage->raw_data_handle); } } if (storage->raw_data_allocated) { g_free (storage->raw_data); } g_free (storage->key); g_free (storage); } static void mono_image_storage_close (MonoImageStorage *storage) { mono_refcount_dec (storage); } static gboolean mono_image_init_raw_data (MonoImage *image, const MonoImageStorage *storage) { if (!storage) return FALSE; image->raw_data = storage->raw_data; image->raw_data_len = storage->raw_data_len; return TRUE; } static MonoImageStorage * mono_image_storage_open (const char *fname) { char *key = NULL; key = mono_path_resolve_symlinks (fname); MonoImageStorage *published_storage = NULL; if (mono_image_storage_tryaddref (key, &published_storage)) { g_free (key); return published_storage; } MonoFileMap *filed; if ((filed = mono_file_map_open (fname)) == NULL){ g_free (key); return NULL; } MonoImageStorage *storage = g_new0 (MonoImageStorage, 1); mono_refcount_init (storage, mono_image_storage_dtor); storage->raw_buffer_used = TRUE; storage->raw_data_len = mono_file_map_size (filed); storage->raw_data = (char*)mono_file_map (storage->raw_data_len, MONO_MMAP_READ|MONO_MMAP_PRIVATE, mono_file_map_fd (filed), 0, &storage->raw_data_handle); #if defined(HAVE_MMAP) && !defined (HOST_WIN32) if (!storage->raw_data) { storage->fileio_used = TRUE; storage->raw_data = (char *)mono_file_map_fileio (storage->raw_data_len, MONO_MMAP_READ|MONO_MMAP_PRIVATE, mono_file_map_fd (filed), 0, &storage->raw_data_handle); } #endif mono_file_map_close (filed); storage->key = key; MonoImageStorage *other_storage = NULL; if (!mono_image_storage_trypublish (storage, &other_storage)) { mono_image_storage_close (storage); storage = other_storage; } return storage; } static MonoImageStorage * mono_image_storage_new_raw_data (char *datac, guint32 data_len, gboolean raw_data_allocated, const char *name) { char *key = (name == NULL) ? g_strdup_printf ("data-%p", datac) : g_strdup (name); MonoImageStorage *published_storage = NULL; if (mono_image_storage_tryaddref (key, &published_storage)) { g_free (key); return published_storage; } MonoImageStorage *storage = g_new0 (MonoImageStorage, 1); mono_refcount_init (storage, mono_image_storage_dtor); storage->raw_data = datac; storage->raw_data_len = data_len; storage->raw_data_allocated = raw_data_allocated; storage->key = key; MonoImageStorage *other_storage = NULL; if (!mono_image_storage_trypublish (storage, &other_storage)) { mono_image_storage_close (storage); storage = other_storage; } return storage; } static MonoImage * do_mono_image_open (MonoAssemblyLoadContext *alc, const char *fname, MonoImageOpenStatus *status, gboolean care_about_cli, gboolean care_about_pecoff, gboolean metadata_only) { MonoCLIImageInfo *iinfo; MonoImage *image; MonoImageStorage *storage = mono_image_storage_open (fname); if (!storage) { if (status) *status = MONO_IMAGE_ERROR_ERRNO; return NULL; } image = g_new0 (MonoImage, 1); image->storage = storage; mono_image_init_raw_data (image, storage); if (!image->raw_data) { mono_image_storage_close (image->storage); g_free (image); if (status) *status = MONO_IMAGE_IMAGE_INVALID; return NULL; } iinfo = g_new0 (MonoCLIImageInfo, 1); image->image_info = iinfo; image->name = mono_path_resolve_symlinks (fname); image->filename = g_strdup (image->name); image->metadata_only = metadata_only; image->ref_count = 1; image->alc = alc; return do_mono_image_load (image, status, care_about_cli, care_about_pecoff); } /** * mono_image_loaded_full: * \param name path or assembly name of the image to load * \param refonly Check with respect to reflection-only loads? * * This routine verifies that the given image is loaded. * It checks either reflection-only loads only, or normal loads only, as specified by parameter. * * \returns the loaded \c MonoImage, or NULL on failure. */ MonoImage * mono_image_loaded_full (const char *name, gboolean refonly) { if (refonly) return NULL; MonoImage *result; MONO_ENTER_GC_UNSAFE; result = mono_image_loaded_internal (mono_alc_get_default (), name); MONO_EXIT_GC_UNSAFE; return result; } /** * mono_image_loaded_internal: * \param alc The AssemblyLoadContext that should be checked * \param name path or assembly name of the image to load * \param refonly Check with respect to reflection-only loads? * * This routine verifies that the given image is loaded. * It checks either reflection-only loads only, or normal loads only, as specified by parameter. * * \returns the loaded \c MonoImage, or NULL on failure. */ MonoImage * mono_image_loaded_internal (MonoAssemblyLoadContext *alc, const char *name) { MonoLoadedImages *li = mono_alc_get_loaded_images (alc); MonoImage *res; mono_images_lock (); res = (MonoImage *)g_hash_table_lookup (mono_loaded_images_get_hash (li), name); if (!res) res = (MonoImage *)g_hash_table_lookup (mono_loaded_images_get_by_name_hash (li), name); mono_images_unlock (); return res; } /** * mono_image_loaded: * \param name path or assembly name of the image to load * This routine verifies that the given image is loaded. Reflection-only loads do not count. * \returns the loaded \c MonoImage, or NULL on failure. */ MonoImage * mono_image_loaded (const char *name) { MonoImage *result; MONO_ENTER_GC_UNSAFE; result = mono_image_loaded_internal (mono_alc_get_default (), name); MONO_EXIT_GC_UNSAFE; return result; } typedef struct { MonoImage *res; const char* guid; } GuidData; static void find_by_guid (gpointer key, gpointer val, gpointer user_data) { GuidData *data = (GuidData *)user_data; MonoImage *image; if (data->res) return; image = (MonoImage *)val; if (strcmp (data->guid, mono_image_get_guid (image)) == 0) data->res = image; } static MonoImage * mono_image_loaded_by_guid_internal (const char *guid, gboolean refonly); /** * mono_image_loaded_by_guid_full: * * Looks only in the global loaded images hash, will miss assemblies loaded * into an AssemblyLoadContext. */ MonoImage * mono_image_loaded_by_guid_full (const char *guid, gboolean refonly) { return mono_image_loaded_by_guid_internal (guid, refonly); } /** * mono_image_loaded_by_guid_internal: * * Do not use. Looks only in the global loaded images hash, will miss Assembly * Load Contexts. */ static MonoImage * mono_image_loaded_by_guid_internal (const char *guid, gboolean refonly) { /* TODO: Maybe implement this for netcore by searching only the default ALC of the current domain */ return NULL; } /** * mono_image_loaded_by_guid: * * Looks only in the global loaded images hash, will miss assemblies loaded * into an AssemblyLoadContext. */ MonoImage * mono_image_loaded_by_guid (const char *guid) { return mono_image_loaded_by_guid_internal (guid, FALSE); } static MonoImage * register_image (MonoLoadedImages *li, MonoImage *image) { MonoImage *image2; char *name = image->name; GHashTable *loaded_images = mono_loaded_images_get_hash (li); mono_images_lock (); image2 = (MonoImage *)g_hash_table_lookup (loaded_images, name); if (image2) { /* Somebody else beat us to it */ mono_image_addref (image2); mono_images_unlock (); mono_image_close (image); return image2; } GHashTable *loaded_images_by_name = mono_loaded_images_get_by_name_hash (li); g_hash_table_insert (loaded_images, name, image); if (image->assembly_name && (g_hash_table_lookup (loaded_images_by_name, image->assembly_name) == NULL)) g_hash_table_insert (loaded_images_by_name, (char *) image->assembly_name, image); mono_images_unlock (); return image; } MonoImage * mono_image_open_from_data_internal (MonoAssemblyLoadContext *alc, char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status, gboolean metadata_only, const char *name, const char *filename) { MonoCLIImageInfo *iinfo; MonoImage *image; char *datac; if (!data || !data_len) { if (status) *status = MONO_IMAGE_IMAGE_INVALID; return NULL; } datac = data; if (need_copy) { datac = (char *)g_try_malloc (data_len); if (!datac) { if (status) *status = MONO_IMAGE_ERROR_ERRNO; return NULL; } memcpy (datac, data, data_len); } MonoImageStorage *storage = mono_image_storage_new_raw_data (datac, data_len, need_copy, filename); image = g_new0 (MonoImage, 1); image->storage = storage; mono_image_init_raw_data (image, storage); image->name = (name == NULL) ? g_strdup_printf ("data-%p", datac) : g_strdup (name); image->filename = filename ? g_strdup (filename) : NULL; iinfo = g_new0 (MonoCLIImageInfo, 1); image->image_info = iinfo; image->metadata_only = metadata_only; image->ref_count = 1; image->alc = alc; image = do_mono_image_load (image, status, TRUE, TRUE); if (image == NULL) return NULL; return register_image (mono_alc_get_loaded_images (alc), image); } MonoImage * mono_image_open_from_data_alc (MonoAssemblyLoadContextGCHandle alc_gchandle, char *data, uint32_t data_len, mono_bool need_copy, MonoImageOpenStatus *status, const char *name) { MonoImage *result; MONO_ENTER_GC_UNSAFE; MonoAssemblyLoadContext *alc = mono_alc_from_gchandle (alc_gchandle); result = mono_image_open_from_data_internal (alc, data, data_len, need_copy, status, FALSE, name, name); MONO_EXIT_GC_UNSAFE; return result; } /** * mono_image_open_from_data_with_name: */ MonoImage * mono_image_open_from_data_with_name (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status, gboolean refonly, const char *name) { if (refonly) { if (status) { *status = MONO_IMAGE_IMAGE_INVALID; return NULL; } } MonoImage *result; MONO_ENTER_GC_UNSAFE; result = mono_image_open_from_data_internal (mono_alc_get_default (), data, data_len, need_copy, status, FALSE, name, name); MONO_EXIT_GC_UNSAFE; return result; } /** * mono_image_open_from_data_full: */ MonoImage * mono_image_open_from_data_full (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status, gboolean refonly) { if (refonly) { if (status) { *status = MONO_IMAGE_IMAGE_INVALID; return NULL; } } MonoImage *result; MONO_ENTER_GC_UNSAFE; result = mono_image_open_from_data_internal (mono_alc_get_default (), data, data_len, need_copy, status, FALSE, NULL, NULL); MONO_EXIT_GC_UNSAFE; return result; } /** * mono_image_open_from_data: */ MonoImage * mono_image_open_from_data (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status) { MonoImage *result; MONO_ENTER_GC_UNSAFE; result = mono_image_open_from_data_internal (mono_alc_get_default (), data, data_len, need_copy, status, FALSE, NULL, NULL); MONO_EXIT_GC_UNSAFE; return result; } #ifdef HOST_WIN32 static MonoImageStorage * mono_image_storage_open_from_module_handle (HMODULE module_handle, const char *fname, gboolean has_entry_point) { char *key = g_strdup (fname); MonoImageStorage *published_storage = NULL; if (mono_image_storage_tryaddref (key, &published_storage)) { g_free (key); return published_storage; } MonoImageStorage *storage = g_new0 (MonoImageStorage, 1); mono_refcount_init (storage, mono_image_storage_dtor); storage->raw_data = (char*) module_handle; storage->is_module_handle = TRUE; storage->has_entry_point = has_entry_point; storage->key = key; MonoImageStorage *other_storage = NULL; if (!mono_image_storage_trypublish (storage, &other_storage)) { mono_image_storage_close (storage); storage = other_storage; } return storage; } /* fname is not duplicated. */ MonoImage* mono_image_open_from_module_handle (MonoAssemblyLoadContext *alc, HMODULE module_handle, char* fname, gboolean has_entry_point, MonoImageOpenStatus* status) { MonoImage* image; MonoCLIImageInfo* iinfo; MonoImageStorage *storage = mono_image_storage_open_from_module_handle (module_handle, fname, has_entry_point); image = g_new0 (MonoImage, 1); image->storage = storage; mono_image_init_raw_data (image, storage); iinfo = g_new0 (MonoCLIImageInfo, 1); image->image_info = iinfo; image->name = fname; image->filename = g_strdup (image->name); image->ref_count = has_entry_point ? 0 : 1; image->alc = alc; image = do_mono_image_load (image, status, TRUE, TRUE); if (image == NULL) return NULL; return register_image (mono_alc_get_loaded_images (alc), image); } #endif /** * mono_image_open_full: */ MonoImage * mono_image_open_full (const char *fname, MonoImageOpenStatus *status, gboolean refonly) { if (refonly) { if (status) *status = MONO_IMAGE_IMAGE_INVALID; return NULL; } return mono_image_open_a_lot (mono_alc_get_default (), fname, status); } static MonoImage * mono_image_open_a_lot_parameterized (MonoLoadedImages *li, MonoAssemblyLoadContext *alc, const char *fname, MonoImageOpenStatus *status) { MonoImage *image; GHashTable *loaded_images = mono_loaded_images_get_hash (li); char *absfname; g_return_val_if_fail (fname != NULL, NULL); #ifdef HOST_WIN32 // Win32 path: If we are running with mixed-mode assemblies enabled (ie have loaded mscoree.dll), // then assemblies need to be loaded with LoadLibrary: if (coree_module_handle) { HMODULE module_handle; gunichar2 *fname_utf16; DWORD last_error; absfname = mono_path_resolve_symlinks (fname); fname_utf16 = NULL; /* There is little overhead because the OS loader lock is held by LoadLibrary. */ mono_images_lock (); image = (MonoImage*)g_hash_table_lookup (loaded_images, absfname); if (image) { // Image already loaded g_assert (m_image_is_module_handle (image)); if (m_image_has_entry_point (image) && image->ref_count == 0) { /* Increment reference count on images loaded outside of the runtime. */ fname_utf16 = g_utf8_to_utf16 (absfname, -1, NULL, NULL, NULL); /* The image is already loaded because _CorDllMain removes images from the hash. */ module_handle = LoadLibrary (fname_utf16); g_assert (module_handle == (HMODULE) image->raw_data); } mono_image_addref (image); mono_images_unlock (); if (fname_utf16) g_free (fname_utf16); g_free (absfname); return image; } // Image not loaded, load it now fname_utf16 = g_utf8_to_utf16 (absfname, -1, NULL, NULL, NULL); module_handle = MonoLoadImage (fname_utf16); if (status && module_handle == NULL) last_error = mono_w32error_get_last (); /* mono_image_open_from_module_handle is called by _CorDllMain. */ image = (MonoImage*)g_hash_table_lookup (loaded_images, absfname); if (image) mono_image_addref (image); mono_images_unlock (); g_free (fname_utf16); if (module_handle == NULL) { g_assert (!image); g_free (absfname); if (status) { if (last_error == ERROR_BAD_EXE_FORMAT || last_error == STATUS_INVALID_IMAGE_FORMAT) { if (status) *status = MONO_IMAGE_IMAGE_INVALID; } else { if (last_error == ERROR_FILE_NOT_FOUND || last_error == ERROR_PATH_NOT_FOUND) mono_set_errno (ENOENT); else mono_set_errno (0); } } return NULL; } if (image) { g_assert (m_image_is_module_handle (image)); g_assert (m_image_has_entry_point (image)); g_free (absfname); return image; } return mono_image_open_from_module_handle (alc, module_handle, absfname, FALSE, status); } #endif absfname = mono_path_resolve_symlinks (fname); /* * The easiest solution would be to do all the loading inside the mutex, * but that would lead to scalability problems. So we let the loading * happen outside the mutex, and if multiple threads happen to load * the same image, we discard all but the first copy. */ mono_images_lock (); image = (MonoImage *)g_hash_table_lookup (loaded_images, absfname); g_free (absfname); if (image) { // Image already loaded mono_image_addref (image); mono_images_unlock (); return image; } mono_images_unlock (); // Image not loaded, load it now image = do_mono_image_open (alc, fname, status, TRUE, TRUE, FALSE); if (image == NULL) return NULL; return register_image (li, image); } MonoImage * mono_image_open_a_lot (MonoAssemblyLoadContext *alc, const char *fname, MonoImageOpenStatus *status) { MonoLoadedImages *li = mono_alc_get_loaded_images (alc); return mono_image_open_a_lot_parameterized (li, alc, fname, status); } /** * mono_image_open: * \param fname filename that points to the module we want to open * \param status An error condition is returned in this field * \returns An open image of type \c MonoImage or NULL on error. * The caller holds a temporary reference to the returned image which should be cleared * when no longer needed by calling \c mono_image_close. * if NULL, then check the value of \p status for details on the error */ MonoImage * mono_image_open (const char *fname, MonoImageOpenStatus *status) { return mono_image_open_a_lot (mono_alc_get_default (), fname, status); } /** * mono_pe_file_open: * \param fname filename that points to the module we want to open * \param status An error condition is returned in this field * \returns An open image of type \c MonoImage or NULL on error. if * NULL, then check the value of \p status for details on the error. * This variant for \c mono_image_open DOES NOT SET UP CLI METADATA. * It's just a PE file loader, used for \c FileVersionInfo. It also does * not use the image cache. */ MonoImage * mono_pe_file_open (const char *fname, MonoImageOpenStatus *status) { g_return_val_if_fail (fname != NULL, NULL); return do_mono_image_open (mono_alc_get_default (), fname, status, FALSE, TRUE, FALSE); } /** * mono_image_open_raw * \param fname filename that points to the module we want to open * \param status An error condition is returned in this field * \returns an image without loading neither pe or cli data. * Use mono_image_load_pe_data and mono_image_load_cli_data to load them. */ MonoImage * mono_image_open_raw (MonoAssemblyLoadContext *alc, const char *fname, MonoImageOpenStatus *status) { g_return_val_if_fail (fname != NULL, NULL); return do_mono_image_open (alc, fname, status, FALSE, FALSE, FALSE); } /* * mono_image_open_metadata_only: * * Open an image which contains metadata only without a PE header. */ MonoImage * mono_image_open_metadata_only (MonoAssemblyLoadContext *alc, const char *fname, MonoImageOpenStatus *status) { return do_mono_image_open (alc, fname, status, TRUE, TRUE, TRUE); } /** * mono_image_fixup_vtable: */ void mono_image_fixup_vtable (MonoImage *image) { #ifdef HOST_WIN32 MonoCLIImageInfo *iinfo; MonoPEDirEntry *de; MonoVTableFixup *vtfixup; int count; gpointer slot; guint16 slot_type; int slot_count; g_assert (m_image_is_module_handle (image)); iinfo = image->image_info; de = &iinfo->cli_cli_header.ch_vtable_fixups; if (!de->rva || !de->size) return; vtfixup = (MonoVTableFixup*) mono_image_rva_map (image, de->rva); if (!vtfixup) return; count = de->size / sizeof (MonoVTableFixup); while (count--) { if (!vtfixup->rva || !vtfixup->count) continue; slot = mono_image_rva_map (image, vtfixup->rva); g_assert (slot); slot_type = vtfixup->type; slot_count = vtfixup->count; if (slot_type & VTFIXUP_TYPE_32BIT) while (slot_count--) { *((guint32*) slot) = (guint32)(gsize)mono_marshal_get_vtfixup_ftnptr (image, *((guint32*) slot), slot_type); slot = ((guint32*) slot) + 1; } else if (slot_type & VTFIXUP_TYPE_64BIT) while (slot_count--) { *((guint64*) slot) = (guint64) mono_marshal_get_vtfixup_ftnptr (image, *((guint64*) slot), slot_type); slot = ((guint32*) slot) + 1; } else g_assert_not_reached(); vtfixup++; } #else g_assert_not_reached(); #endif } static void free_hash_table (gpointer key, gpointer val, gpointer user_data) { g_hash_table_destroy ((GHashTable*)val); } /* static void free_mr_signatures (gpointer key, gpointer val, gpointer user_data) { mono_metadata_free_method_signature ((MonoMethodSignature*)val); } */ static void free_array_cache_entry (gpointer key, gpointer val, gpointer user_data) { g_slist_free ((GSList*)val); } /** * mono_image_addref: * \param image The image file we wish to add a reference to * Increases the reference count of an image. */ void mono_image_addref (MonoImage *image) { mono_atomic_inc_i32 (&image->ref_count); } void mono_dynamic_stream_reset (MonoDynamicStream* stream) { stream->alloc_size = stream->index = stream->offset = 0; g_free (stream->data); stream->data = NULL; if (stream->hash) { g_hash_table_destroy (stream->hash); stream->hash = NULL; } } static void free_hash (GHashTable *hash) { if (hash) g_hash_table_destroy (hash); } void mono_wrapper_caches_free (MonoWrapperCaches *cache) { free_hash (cache->delegate_invoke_cache); free_hash (cache->delegate_begin_invoke_cache); free_hash (cache->delegate_end_invoke_cache); free_hash (cache->delegate_bound_static_invoke_cache); free_hash (cache->runtime_invoke_signature_cache); free_hash (cache->delegate_abstract_invoke_cache); free_hash (cache->runtime_invoke_method_cache); free_hash (cache->managed_wrapper_cache); free_hash (cache->native_wrapper_cache); free_hash (cache->native_wrapper_aot_cache); free_hash (cache->native_wrapper_check_cache); free_hash (cache->native_wrapper_aot_check_cache); free_hash (cache->native_func_wrapper_aot_cache); free_hash (cache->native_func_wrapper_indirect_cache); free_hash (cache->synchronized_cache); free_hash (cache->unbox_wrapper_cache); free_hash (cache->cominterop_invoke_cache); free_hash (cache->cominterop_wrapper_cache); free_hash (cache->thunk_invoke_cache); } static void mono_image_close_except_pools_all (MonoImage**images, int image_count) { for (int i = 0; i < image_count; ++i) { if (images [i]) { if (!mono_image_close_except_pools (images [i])) images [i] = NULL; } } } /* * Returns whether mono_image_close_finish() must be called as well. * We must unload images in two steps because clearing the domain in * SGen requires the class metadata to be intact, but we need to free * the mono_g_hash_tables in case a collection occurs during domain * unloading and the roots would trip up the GC. */ gboolean mono_image_close_except_pools (MonoImage *image) { int i; g_return_val_if_fail (image != NULL, FALSE); if (!mono_loaded_images_remove_image (image)) return FALSE; #ifdef HOST_WIN32 if (m_image_is_module_handle (image) && m_image_has_entry_point (image)) { mono_images_lock (); if (image->ref_count == 0) { /* Image will be closed by _CorDllMain. */ FreeLibrary ((HMODULE) image->raw_data); mono_images_unlock (); return FALSE; } mono_images_unlock (); } #endif MONO_PROFILER_RAISE (image_unloading, (image)); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_ASSEMBLY, "Unloading image %s [%p].", image->name, image); mono_image_invoke_unload_hook (image); mono_metadata_update_cleanup_on_close (image); /* * The caches inside a MonoImage might refer to metadata which is stored in referenced * assemblies, so we can't release these references in mono_assembly_close () since the * MonoImage might outlive its associated MonoAssembly. */ if (image->references && !image_is_dynamic (image)) { for (i = 0; i < image->nreferences; i++) { if (image->references [i] && image->references [i] != REFERENCE_MISSING) { if (!mono_assembly_close_except_image_pools (image->references [i])) image->references [i] = NULL; } } } else { if (image->references) { g_free (image->references); image->references = NULL; } } /* a MonoDynamicImage doesn't have any storage */ g_assert (image_is_dynamic (image) || image->storage != NULL); if (image->storage && m_image_is_raw_data_allocated (image)) { /* FIXME: do we need this? (image is disposed anyway) */ /* image->raw_metadata and cli_sections might lie inside image->raw_data */ MonoCLIImageInfo *ii = image->image_info; if ((image->raw_metadata > image->raw_data) && (image->raw_metadata <= (image->raw_data + image->raw_data_len))) image->raw_metadata = NULL; for (i = 0; i < ii->cli_section_count; i++) if (((char*)(ii->cli_sections [i]) > image->raw_data) && ((char*)(ii->cli_sections [i]) <= ((char*)image->raw_data + image->raw_data_len))) ii->cli_sections [i] = NULL; } if (image->storage) mono_image_storage_close (image->storage); if (debug_assembly_unload) { char *old_name = image->name; image->name = g_strdup_printf ("%s - UNLOADED", old_name); g_free (old_name); g_free (image->filename); image->filename = NULL; } else { g_free (image->name); g_free (image->filename); g_free (image->guid); g_free (image->version); } if (image->method_cache) g_hash_table_destroy (image->method_cache); if (image->methodref_cache) g_hash_table_destroy (image->methodref_cache); mono_internal_hash_table_destroy (&image->class_cache); mono_conc_hashtable_destroy (image->field_cache); if (image->array_cache) { g_hash_table_foreach (image->array_cache, free_array_cache_entry, NULL); g_hash_table_destroy (image->array_cache); } if (image->szarray_cache) g_hash_table_destroy (image->szarray_cache); if (image->ptr_cache) g_hash_table_destroy (image->ptr_cache); if (image->name_cache) { g_hash_table_foreach (image->name_cache, free_hash_table, NULL); g_hash_table_destroy (image->name_cache); } free_hash (image->icall_wrapper_cache); if (image->var_gparam_cache) mono_conc_hashtable_destroy (image->var_gparam_cache); if (image->mvar_gparam_cache) mono_conc_hashtable_destroy (image->mvar_gparam_cache); free_hash (image->wrapper_param_names); free_hash (image->native_func_wrapper_cache); mono_conc_hashtable_destroy (image->typespec_cache); #ifdef ENABLE_WEAK_ATTR free_hash (image->weak_field_indexes); #endif mono_wrapper_caches_free (&image->wrapper_caches); /* The ownership of signatures is not well defined */ g_hash_table_destroy (image->memberref_signatures); g_hash_table_destroy (image->method_signatures); if (image->rgctx_template_hash) g_hash_table_destroy (image->rgctx_template_hash); if (image->property_hash) mono_property_hash_destroy (image->property_hash); /* reflection_info_unregister_classes is only required by dynamic images, which will not be properly cleared during shutdown as we don't perform regular appdomain unload for the root one. */ g_assert (!image->reflection_info_unregister_classes || mono_runtime_is_shutting_down ()); image->reflection_info_unregister_classes = NULL; if (image->interface_bitset) { mono_unload_interface_ids (image->interface_bitset); mono_bitset_free (image->interface_bitset); } if (image->image_info){ MonoCLIImageInfo *ii = image->image_info; g_free (ii->cli_section_tables); g_free (ii->cli_sections); g_free (image->image_info); } mono_image_close_except_pools_all (image->files, image->file_count); mono_image_close_except_pools_all (image->modules, image->module_count); g_free (image->modules_loaded); if (image->has_updates) mono_metadata_update_image_close_except_pools_all (image); mono_os_mutex_destroy (&image->szarray_cache_lock); mono_os_mutex_destroy (&image->lock); /*g_print ("destroy image %p (dynamic: %d)\n", image, image->dynamic);*/ if (image_is_dynamic (image)) { /* Dynamic images are GC_MALLOCed */ g_free ((char*)image->module_name); mono_dynamic_image_free ((MonoDynamicImage*)image); } MONO_PROFILER_RAISE (image_unloaded, (image)); return TRUE; } static void mono_image_close_all (MonoImage**images, int image_count) { for (int i = 0; i < image_count; ++i) { if (images [i]) mono_image_close_finish (images [i]); } if (images) g_free (images); } void mono_image_close_finish (MonoImage *image) { int i; if (image->references && !image_is_dynamic (image)) { for (i = 0; i < image->nreferences; i++) { if (image->references [i] && image->references [i] != REFERENCE_MISSING) mono_assembly_close_finish (image->references [i]); } g_free (image->references); image->references = NULL; } mono_image_close_all (image->files, image->file_count); mono_image_close_all (image->modules, image->module_count); mono_metadata_update_image_close_all (image); #ifndef DISABLE_PERFCOUNTERS /* FIXME: use an explicit subtraction method as soon as it's available */ mono_atomic_fetch_add_i32 (&mono_perfcounters->loader_bytes, -1 * mono_mempool_get_allocated (image->mempool)); #endif if (!image_is_dynamic (image)) { if (debug_assembly_unload) mono_mempool_invalidate (image->mempool); else { mono_mempool_destroy (image->mempool); g_free (image); } } else { if (debug_assembly_unload) mono_mempool_invalidate (image->mempool); else { mono_mempool_destroy (image->mempool); mono_dynamic_image_free_image ((MonoDynamicImage*)image); } } } /** * mono_image_close: * \param image The image file we wish to close * Closes an image file, deallocates all memory consumed and * unmaps all possible sections of the file */ void mono_image_close (MonoImage *image) { if (mono_image_close_except_pools (image)) mono_image_close_finish (image); } /** * mono_image_strerror: * \param status an code indicating the result from a recent operation * \returns a string describing the error */ const char * mono_image_strerror (MonoImageOpenStatus status) { switch (status){ case MONO_IMAGE_OK: return "success"; case MONO_IMAGE_ERROR_ERRNO: return strerror (errno); case MONO_IMAGE_IMAGE_INVALID: return "File does not contain a valid CIL image"; case MONO_IMAGE_MISSING_ASSEMBLYREF: return "An assembly was referenced, but could not be found"; } return "Internal error"; } static gpointer mono_image_walk_resource_tree (MonoCLIImageInfo *info, guint32 res_id, guint32 lang_id, gunichar2 *name, MonoPEResourceDirEntry *entry, MonoPEResourceDir *root, guint32 level) { gboolean is_string, is_dir; guint32 name_offset, dir_offset; /* Level 0 holds a directory entry for each type of resource * (identified by ID or name). * * Level 1 holds a directory entry for each named resource * item, and each "anonymous" item of a particular type of * resource. * * Level 2 holds a directory entry for each language pointing to * the actual data. */ is_string = MONO_PE_RES_DIR_ENTRY_NAME_IS_STRING (*entry); name_offset = MONO_PE_RES_DIR_ENTRY_NAME_OFFSET (*entry); is_dir = MONO_PE_RES_DIR_ENTRY_IS_DIR (*entry); dir_offset = MONO_PE_RES_DIR_ENTRY_DIR_OFFSET (*entry); if(level==0) { if (is_string) return NULL; } else if (level==1) { if (res_id != name_offset) return NULL; #if 0 if(name!=NULL && is_string==TRUE && name!=lookup (name_offset)) { return(NULL); } #endif } else if (level==2) { if (is_string || (lang_id != 0 && name_offset != lang_id)) return NULL; } else { g_assert_not_reached (); } if (is_dir) { MonoPEResourceDir *res_dir=(MonoPEResourceDir *)(((char *)root)+dir_offset); MonoPEResourceDirEntry *sub_entries=(MonoPEResourceDirEntry *)(res_dir+1); guint32 entries, i; entries = GUINT16_FROM_LE (res_dir->res_named_entries) + GUINT16_FROM_LE (res_dir->res_id_entries); for(i=0; i<entries; i++) { MonoPEResourceDirEntry *sub_entry=&sub_entries[i]; gpointer ret; ret=mono_image_walk_resource_tree (info, res_id, lang_id, name, sub_entry, root, level+1); if(ret!=NULL) { return(ret); } } return(NULL); } else { MonoPEResourceDataEntry *data_entry=(MonoPEResourceDataEntry *)((char *)(root)+dir_offset); MonoPEResourceDataEntry *res; res = g_new0 (MonoPEResourceDataEntry, 1); res->rde_data_offset = GUINT32_TO_LE (data_entry->rde_data_offset); res->rde_size = GUINT32_TO_LE (data_entry->rde_size); res->rde_codepage = GUINT32_TO_LE (data_entry->rde_codepage); res->rde_reserved = GUINT32_TO_LE (data_entry->rde_reserved); return (res); } } /** * mono_image_lookup_resource: * \param image the image to look up the resource in * \param res_id A \c MONO_PE_RESOURCE_ID_ that represents the resource ID to lookup. * \param lang_id The language id. * \param name the resource name to lookup. * \returns NULL if not found, otherwise a pointer to the in-memory representation * of the given resource. The caller should free it using \c g_free when no longer * needed. */ gpointer mono_image_lookup_resource (MonoImage *image, guint32 res_id, guint32 lang_id, gunichar2 *name) { MonoCLIImageInfo *info; MonoDotNetHeader *header; MonoPEDatadir *datadir; MonoPEDirEntry *rsrc; MonoPEResourceDir *resource_dir; MonoPEResourceDirEntry *res_entries; guint32 entries, i; if(image==NULL) { return(NULL); } mono_image_ensure_section_idx (image, MONO_SECTION_RSRC); info = (MonoCLIImageInfo *)image->image_info; if(info==NULL) { return(NULL); } header=&info->cli_header; if(header==NULL) { return(NULL); } datadir=&header->datadir; if(datadir==NULL) { return(NULL); } rsrc=&datadir->pe_resource_table; if(rsrc==NULL) { return(NULL); } resource_dir=(MonoPEResourceDir *)mono_image_rva_map (image, rsrc->rva); if(resource_dir==NULL) { return(NULL); } entries = GUINT16_FROM_LE (resource_dir->res_named_entries) + GUINT16_FROM_LE (resource_dir->res_id_entries); res_entries=(MonoPEResourceDirEntry *)(resource_dir+1); for(i=0; i<entries; i++) { MonoPEResourceDirEntry *entry=&res_entries[i]; gpointer ret; ret=mono_image_walk_resource_tree (info, res_id, lang_id, name, entry, resource_dir, 0); if(ret!=NULL) { return(ret); } } return(NULL); } /** * mono_image_get_entry_point: * \param image the image where the entry point will be looked up. * Use this routine to determine the metadata token for method that * has been flagged as the entry point. * \returns the token for the entry point method in the image */ guint32 mono_image_get_entry_point (MonoImage *image) { return image->image_info->cli_cli_header.ch_entry_point; } /** * mono_image_get_resource: * \param image the image where the resource will be looked up. * \param offset The offset to add to the resource * \param size a pointer to an int where the size of the resource will be stored * * This is a low-level routine that fetches a resource from the * metadata that starts at a given \p offset. The \p size parameter is * filled with the data field as encoded in the metadata. * * \returns the pointer to the resource whose offset is \p offset. */ const char* mono_image_get_resource (MonoImage *image, guint32 offset, guint32 *size) { MonoCLIImageInfo *iinfo = image->image_info; MonoCLIHeader *ch = &iinfo->cli_cli_header; const char* data; if (!ch->ch_resources.rva || offset + 4 > ch->ch_resources.size) return NULL; data = mono_image_rva_map (image, ch->ch_resources.rva); if (!data) return NULL; data += offset; if (size) *size = read32 (data); data += 4; return data; } // Returning NULL with no error set will be interpeted as "not found" MonoImage* mono_image_load_file_for_image_checked (MonoImage *image, int fileidx, MonoError *error) { char *base_dir, *name; MonoImage *res; MonoTableInfo *t = &image->tables [MONO_TABLE_FILE]; const char *fname; guint32 fname_id; error_init (error); if (fileidx < 1 || fileidx > table_info_get_rows (t)) return NULL; mono_image_lock (image); if (image->files && image->files [fileidx - 1]) { mono_image_unlock (image); return image->files [fileidx - 1]; } mono_image_unlock (image); fname_id = mono_metadata_decode_row_col (t, fileidx - 1, MONO_FILE_NAME); fname = mono_metadata_string_heap (image, fname_id); base_dir = g_path_get_dirname (image->name); name = g_build_filename (base_dir, fname, (const char*)NULL); res = mono_image_open (name, NULL); if (!res) goto done; mono_image_lock (image); if (image->files && image->files [fileidx - 1]) { MonoImage *old = res; res = image->files [fileidx - 1]; mono_image_unlock (image); mono_image_close (old); } else { int i; /* g_print ("loaded file %s from %s (%p)\n", name, image->name, image->assembly); */ if (!assign_assembly_parent_for_netmodule (res, image, error)) { mono_image_unlock (image); mono_image_close (res); return NULL; } for (i = 0; i < res->module_count; ++i) { if (res->modules [i] && !res->modules [i]->assembly) res->modules [i]->assembly = image->assembly; } if (!image->files) { int n = table_info_get_rows (t); image->files = g_new0 (MonoImage*, n); image->file_count = n; } image->files [fileidx - 1] = res; mono_image_unlock (image); /* vtable fixup can't happen with the image lock held */ #ifdef HOST_WIN32 if (m_image_is_module_handle (res)) mono_image_fixup_vtable (res); #endif } done: g_free (name); g_free (base_dir); return res; } /** * mono_image_load_file_for_image: */ MonoImage* mono_image_load_file_for_image (MonoImage *image, int fileidx) { ERROR_DECL (error); MonoImage *result = mono_image_load_file_for_image_checked (image, fileidx, error); mono_error_assert_ok (error); return result; } /** * mono_image_get_strong_name: * \param image a MonoImage * \param size a \c guint32 pointer, or NULL. * * If the image has a strong name, and \p size is not NULL, the value * pointed to by size will have the size of the strong name. * * \returns NULL if the image does not have a strong name, or a * pointer to the public key. */ const char* mono_image_get_strong_name (MonoImage *image, guint32 *size) { MonoCLIImageInfo *iinfo = image->image_info; MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name; const char* data; if (!de->size || !de->rva) return NULL; data = mono_image_rva_map (image, de->rva); if (!data) return NULL; if (size) *size = de->size; return data; } /** * mono_image_strong_name_position: * \param image a \c MonoImage * \param size a \c guint32 pointer, or NULL. * * If the image has a strong name, and \p size is not NULL, the value * pointed to by size will have the size of the strong name. * * \returns the position within the image file where the strong name * is stored. */ guint32 mono_image_strong_name_position (MonoImage *image, guint32 *size) { MonoCLIImageInfo *iinfo = image->image_info; MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name; guint32 pos; if (size) *size = de->size; if (!de->size || !de->rva) return 0; pos = mono_cli_rva_image_map (image, de->rva); return pos == INVALID_ADDRESS ? 0 : pos; } /** * mono_image_get_public_key: * \param image a \c MonoImage * \param size a \c guint32 pointer, or NULL. * * This is used to obtain the public key in the \p image. * * If the image has a public key, and \p size is not NULL, the value * pointed to by size will have the size of the public key. * * \returns NULL if the image does not have a public key, or a pointer * to the public key. */ const char* mono_image_get_public_key (MonoImage *image, guint32 *size) { const char *pubkey; guint32 len, tok; if (image_is_dynamic (image)) { if (size) *size = ((MonoDynamicImage*)image)->public_key_len; return (char*)((MonoDynamicImage*)image)->public_key; } if (table_info_get_rows (&image->tables [MONO_TABLE_ASSEMBLY]) != 1) return NULL; tok = mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY], 0, MONO_ASSEMBLY_PUBLIC_KEY); if (!tok) return NULL; pubkey = mono_metadata_blob_heap (image, tok); len = mono_metadata_decode_blob_size (pubkey, &pubkey); if (size) *size = len; return pubkey; } /** * mono_image_get_name: * \param name a \c MonoImage * \returns the name of the assembly. */ const char* mono_image_get_name (MonoImage *image) { return image->assembly_name; } /** * mono_image_get_filename: * \param image a \c MonoImage * Used to get the filename that hold the actual \c MonoImage * \returns the filename. */ const char* mono_image_get_filename (MonoImage *image) { return image->name; } /** * mono_image_get_guid: */ const char* mono_image_get_guid (MonoImage *image) { return image->guid; } /** * mono_image_get_table_info: */ const MonoTableInfo* mono_image_get_table_info (MonoImage *image, int table_id) { if (table_id < 0 || table_id >= MONO_TABLE_NUM) return NULL; return &image->tables [table_id]; } /** * mono_image_get_table_rows: */ int mono_image_get_table_rows (MonoImage *image, int table_id) { if (table_id < 0 || table_id >= MONO_TABLE_NUM) return 0; return table_info_get_rows (&image->tables [table_id]); } /** * mono_table_info_get_rows: */ int mono_table_info_get_rows (const MonoTableInfo *table) { return table_info_get_rows (table); } /** * mono_image_get_assembly: * \param image the \c MonoImage . * Use this routine to get the assembly that owns this image. * \returns the assembly that holds this image. */ MonoAssembly* mono_image_get_assembly (MonoImage *image) { return image->assembly; } /** * mono_image_is_dynamic: * \param image the \c MonoImage * * Determines if the given image was created dynamically through the * \c System.Reflection.Emit API * \returns TRUE if the image was created dynamically, FALSE if not. */ gboolean mono_image_is_dynamic (MonoImage *image) { return image_is_dynamic (image); } /** * mono_image_has_authenticode_entry: * \param image the \c MonoImage * Use this routine to determine if the image has a Authenticode * Certificate Table. * \returns TRUE if the image contains an authenticode entry in the PE * directory. */ gboolean mono_image_has_authenticode_entry (MonoImage *image) { MonoCLIImageInfo *iinfo = image->image_info; MonoDotNetHeader *header = &iinfo->cli_header; if (!header) return FALSE; MonoPEDirEntry *de = &header->datadir.pe_certificate_table; // the Authenticode "pre" (non ASN.1) header is 8 bytes long return ((de->rva != 0) && (de->size > 8)); } gpointer mono_image_alloc (MonoImage *image, guint size) { gpointer res; #ifndef DISABLE_PERFCOUNTERS mono_atomic_fetch_add_i32 (&mono_perfcounters->loader_bytes, size); #endif mono_image_lock (image); res = mono_mempool_alloc (image->mempool, size); mono_image_unlock (image); return res; } gpointer mono_image_alloc0 (MonoImage *image, guint size) { gpointer res; #ifndef DISABLE_PERFCOUNTERS mono_atomic_fetch_add_i32 (&mono_perfcounters->loader_bytes, size); #endif mono_image_lock (image); res = mono_mempool_alloc0 (image->mempool, size); mono_image_unlock (image); return res; } char* mono_image_strdup (MonoImage *image, const char *s) { char *res; #ifndef DISABLE_PERFCOUNTERS mono_atomic_fetch_add_i32 (&mono_perfcounters->loader_bytes, (gint32)strlen (s)); #endif mono_image_lock (image); res = mono_mempool_strdup (image->mempool, s); mono_image_unlock (image); return res; } char* mono_image_strdup_vprintf (MonoImage *image, const char *format, va_list args) { char *buf; mono_image_lock (image); buf = mono_mempool_strdup_vprintf (image->mempool, format, args); mono_image_unlock (image); #ifndef DISABLE_PERFCOUNTERS mono_atomic_fetch_add_i32 (&mono_perfcounters->loader_bytes, (gint32)strlen (buf)); #endif return buf; } char* mono_image_strdup_printf (MonoImage *image, const char *format, ...) { char *buf; va_list args; va_start (args, format); buf = mono_image_strdup_vprintf (image, format, args); va_end (args); return buf; } GList* mono_g_list_prepend_image (MonoImage *image, GList *list, gpointer data) { GList *new_list; new_list = (GList *)mono_image_alloc (image, sizeof (GList)); new_list->data = data; new_list->prev = list ? list->prev : NULL; new_list->next = list; if (new_list->prev) new_list->prev->next = new_list; if (list) list->prev = new_list; return new_list; } GSList* mono_g_slist_append_image (MonoImage *image, GSList *list, gpointer data) { GSList *new_list; new_list = (GSList *)mono_image_alloc (image, sizeof (GSList)); new_list->data = data; new_list->next = NULL; return g_slist_concat (list, new_list); } void mono_image_lock (MonoImage *image) { mono_locks_os_acquire (&image->lock, ImageDataLock); } void mono_image_unlock (MonoImage *image) { mono_locks_os_release (&image->lock, ImageDataLock); } /** * mono_image_property_lookup: * Lookup a property on \p image . Used to store very rare fields of \c MonoClass and \c MonoMethod . * * LOCKING: Takes the image lock */ gpointer mono_image_property_lookup (MonoImage *image, gpointer subject, guint32 property) { gpointer res; mono_image_lock (image); res = mono_property_hash_lookup (image->property_hash, subject, property); mono_image_unlock (image); return res; } /** * mono_image_property_insert: * Insert a new property \p property with value \p value on \p subject in \p * image. Used to store very rare fields of \c MonoClass and \c MonoMethod. * * LOCKING: Takes the image lock */ void mono_image_property_insert (MonoImage *image, gpointer subject, guint32 property, gpointer value) { CHECKED_METADATA_STORE_LOCAL (image->mempool, value); mono_image_lock (image); mono_property_hash_insert (image->property_hash, subject, property, value); mono_image_unlock (image); } /** * mono_image_property_remove: * Remove all properties associated with \p subject in \p image. Used to store very rare fields of \c MonoClass and \c MonoMethod . * * LOCKING: Takes the image lock */ void mono_image_property_remove (MonoImage *image, gpointer subject) { mono_image_lock (image); mono_property_hash_remove_object (image->property_hash, subject); mono_image_unlock (image); } void mono_image_append_class_to_reflection_info_set (MonoClass *klass) { MonoImage *image = m_class_get_image (klass); g_assert (image_is_dynamic (image)); mono_image_lock (image); image->reflection_info_unregister_classes = g_slist_prepend_mempool (image->mempool, image->reflection_info_unregister_classes, klass); mono_image_unlock (image); }
/** * \file * Routines for manipulating an image stored in an * extended PE/COFF file. * * Authors: * Miguel de Icaza ([email protected]) * Paolo Molaro ([email protected]) * * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com) * Copyright 2004-2009 Novell, Inc (http://www.novell.com) * * Licensed under the MIT license. See LICENSE file in the project root for full license information. */ #include <config.h> #include <stdio.h> #include <glib.h> #include <errno.h> #include <time.h> #include <string.h> #include <mono/metadata/image.h> #include "cil-coff.h" #include "mono-endian.h" #include "tabledefs.h" #include <mono/metadata/tokentype.h> #include "metadata-internals.h" #include "metadata-update.h" #include "profiler-private.h" #include <mono/metadata/loader.h> #include "marshal.h" #include "coree.h" #include <mono/metadata/exception-internals.h> #include <mono/utils/checked-build.h> #include <mono/utils/mono-logger-internals.h> #include <mono/utils/mono-errno.h> #include <mono/utils/mono-path.h> #include <mono/utils/mono-mmap.h> #include <mono/utils/atomic.h> #include <mono/utils/mono-proclib.h> #include <mono/metadata/class-internals.h> #include <mono/metadata/assembly.h> #include <mono/metadata/object-internals.h> #include <mono/metadata/verify.h> #include <mono/metadata/image-internals.h> #include <mono/metadata/loaded-images-internals.h> #include <mono/metadata/metadata-update.h> #include <mono/metadata/debug-internals.h> #include <mono/metadata/mono-private-unstable.h> #include <sys/types.h> #include <sys/stat.h> #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #include <mono/metadata/w32error.h> #define INVALID_ADDRESS 0xffffffff // Amount initially reserved in each image's mempool. // FIXME: This number is arbitrary, a more practical number should be found #define INITIAL_IMAGE_SIZE 512 // Change the assembly set in `image` to the assembly set in `assemblyImage`. Halt if overwriting is attempted. // Can be used on modules loaded through either the "file" or "module" mechanism static gboolean assign_assembly_parent_for_netmodule (MonoImage *image, MonoImage *assemblyImage, MonoError *error) { // Assembly to assign MonoAssembly *assembly = assemblyImage->assembly; while (1) { // Assembly currently assigned MonoAssembly *assemblyOld = image->assembly; if (assemblyOld) { if (assemblyOld == assembly) return TRUE; mono_error_set_bad_image (error, assemblyImage, "Attempted to load module %s which has already been loaded by assembly %s. This is not supported in Mono.", image->name, assemblyOld->image->name); return FALSE; } gpointer result = mono_atomic_xchg_ptr((gpointer *)&image->assembly, assembly); if (result == assembly) return TRUE; } } static gboolean debug_assembly_unload = FALSE; #define mono_images_storage_lock() do { if (mutex_inited) mono_os_mutex_lock (&images_storage_mutex); } while (0) #define mono_images_storage_unlock() do { if (mutex_inited) mono_os_mutex_unlock (&images_storage_mutex); } while (0) static gboolean mutex_inited; static mono_mutex_t images_mutex; static mono_mutex_t images_storage_mutex; void mono_images_lock (void) { if (mutex_inited) mono_os_mutex_lock (&images_mutex); } void mono_images_unlock(void) { if (mutex_inited) mono_os_mutex_unlock (&images_mutex); } static MonoImage * mono_image_open_a_lot_parameterized (MonoLoadedImages *li, MonoAssemblyLoadContext *alc, const char *fname, MonoImageOpenStatus *status); /* Maps string keys to MonoImageStorage values. * * The MonoImageStorage in the hash owns the key. */ static GHashTable *images_storage_hash; static void install_pe_loader (void); typedef struct ImageUnloadHook ImageUnloadHook; struct ImageUnloadHook { MonoImageUnloadFunc func; gpointer user_data; }; static GSList *image_unload_hooks; void mono_install_image_unload_hook (MonoImageUnloadFunc func, gpointer user_data) { ImageUnloadHook *hook; g_return_if_fail (func != NULL); hook = g_new0 (ImageUnloadHook, 1); hook->func = func; hook->user_data = user_data; image_unload_hooks = g_slist_prepend (image_unload_hooks, hook); } void mono_remove_image_unload_hook (MonoImageUnloadFunc func, gpointer user_data) { GSList *l; ImageUnloadHook *hook; for (l = image_unload_hooks; l; l = l->next) { hook = (ImageUnloadHook *)l->data; if (hook->func == func && hook->user_data == user_data) { g_free (hook); image_unload_hooks = g_slist_delete_link (image_unload_hooks, l); break; } } } static void mono_image_invoke_unload_hook (MonoImage *image) { GSList *l; ImageUnloadHook *hook; for (l = image_unload_hooks; l; l = l->next) { hook = (ImageUnloadHook *)l->data; hook->func (image, hook->user_data); } } static GSList *image_loaders; void mono_install_image_loader (const MonoImageLoader *loader) { image_loaders = g_slist_prepend (image_loaders, (MonoImageLoader*)loader); } /* returns offset relative to image->raw_data */ guint32 mono_cli_rva_image_map (MonoImage *image, guint32 addr) { MonoCLIImageInfo *iinfo = image->image_info; const int top = iinfo->cli_section_count; MonoSectionTable *tables = iinfo->cli_section_tables; int i; if (image->metadata_only) return addr; for (i = 0; i < top; i++){ if ((addr >= tables->st_virtual_address) && (addr < tables->st_virtual_address + tables->st_raw_data_size)){ #ifdef HOST_WIN32 if (m_image_is_module_handle (image)) return addr; #endif return addr - tables->st_virtual_address + tables->st_raw_data_ptr; } tables++; } return INVALID_ADDRESS; } /** * mono_image_rva_map: * \param image a \c MonoImage * \param addr relative virtual address (RVA) * * This is a low-level routine used by the runtime to map relative * virtual address (RVA) into their location in memory. * * \returns the address in memory for the given RVA, or NULL if the * RVA is not valid for this image. */ char * mono_image_rva_map (MonoImage *image, guint32 addr) { MonoCLIImageInfo *iinfo = image->image_info; const int top = iinfo->cli_section_count; MonoSectionTable *tables = iinfo->cli_section_tables; int i; #ifdef HOST_WIN32 if (m_image_is_module_handle (image)) { if (addr && addr < image->raw_data_len) return image->raw_data + addr; else return NULL; } #endif for (i = 0; i < top; i++){ if ((addr >= tables->st_virtual_address) && (addr < tables->st_virtual_address + tables->st_raw_data_size)){ if (!iinfo->cli_sections [i]) { if (!mono_image_ensure_section_idx (image, i)) return NULL; } return (char*)iinfo->cli_sections [i] + (addr - tables->st_virtual_address); } tables++; } return NULL; } /** * mono_images_init: * * Initialize the global variables used by this module. */ void mono_images_init (void) { mono_os_mutex_init (&images_storage_mutex); mono_os_mutex_init_recursive (&images_mutex); images_storage_hash = g_hash_table_new (g_str_hash, g_str_equal); debug_assembly_unload = g_hasenv ("MONO_DEBUG_ASSEMBLY_UNLOAD"); install_pe_loader (); mutex_inited = TRUE; } /** * mono_images_cleanup: * * Free all resources used by this module. */ void mono_images_cleanup (void) { } /** * mono_image_ensure_section_idx: * \param image The image we are operating on * \param section section number that we will load/map into memory * * This routine makes sure that we have an in-memory copy of * an image section (<code>.text</code>, <code>.rsrc</code>, <code>.data</code>). * * \returns TRUE on success */ int mono_image_ensure_section_idx (MonoImage *image, int section) { MonoCLIImageInfo *iinfo = image->image_info; MonoSectionTable *sect; g_return_val_if_fail (section < iinfo->cli_section_count, FALSE); if (iinfo->cli_sections [section] != NULL) return TRUE; sect = &iinfo->cli_section_tables [section]; if (sect->st_raw_data_ptr + sect->st_raw_data_size > image->raw_data_len) return FALSE; #ifdef HOST_WIN32 if (m_image_is_module_handle (image)) iinfo->cli_sections [section] = image->raw_data + sect->st_virtual_address; else #endif /* FIXME: we ignore the writable flag since we don't patch the binary */ iinfo->cli_sections [section] = image->raw_data + sect->st_raw_data_ptr; return TRUE; } /** * mono_image_ensure_section: * \param image The image we are operating on * \param section section name that we will load/map into memory * * This routine makes sure that we have an in-memory copy of * an image section (.text, .rsrc, .data). * * \returns TRUE on success */ int mono_image_ensure_section (MonoImage *image, const char *section) { MonoCLIImageInfo *ii = image->image_info; int i; for (i = 0; i < ii->cli_section_count; i++){ if (strncmp (ii->cli_section_tables [i].st_name, section, 8) != 0) continue; return mono_image_ensure_section_idx (image, i); } return FALSE; } static int load_section_tables (MonoImage *image, MonoCLIImageInfo *iinfo, guint32 offset) { const int top = iinfo->cli_header.coff.coff_sections; int i; iinfo->cli_section_count = top; iinfo->cli_section_tables = g_new0 (MonoSectionTable, top); iinfo->cli_sections = g_new0 (void *, top); for (i = 0; i < top; i++){ MonoSectionTable *t = &iinfo->cli_section_tables [i]; if (offset + sizeof (MonoSectionTable) > image->raw_data_len) return FALSE; memcpy (t, image->raw_data + offset, sizeof (MonoSectionTable)); offset += sizeof (MonoSectionTable); #if G_BYTE_ORDER != G_LITTLE_ENDIAN t->st_virtual_size = GUINT32_FROM_LE (t->st_virtual_size); t->st_virtual_address = GUINT32_FROM_LE (t->st_virtual_address); t->st_raw_data_size = GUINT32_FROM_LE (t->st_raw_data_size); t->st_raw_data_ptr = GUINT32_FROM_LE (t->st_raw_data_ptr); t->st_reloc_ptr = GUINT32_FROM_LE (t->st_reloc_ptr); t->st_lineno_ptr = GUINT32_FROM_LE (t->st_lineno_ptr); t->st_reloc_count = GUINT16_FROM_LE (t->st_reloc_count); t->st_line_count = GUINT16_FROM_LE (t->st_line_count); t->st_flags = GUINT32_FROM_LE (t->st_flags); #endif /* consistency checks here */ } return TRUE; } gboolean mono_image_load_cli_header (MonoImage *image, MonoCLIImageInfo *iinfo) { guint32 offset; offset = mono_cli_rva_image_map (image, iinfo->cli_header.datadir.pe_cli_header.rva); if (offset == INVALID_ADDRESS) return FALSE; if (offset + sizeof (MonoCLIHeader) > image->raw_data_len) return FALSE; memcpy (&iinfo->cli_cli_header, image->raw_data + offset, sizeof (MonoCLIHeader)); #if G_BYTE_ORDER != G_LITTLE_ENDIAN #define SWAP32(x) (x) = GUINT32_FROM_LE ((x)) #define SWAP16(x) (x) = GUINT16_FROM_LE ((x)) #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0) SWAP32 (iinfo->cli_cli_header.ch_size); SWAP32 (iinfo->cli_cli_header.ch_flags); SWAP32 (iinfo->cli_cli_header.ch_entry_point); SWAP16 (iinfo->cli_cli_header.ch_runtime_major); SWAP16 (iinfo->cli_cli_header.ch_runtime_minor); SWAPPDE (iinfo->cli_cli_header.ch_metadata); SWAPPDE (iinfo->cli_cli_header.ch_resources); SWAPPDE (iinfo->cli_cli_header.ch_strong_name); SWAPPDE (iinfo->cli_cli_header.ch_code_manager_table); SWAPPDE (iinfo->cli_cli_header.ch_vtable_fixups); SWAPPDE (iinfo->cli_cli_header.ch_export_address_table_jumps); SWAPPDE (iinfo->cli_cli_header.ch_eeinfo_table); SWAPPDE (iinfo->cli_cli_header.ch_helper_table); SWAPPDE (iinfo->cli_cli_header.ch_dynamic_info); SWAPPDE (iinfo->cli_cli_header.ch_delay_load_info); SWAPPDE (iinfo->cli_cli_header.ch_module_image); SWAPPDE (iinfo->cli_cli_header.ch_external_fixups); SWAPPDE (iinfo->cli_cli_header.ch_ridmap); SWAPPDE (iinfo->cli_cli_header.ch_debug_map); SWAPPDE (iinfo->cli_cli_header.ch_ip_map); #undef SWAP32 #undef SWAP16 #undef SWAPPDE #endif /* Catch new uses of the fields that are supposed to be zero */ if ((iinfo->cli_cli_header.ch_eeinfo_table.rva != 0) || (iinfo->cli_cli_header.ch_helper_table.rva != 0) || (iinfo->cli_cli_header.ch_dynamic_info.rva != 0) || (iinfo->cli_cli_header.ch_delay_load_info.rva != 0) || (iinfo->cli_cli_header.ch_module_image.rva != 0) || (iinfo->cli_cli_header.ch_external_fixups.rva != 0) || (iinfo->cli_cli_header.ch_ridmap.rva != 0) || (iinfo->cli_cli_header.ch_debug_map.rva != 0) || (iinfo->cli_cli_header.ch_ip_map.rva != 0)){ /* * No need to scare people who are testing this, I am just * labelling this as a LAMESPEC */ /* g_warning ("Some fields in the CLI header which should have been zero are not zero"); */ } return TRUE; } /** * mono_metadata_module_mvid: * * Return the module mvid GUID or NULL if the image doesn't have a module table. */ static const guint8 * mono_metadata_module_mvid (MonoImage *image) { if (!image->tables [MONO_TABLE_MODULE].base) return NULL; guint32 module_cols [MONO_MODULE_SIZE]; mono_metadata_decode_row (&image->tables [MONO_TABLE_MODULE], 0, module_cols, MONO_MODULE_SIZE); return (const guint8*) mono_metadata_guid_heap (image, module_cols [MONO_MODULE_MVID]); } static gboolean load_metadata_ptrs (MonoImage *image, MonoCLIImageInfo *iinfo) { guint32 offset, size; guint16 streams; int i; guint32 pad; char *ptr; offset = mono_cli_rva_image_map (image, iinfo->cli_cli_header.ch_metadata.rva); if (offset == INVALID_ADDRESS) return FALSE; size = iinfo->cli_cli_header.ch_metadata.size; if (offset + size > image->raw_data_len) return FALSE; image->raw_metadata = image->raw_data + offset; /* 24.2.1: Metadata root starts here */ ptr = image->raw_metadata; if (strncmp (ptr, "BSJB", 4) == 0){ guint32 version_string_len; ptr += 4; image->md_version_major = read16 (ptr); ptr += 2; image->md_version_minor = read16 (ptr); ptr += 6; version_string_len = read32 (ptr); ptr += 4; image->version = g_strndup (ptr, version_string_len); ptr += version_string_len; pad = ptr - image->raw_metadata; if (pad % 4) ptr += 4 - (pad % 4); } else return FALSE; /* skip over flags */ ptr += 2; streams = read16 (ptr); ptr += 2; for (i = 0; i < streams; i++){ if (strncmp (ptr + 8, "#~", 3) == 0){ image->heap_tables.data = image->raw_metadata + read32 (ptr); image->heap_tables.size = read32 (ptr + 4); ptr += 8 + 3; } else if (strncmp (ptr + 8, "#Strings", 9) == 0){ image->heap_strings.data = image->raw_metadata + read32 (ptr); image->heap_strings.size = read32 (ptr + 4); ptr += 8 + 9; } else if (strncmp (ptr + 8, "#US", 4) == 0){ image->heap_us.data = image->raw_metadata + read32 (ptr); image->heap_us.size = read32 (ptr + 4); ptr += 8 + 4; } else if (strncmp (ptr + 8, "#Blob", 6) == 0){ image->heap_blob.data = image->raw_metadata + read32 (ptr); image->heap_blob.size = read32 (ptr + 4); ptr += 8 + 6; } else if (strncmp (ptr + 8, "#GUID", 6) == 0){ image->heap_guid.data = image->raw_metadata + read32 (ptr); image->heap_guid.size = read32 (ptr + 4); ptr += 8 + 6; } else if (strncmp (ptr + 8, "#-", 3) == 0) { image->heap_tables.data = image->raw_metadata + read32 (ptr); image->heap_tables.size = read32 (ptr + 4); ptr += 8 + 3; image->uncompressed_metadata = TRUE; mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_ASSEMBLY, "Assembly '%s' has the non-standard metadata heap #-.\nRecompile it correctly (without the /incremental switch or in Release mode).", image->name); } else if (strncmp (ptr + 8, "#Pdb", 5) == 0) { image->heap_pdb.data = image->raw_metadata + read32 (ptr); image->heap_pdb.size = read32 (ptr + 4); ptr += 8 + 5; } else if (strncmp (ptr + 8, "#JTD", 5) == 0) { // See https://github.com/dotnet/runtime/blob/110282c71b3f7e1f91ea339953f4a0eba362a62c/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReader.cs#L165-L175 // skip read32(ptr) and read32(ptr + 4) // ignore the content of this stream image->minimal_delta = TRUE; mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_METADATA_UPDATE, "Image '%s' has a minimal delta marker", image->name); ptr += 8 + 5; } else { g_message ("Unknown heap type: %s\n", ptr + 8); ptr += 8 + strlen (ptr + 8) + 1; } pad = ptr - image->raw_metadata; if (pad % 4) ptr += 4 - (pad % 4); } { /* Compute the precise size of the string heap by walking back over the trailing nul padding. * * ENC minimal delta images require the precise size of the base image string heap to be known. */ const char *p; p = image->heap_strings.data + image->heap_strings.size - 1; pad = 0; while (p [0] == '\0' && p [-1] == '\0') { p--; pad++; } image->heap_strings.size -= pad; } i = ((MonoImageLoader*)image->loader)->load_tables (image); if (!image->metadata_only) { g_assert (image->heap_guid.data); g_assert (image->heap_guid.size >= 16); image->guid = mono_guid_to_string ((guint8*)image->heap_guid.data); } else { const guint8 *guid = mono_metadata_module_mvid (image); if (guid) image->guid = mono_guid_to_string (guid); else { /* PPDB files have no guid */ guint8 empty_guid [16]; memset (empty_guid, 0, sizeof (empty_guid)); image->guid = mono_guid_to_string (empty_guid); } } return i; } /* * Load representation of logical metadata tables, from the "#~" or "#-" stream */ static gboolean load_tables (MonoImage *image) { const char *heap_tables = image->heap_tables.data; const guint32 *rows; guint64 valid_mask; int valid = 0, table; int heap_sizes; heap_sizes = heap_tables [6]; image->idx_string_wide = ((heap_sizes & 0x01) == 1); image->idx_guid_wide = ((heap_sizes & 0x02) == 2); image->idx_blob_wide = ((heap_sizes & 0x04) == 4); if (G_UNLIKELY (image->minimal_delta)) { /* sanity check */ g_assert (image->idx_string_wide); g_assert (image->idx_guid_wide); g_assert (image->idx_blob_wide); } valid_mask = read64 (heap_tables + 8); rows = (const guint32 *) (heap_tables + 24); for (table = 0; table < 64; table++){ if ((valid_mask & ((guint64) 1 << table)) == 0){ if (table > MONO_TABLE_LAST) continue; image->tables [table].rows_ = 0; continue; } if (table > MONO_TABLE_LAST) { g_warning("bits in valid must be zero above 0x37 (II - 23.1.6)"); } else { image->tables [table].rows_ = read32 (rows); } rows++; valid++; } image->tables_base = (heap_tables + 24) + (4 * valid); /* They must be the same */ g_assert ((const void *) image->tables_base == (const void *) rows); if (image->heap_pdb.size) { /* * Obtain token sizes from the pdb stream. */ /* 24 = guid + entry point */ int pos = 24; image->referenced_tables = read64 (image->heap_pdb.data + pos); pos += 8; image->referenced_table_rows = g_new0 (int, 64); for (int i = 0; i < 64; ++i) { if (image->referenced_tables & ((guint64)1 << i)) { image->referenced_table_rows [i] = read32 (image->heap_pdb.data + pos); pos += 4; } } } mono_metadata_compute_table_bases (image); return TRUE; } gboolean mono_image_load_metadata (MonoImage *image, MonoCLIImageInfo *iinfo) { if (!load_metadata_ptrs (image, iinfo)) return FALSE; return load_tables (image); } void mono_image_check_for_module_cctor (MonoImage *image) { MonoTableInfo *t, *mt; t = &image->tables [MONO_TABLE_TYPEDEF]; mt = &image->tables [MONO_TABLE_METHOD]; if (image_is_dynamic (image)) { /* FIXME: */ image->checked_module_cctor = TRUE; return; } if (table_info_get_rows (t) >= 1) { guint32 nameidx = mono_metadata_decode_row_col (t, 0, MONO_TYPEDEF_NAME); const char *name = mono_metadata_string_heap (image, nameidx); if (strcmp (name, "<Module>") == 0) { guint32 first_method = mono_metadata_decode_row_col (t, 0, MONO_TYPEDEF_METHOD_LIST) - 1; guint32 last_method; if (table_info_get_rows (t) > 1) last_method = mono_metadata_decode_row_col (t, 1, MONO_TYPEDEF_METHOD_LIST) - 1; else last_method = table_info_get_rows (mt); for (; first_method < last_method; first_method++) { nameidx = mono_metadata_decode_row_col (mt, first_method, MONO_METHOD_NAME); name = mono_metadata_string_heap (image, nameidx); if (strcmp (name, ".cctor") == 0) { image->has_module_cctor = TRUE; image->checked_module_cctor = TRUE; return; } } } } image->has_module_cctor = FALSE; image->checked_module_cctor = TRUE; } /** * mono_image_load_module_checked: * * Load the module with the one-based index IDX from IMAGE and return it. Return NULL if * it cannot be loaded. NULL without MonoError being set will be interpreted as "not found". */ MonoImage* mono_image_load_module_checked (MonoImage *image, int idx, MonoError *error) { error_init (error); if ((image->module_count == 0) || (idx > image->module_count || idx <= 0)) return NULL; if (image->modules_loaded [idx - 1]) return image->modules [idx - 1]; /* SRE still uses image->modules, but they are not loaded from files, so the rest of this function is dead code for netcore */ g_assert_not_reached (); } /** * mono_image_load_module: */ MonoImage* mono_image_load_module (MonoImage *image, int idx) { ERROR_DECL (error); MonoImage *result = mono_image_load_module_checked (image, idx, error); mono_error_assert_ok (error); return result; } static gpointer class_key_extract (gpointer value) { MonoClass *klass = (MonoClass *)value; return GUINT_TO_POINTER (m_class_get_type_token (klass)); } static gpointer* class_next_value (gpointer value) { MonoClassDef *klass = (MonoClassDef *)value; return (gpointer*)m_classdef_get_next_class_cache (klass); } /** * mono_image_init: */ void mono_image_init (MonoImage *image) { mono_os_mutex_init_recursive (&image->lock); mono_os_mutex_init_recursive (&image->szarray_cache_lock); image->mempool = mono_mempool_new_size (INITIAL_IMAGE_SIZE); mono_internal_hash_table_init (&image->class_cache, g_direct_hash, class_key_extract, class_next_value); image->field_cache = mono_conc_hashtable_new (NULL, NULL); image->typespec_cache = mono_conc_hashtable_new (NULL, NULL); image->memberref_signatures = g_hash_table_new (NULL, NULL); image->method_signatures = g_hash_table_new (NULL, NULL); image->property_hash = mono_property_hash_new (); } #if G_BYTE_ORDER != G_LITTLE_ENDIAN #define SWAP64(x) (x) = GUINT64_FROM_LE ((x)) #define SWAP32(x) (x) = GUINT32_FROM_LE ((x)) #define SWAP16(x) (x) = GUINT16_FROM_LE ((x)) #define SWAPPDE(x) do { (x).rva = GUINT32_FROM_LE ((x).rva); (x).size = GUINT32_FROM_LE ((x).size);} while (0) #else #define SWAP64(x) #define SWAP32(x) #define SWAP16(x) #define SWAPPDE(x) #endif static int do_load_header_internal (const char *raw_data, guint32 raw_data_len, MonoDotNetHeader *header, int offset, gboolean image_is_module_handle) { MonoDotNetHeader64 header64; #ifdef HOST_WIN32 if (!image_is_module_handle) #endif if (offset + sizeof (MonoDotNetHeader32) > raw_data_len) return -1; memcpy (header, raw_data + offset, sizeof (MonoDotNetHeader)); if (header->pesig [0] != 'P' || header->pesig [1] != 'E' || header->pesig [2] || header->pesig [3]) return -1; /* endian swap the fields common between PE and PE+ */ SWAP32 (header->coff.coff_time); SWAP32 (header->coff.coff_symptr); SWAP32 (header->coff.coff_symcount); SWAP16 (header->coff.coff_machine); SWAP16 (header->coff.coff_sections); SWAP16 (header->coff.coff_opt_header_size); SWAP16 (header->coff.coff_attributes); /* MonoPEHeader */ SWAP32 (header->pe.pe_code_size); SWAP32 (header->pe.pe_uninit_data_size); SWAP32 (header->pe.pe_rva_entry_point); SWAP32 (header->pe.pe_rva_code_base); SWAP32 (header->pe.pe_rva_data_base); SWAP16 (header->pe.pe_magic); /* now we are ready for the basic tests */ if (header->pe.pe_magic == 0x10B) { offset += sizeof (MonoDotNetHeader); SWAP32 (header->pe.pe_data_size); if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader) - sizeof (MonoCOFFHeader) - 4)) return -1; SWAP32 (header->nt.pe_image_base); /* must be 0x400000 */ SWAP32 (header->nt.pe_stack_reserve); SWAP32 (header->nt.pe_stack_commit); SWAP32 (header->nt.pe_heap_reserve); SWAP32 (header->nt.pe_heap_commit); } else if (header->pe.pe_magic == 0x20B) { /* PE32+ file format */ if (header->coff.coff_opt_header_size != (sizeof (MonoDotNetHeader64) - sizeof (MonoCOFFHeader) - 4)) return -1; memcpy (&header64, raw_data + offset, sizeof (MonoDotNetHeader64)); offset += sizeof (MonoDotNetHeader64); /* copy the fields already swapped. the last field, pe_data_size, is missing */ memcpy (&header64, header, sizeof (MonoDotNetHeader) - 4); /* FIXME: we lose bits here, but we don't use this stuff internally, so we don't care much. * will be fixed when we change MonoDotNetHeader to not match the 32 bit variant */ SWAP64 (header64.nt.pe_image_base); header->nt.pe_image_base = header64.nt.pe_image_base; SWAP64 (header64.nt.pe_stack_reserve); header->nt.pe_stack_reserve = header64.nt.pe_stack_reserve; SWAP64 (header64.nt.pe_stack_commit); header->nt.pe_stack_commit = header64.nt.pe_stack_commit; SWAP64 (header64.nt.pe_heap_reserve); header->nt.pe_heap_reserve = header64.nt.pe_heap_reserve; SWAP64 (header64.nt.pe_heap_commit); header->nt.pe_heap_commit = header64.nt.pe_heap_commit; header->nt.pe_section_align = header64.nt.pe_section_align; header->nt.pe_file_alignment = header64.nt.pe_file_alignment; header->nt.pe_os_major = header64.nt.pe_os_major; header->nt.pe_os_minor = header64.nt.pe_os_minor; header->nt.pe_user_major = header64.nt.pe_user_major; header->nt.pe_user_minor = header64.nt.pe_user_minor; header->nt.pe_subsys_major = header64.nt.pe_subsys_major; header->nt.pe_subsys_minor = header64.nt.pe_subsys_minor; header->nt.pe_reserved_1 = header64.nt.pe_reserved_1; header->nt.pe_image_size = header64.nt.pe_image_size; header->nt.pe_header_size = header64.nt.pe_header_size; header->nt.pe_checksum = header64.nt.pe_checksum; header->nt.pe_subsys_required = header64.nt.pe_subsys_required; header->nt.pe_dll_flags = header64.nt.pe_dll_flags; header->nt.pe_loader_flags = header64.nt.pe_loader_flags; header->nt.pe_data_dir_count = header64.nt.pe_data_dir_count; /* copy the datadir */ memcpy (&header->datadir, &header64.datadir, sizeof (MonoPEDatadir)); } else { return -1; } /* MonoPEHeaderNT: not used yet */ SWAP32 (header->nt.pe_section_align); /* must be 8192 */ SWAP32 (header->nt.pe_file_alignment); /* must be 512 or 4096 */ SWAP16 (header->nt.pe_os_major); /* must be 4 */ SWAP16 (header->nt.pe_os_minor); /* must be 0 */ SWAP16 (header->nt.pe_user_major); SWAP16 (header->nt.pe_user_minor); SWAP16 (header->nt.pe_subsys_major); SWAP16 (header->nt.pe_subsys_minor); SWAP32 (header->nt.pe_reserved_1); SWAP32 (header->nt.pe_image_size); SWAP32 (header->nt.pe_header_size); SWAP32 (header->nt.pe_checksum); SWAP16 (header->nt.pe_subsys_required); SWAP16 (header->nt.pe_dll_flags); SWAP32 (header->nt.pe_loader_flags); SWAP32 (header->nt.pe_data_dir_count); /* MonoDotNetHeader: mostly unused */ SWAPPDE (header->datadir.pe_export_table); SWAPPDE (header->datadir.pe_import_table); SWAPPDE (header->datadir.pe_resource_table); SWAPPDE (header->datadir.pe_exception_table); SWAPPDE (header->datadir.pe_certificate_table); SWAPPDE (header->datadir.pe_reloc_table); SWAPPDE (header->datadir.pe_debug); SWAPPDE (header->datadir.pe_copyright); SWAPPDE (header->datadir.pe_global_ptr); SWAPPDE (header->datadir.pe_tls_table); SWAPPDE (header->datadir.pe_load_config_table); SWAPPDE (header->datadir.pe_bound_import); SWAPPDE (header->datadir.pe_iat); SWAPPDE (header->datadir.pe_delay_import_desc); SWAPPDE (header->datadir.pe_cli_header); SWAPPDE (header->datadir.pe_reserved); return offset; } /* * Returns < 0 to indicate an error. */ static int do_load_header (MonoImage *image, MonoDotNetHeader *header, int offset) { offset = do_load_header_internal (image->raw_data, image->raw_data_len, header, offset, #ifdef HOST_WIN32 m_image_is_module_handle (image)); #else FALSE); #endif #ifdef HOST_WIN32 if (m_image_is_module_handle (image)) image->storage->raw_data_len = header->nt.pe_image_size; #endif return offset; } mono_bool mono_has_pdb_checksum (char *raw_data, uint32_t raw_data_len) { MonoDotNetHeader cli_header; MonoMSDOSHeader msdos; int idx; guint8 *data; int offset = 0; memcpy (&msdos, raw_data + offset, sizeof (msdos)); if (!(msdos.msdos_sig [0] == 'M' && msdos.msdos_sig [1] == 'Z')) { return FALSE; } msdos.pe_offset = GUINT32_FROM_LE (msdos.pe_offset); offset = msdos.pe_offset; int ret = do_load_header_internal (raw_data, raw_data_len, &cli_header, offset, FALSE); if ( ret >= 0 ) { MonoPEDirEntry *debug_dir_entry = (MonoPEDirEntry *) &cli_header.datadir.pe_debug; ImageDebugDirectory debug_dir; if (!debug_dir_entry->size) return FALSE; else { const int top = cli_header.coff.coff_sections; int addr = debug_dir_entry->rva; int i = 0; for (i = 0; i < top; i++){ MonoSectionTable t; if (ret + sizeof (MonoSectionTable) > raw_data_len) { return FALSE; } memcpy (&t, raw_data + ret, sizeof (MonoSectionTable)); ret += sizeof (MonoSectionTable); #if G_BYTE_ORDER != G_LITTLE_ENDIAN t.st_virtual_address = GUINT32_FROM_LE (t.st_virtual_address); t.st_raw_data_size = GUINT32_FROM_LE (t.st_raw_data_size); t.st_raw_data_ptr = GUINT32_FROM_LE (t.st_raw_data_ptr); #endif /* consistency checks here */ if ((addr >= t.st_virtual_address) && (addr < t.st_virtual_address + t.st_raw_data_size)){ addr = addr - t.st_virtual_address + t.st_raw_data_ptr; break; } } for (idx = 0; idx < debug_dir_entry->size / sizeof (ImageDebugDirectory); ++idx) { data = (guint8 *) ((ImageDebugDirectory *) (raw_data + addr) + idx); debug_dir.characteristics = read32(data); debug_dir.time_date_stamp = read32(data + 4); debug_dir.major_version = read16(data + 8); debug_dir.minor_version = read16(data + 10); debug_dir.type = read32(data + 12); if (debug_dir.type == DEBUG_DIR_PDB_CHECKSUM || debug_dir.type == DEBUG_DIR_REPRODUCIBLE) return TRUE; } } } return FALSE; } gboolean mono_image_load_pe_data (MonoImage *image) { return ((MonoImageLoader*)image->loader)->load_pe_data (image); } static gboolean pe_image_load_pe_data (MonoImage *image) { MonoCLIImageInfo *iinfo; MonoDotNetHeader *header; MonoMSDOSHeader msdos; gint32 offset = 0; iinfo = image->image_info; header = &iinfo->cli_header; #ifdef HOST_WIN32 if (!m_image_is_module_handle (image)) #endif if (offset + sizeof (msdos) > image->raw_data_len) goto invalid_image; memcpy (&msdos, image->raw_data + offset, sizeof (msdos)); if (!(msdos.msdos_sig [0] == 'M' && msdos.msdos_sig [1] == 'Z')) goto invalid_image; msdos.pe_offset = GUINT32_FROM_LE (msdos.pe_offset); offset = msdos.pe_offset; offset = do_load_header (image, header, offset); if (offset < 0) goto invalid_image; /* * this tests for a x86 machine type, but itanium, amd64 and others could be used, too. * we skip this test. if (header->coff.coff_machine != 0x14c) goto invalid_image; */ #if 0 /* * The spec says that this field should contain 6.0, but Visual Studio includes a new compiler, * which produces binaries with 7.0. From Sergey: * * The reason is that MSVC7 uses traditional compile/link * sequence for CIL executables, and VS.NET (and Framework * SDK) includes linker version 7, that puts 7.0 in this * field. That's why it's currently not possible to load VC * binaries with Mono. This field is pretty much meaningless * anyway (what linker?). */ if (header->pe.pe_major != 6 || header->pe.pe_minor != 0) goto invalid_image; #endif /* * FIXME: byte swap all addresses here for header. */ if (!load_section_tables (image, iinfo, offset)) goto invalid_image; return TRUE; invalid_image: return FALSE; } gboolean mono_image_load_cli_data (MonoImage *image) { return ((MonoImageLoader*)image->loader)->load_cli_data (image); } static gboolean pe_image_load_cli_data (MonoImage *image) { MonoCLIImageInfo *iinfo; iinfo = image->image_info; /* Load the CLI header */ if (!mono_image_load_cli_header (image, iinfo)) return FALSE; if (!mono_image_load_metadata (image, iinfo)) return FALSE; return TRUE; } void mono_image_load_names (MonoImage *image) { /* modules don't have an assembly table row */ if (table_info_get_rows (&image->tables [MONO_TABLE_ASSEMBLY])) { image->assembly_name = mono_metadata_string_heap (image, mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY], 0, MONO_ASSEMBLY_NAME)); } /* Portable pdb images don't have a MODULE row */ /* Minimal ENC delta images index the combined string heap of the base and delta image, * so the module index is out of bounds here. */ if (table_info_get_rows (&image->tables [MONO_TABLE_MODULE]) && !image->minimal_delta) { image->module_name = mono_metadata_string_heap (image, mono_metadata_decode_row_col (&image->tables [MONO_TABLE_MODULE], 0, MONO_MODULE_NAME)); } } static gboolean pe_image_load_tables (MonoImage *image) { return TRUE; } static gboolean pe_image_match (MonoImage *image) { if (image->raw_data [0] == 'M' && image->raw_data [1] == 'Z') return TRUE; return FALSE; } static const MonoImageLoader pe_loader = { pe_image_match, pe_image_load_pe_data, pe_image_load_cli_data, pe_image_load_tables, }; static void install_pe_loader (void) { mono_install_image_loader (&pe_loader); } /* Equivalent C# code: static void Main () { string str = "..."; int h = 5381; for (int i = 0; i < str.Length; ++i) h = ((h << 5) + h) ^ str[i]; Console.WriteLine ("{0:X}", h); } */ static int hash_guid (const char *str) { int h = 5381; while (*str) { h = ((h << 5) + h) ^ *str; ++str; } return h; } static void dump_encmap (MonoImage *image) { MonoTableInfo *encmap = &image->tables [MONO_TABLE_ENCMAP]; if (!encmap || !table_info_get_rows (encmap)) return; if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE)) { mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "ENCMAP for %s", image->filename); for (int i = 0; i < table_info_get_rows (encmap); ++i) { guint32 cols [MONO_ENCMAP_SIZE]; mono_metadata_decode_row (encmap, i, cols, MONO_ENCMAP_SIZE); int token = cols [MONO_ENCMAP_TOKEN]; mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "\t0x%08x: 0x%08x table: %s", i+1, token, mono_meta_table_name (mono_metadata_token_table (token))); } } } static MonoImage * do_mono_image_load (MonoImage *image, MonoImageOpenStatus *status, gboolean care_about_cli, gboolean care_about_pecoff) { ERROR_DECL (error); GSList *l; MONO_PROFILER_RAISE (image_loading, (image)); mono_image_init (image); if (!image->metadata_only) { for (l = image_loaders; l; l = l->next) { MonoImageLoader *loader = (MonoImageLoader *)l->data; if (loader->match (image)) { image->loader = loader; break; } } if (!image->loader) { if (status) *status = MONO_IMAGE_IMAGE_INVALID; goto invalid_image; } if (status) *status = MONO_IMAGE_IMAGE_INVALID; if (care_about_pecoff == FALSE) goto done; if (!mono_image_load_pe_data (image)) goto invalid_image; } else { image->loader = (MonoImageLoader*)&pe_loader; } if (care_about_cli == FALSE) { goto done; } if (!mono_image_load_cli_data (image)) goto invalid_image; dump_encmap (image); mono_image_load_names (image); done: MONO_PROFILER_RAISE (image_loaded, (image)); if (status) *status = MONO_IMAGE_OK; return image; invalid_image: if (!is_ok (error)) { mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_ASSEMBLY, "Could not load image %s due to %s", image->name, mono_error_get_message (error)); mono_error_cleanup (error); } MONO_PROFILER_RAISE (image_failed, (image)); mono_image_close (image); return NULL; } static gboolean mono_image_storage_trypublish (MonoImageStorage *candidate, MonoImageStorage **out_storage) { gboolean result; mono_images_storage_lock (); MonoImageStorage *val = (MonoImageStorage *)g_hash_table_lookup (images_storage_hash, candidate->key); if (val && !mono_refcount_tryinc (val)) { // We raced against a mono_image_storage_dtor in progress. val = NULL; } if (val) { *out_storage = val; result = FALSE; } else { g_hash_table_insert (images_storage_hash, candidate->key, candidate); result = TRUE; } mono_images_storage_unlock (); return result; } static void mono_image_storage_unpublish (MonoImageStorage *storage) { mono_images_storage_lock (); g_assert (storage->ref.ref == 0); MonoImageStorage *published = (MonoImageStorage *)g_hash_table_lookup (images_storage_hash, storage->key); if (published == storage) { g_hash_table_remove (images_storage_hash, storage->key); } mono_images_storage_unlock (); } static gboolean mono_image_storage_tryaddref (const char *key, MonoImageStorage **found) { gboolean result = FALSE; mono_images_storage_lock (); MonoImageStorage *val = (MonoImageStorage *)g_hash_table_lookup (images_storage_hash, key); if (val && !mono_refcount_tryinc (val)) { // We raced against a mono_image_storage_dtor in progress. val = NULL; } if (val) { *found = val; result = TRUE; } mono_images_storage_unlock (); return result; } static void mono_image_storage_dtor (gpointer self) { MonoImageStorage *storage = (MonoImageStorage *)self; mono_image_storage_unpublish (storage); #ifdef HOST_WIN32 if (storage->is_module_handle && !storage->has_entry_point) { mono_images_lock (); FreeLibrary ((HMODULE) storage->raw_data); mono_images_unlock (); } #endif if (storage->raw_buffer_used) { if (storage->raw_data != NULL) { #ifndef HOST_WIN32 if (storage->fileio_used) mono_file_unmap_fileio (storage->raw_data, storage->raw_data_handle); else #endif mono_file_unmap (storage->raw_data, storage->raw_data_handle); } } if (storage->raw_data_allocated) { g_free (storage->raw_data); } g_free (storage->key); g_free (storage); } static void mono_image_storage_close (MonoImageStorage *storage) { mono_refcount_dec (storage); } static gboolean mono_image_init_raw_data (MonoImage *image, const MonoImageStorage *storage) { if (!storage) return FALSE; image->raw_data = storage->raw_data; image->raw_data_len = storage->raw_data_len; return TRUE; } static MonoImageStorage * mono_image_storage_open (const char *fname) { char *key = NULL; key = mono_path_resolve_symlinks (fname); MonoImageStorage *published_storage = NULL; if (mono_image_storage_tryaddref (key, &published_storage)) { g_free (key); return published_storage; } MonoFileMap *filed; if ((filed = mono_file_map_open (fname)) == NULL){ g_free (key); return NULL; } MonoImageStorage *storage = g_new0 (MonoImageStorage, 1); mono_refcount_init (storage, mono_image_storage_dtor); storage->raw_buffer_used = TRUE; storage->raw_data_len = mono_file_map_size (filed); storage->raw_data = (char*)mono_file_map (storage->raw_data_len, MONO_MMAP_READ|MONO_MMAP_PRIVATE, mono_file_map_fd (filed), 0, &storage->raw_data_handle); #if defined(HAVE_MMAP) && !defined (HOST_WIN32) if (!storage->raw_data) { storage->fileio_used = TRUE; storage->raw_data = (char *)mono_file_map_fileio (storage->raw_data_len, MONO_MMAP_READ|MONO_MMAP_PRIVATE, mono_file_map_fd (filed), 0, &storage->raw_data_handle); } #endif mono_file_map_close (filed); storage->key = key; MonoImageStorage *other_storage = NULL; if (!mono_image_storage_trypublish (storage, &other_storage)) { mono_image_storage_close (storage); storage = other_storage; } return storage; } static MonoImageStorage * mono_image_storage_new_raw_data (char *datac, guint32 data_len, gboolean raw_data_allocated, const char *name) { char *key = (name == NULL) ? g_strdup_printf ("data-%p", datac) : g_strdup (name); MonoImageStorage *published_storage = NULL; if (mono_image_storage_tryaddref (key, &published_storage)) { g_free (key); return published_storage; } MonoImageStorage *storage = g_new0 (MonoImageStorage, 1); mono_refcount_init (storage, mono_image_storage_dtor); storage->raw_data = datac; storage->raw_data_len = data_len; storage->raw_data_allocated = raw_data_allocated; storage->key = key; MonoImageStorage *other_storage = NULL; if (!mono_image_storage_trypublish (storage, &other_storage)) { mono_image_storage_close (storage); storage = other_storage; } return storage; } static MonoImage * do_mono_image_open (MonoAssemblyLoadContext *alc, const char *fname, MonoImageOpenStatus *status, gboolean care_about_cli, gboolean care_about_pecoff, gboolean metadata_only) { MonoCLIImageInfo *iinfo; MonoImage *image; MonoImageStorage *storage = mono_image_storage_open (fname); if (!storage) { if (status) *status = MONO_IMAGE_ERROR_ERRNO; return NULL; } image = g_new0 (MonoImage, 1); image->storage = storage; mono_image_init_raw_data (image, storage); if (!image->raw_data) { mono_image_storage_close (image->storage); g_free (image); if (status) *status = MONO_IMAGE_IMAGE_INVALID; return NULL; } iinfo = g_new0 (MonoCLIImageInfo, 1); image->image_info = iinfo; image->name = mono_path_resolve_symlinks (fname); image->filename = g_strdup (image->name); image->metadata_only = metadata_only; image->ref_count = 1; image->alc = alc; return do_mono_image_load (image, status, care_about_cli, care_about_pecoff); } /** * mono_image_loaded_full: * \param name path or assembly name of the image to load * \param refonly Check with respect to reflection-only loads? * * This routine verifies that the given image is loaded. * It checks either reflection-only loads only, or normal loads only, as specified by parameter. * * \returns the loaded \c MonoImage, or NULL on failure. */ MonoImage * mono_image_loaded_full (const char *name, gboolean refonly) { if (refonly) return NULL; MonoImage *result; MONO_ENTER_GC_UNSAFE; result = mono_image_loaded_internal (mono_alc_get_default (), name); MONO_EXIT_GC_UNSAFE; return result; } /** * mono_image_loaded_internal: * \param alc The AssemblyLoadContext that should be checked * \param name path or assembly name of the image to load * \param refonly Check with respect to reflection-only loads? * * This routine verifies that the given image is loaded. * It checks either reflection-only loads only, or normal loads only, as specified by parameter. * * \returns the loaded \c MonoImage, or NULL on failure. */ MonoImage * mono_image_loaded_internal (MonoAssemblyLoadContext *alc, const char *name) { MonoLoadedImages *li = mono_alc_get_loaded_images (alc); MonoImage *res; mono_images_lock (); res = (MonoImage *)g_hash_table_lookup (mono_loaded_images_get_hash (li), name); if (!res) res = (MonoImage *)g_hash_table_lookup (mono_loaded_images_get_by_name_hash (li), name); mono_images_unlock (); return res; } /** * mono_image_loaded: * \param name path or assembly name of the image to load * This routine verifies that the given image is loaded. Reflection-only loads do not count. * \returns the loaded \c MonoImage, or NULL on failure. */ MonoImage * mono_image_loaded (const char *name) { MonoImage *result; MONO_ENTER_GC_UNSAFE; result = mono_image_loaded_internal (mono_alc_get_default (), name); MONO_EXIT_GC_UNSAFE; return result; } typedef struct { MonoImage *res; const char* guid; } GuidData; static void find_by_guid (gpointer key, gpointer val, gpointer user_data) { GuidData *data = (GuidData *)user_data; MonoImage *image; if (data->res) return; image = (MonoImage *)val; if (strcmp (data->guid, mono_image_get_guid (image)) == 0) data->res = image; } static MonoImage * mono_image_loaded_by_guid_internal (const char *guid, gboolean refonly); /** * mono_image_loaded_by_guid_full: * * Looks only in the global loaded images hash, will miss assemblies loaded * into an AssemblyLoadContext. */ MonoImage * mono_image_loaded_by_guid_full (const char *guid, gboolean refonly) { return mono_image_loaded_by_guid_internal (guid, refonly); } /** * mono_image_loaded_by_guid_internal: * * Do not use. Looks only in the global loaded images hash, will miss Assembly * Load Contexts. */ static MonoImage * mono_image_loaded_by_guid_internal (const char *guid, gboolean refonly) { /* TODO: Maybe implement this for netcore by searching only the default ALC of the current domain */ return NULL; } /** * mono_image_loaded_by_guid: * * Looks only in the global loaded images hash, will miss assemblies loaded * into an AssemblyLoadContext. */ MonoImage * mono_image_loaded_by_guid (const char *guid) { return mono_image_loaded_by_guid_internal (guid, FALSE); } static MonoImage * register_image (MonoLoadedImages *li, MonoImage *image) { MonoImage *image2; char *name = image->name; GHashTable *loaded_images = mono_loaded_images_get_hash (li); mono_images_lock (); image2 = (MonoImage *)g_hash_table_lookup (loaded_images, name); if (image2) { /* Somebody else beat us to it */ mono_image_addref (image2); mono_images_unlock (); mono_image_close (image); return image2; } GHashTable *loaded_images_by_name = mono_loaded_images_get_by_name_hash (li); g_hash_table_insert (loaded_images, name, image); if (image->assembly_name && (g_hash_table_lookup (loaded_images_by_name, image->assembly_name) == NULL)) g_hash_table_insert (loaded_images_by_name, (char *) image->assembly_name, image); mono_images_unlock (); return image; } MonoImage * mono_image_open_from_data_internal (MonoAssemblyLoadContext *alc, char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status, gboolean metadata_only, const char *name, const char *filename) { MonoCLIImageInfo *iinfo; MonoImage *image; char *datac; if (!data || !data_len) { if (status) *status = MONO_IMAGE_IMAGE_INVALID; return NULL; } datac = data; if (need_copy) { datac = (char *)g_try_malloc (data_len); if (!datac) { if (status) *status = MONO_IMAGE_ERROR_ERRNO; return NULL; } memcpy (datac, data, data_len); } MonoImageStorage *storage = mono_image_storage_new_raw_data (datac, data_len, need_copy, filename); image = g_new0 (MonoImage, 1); image->storage = storage; mono_image_init_raw_data (image, storage); image->name = (name == NULL) ? g_strdup_printf ("data-%p", datac) : g_strdup (name); image->filename = filename ? g_strdup (filename) : NULL; iinfo = g_new0 (MonoCLIImageInfo, 1); image->image_info = iinfo; image->metadata_only = metadata_only; image->ref_count = 1; image->alc = alc; image = do_mono_image_load (image, status, TRUE, TRUE); if (image == NULL) return NULL; return register_image (mono_alc_get_loaded_images (alc), image); } MonoImage * mono_image_open_from_data_alc (MonoAssemblyLoadContextGCHandle alc_gchandle, char *data, uint32_t data_len, mono_bool need_copy, MonoImageOpenStatus *status, const char *name) { MonoImage *result; MONO_ENTER_GC_UNSAFE; MonoAssemblyLoadContext *alc = mono_alc_from_gchandle (alc_gchandle); result = mono_image_open_from_data_internal (alc, data, data_len, need_copy, status, FALSE, name, name); MONO_EXIT_GC_UNSAFE; return result; } /** * mono_image_open_from_data_with_name: */ MonoImage * mono_image_open_from_data_with_name (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status, gboolean refonly, const char *name) { if (refonly) { if (status) { *status = MONO_IMAGE_IMAGE_INVALID; return NULL; } } MonoImage *result; MONO_ENTER_GC_UNSAFE; result = mono_image_open_from_data_internal (mono_alc_get_default (), data, data_len, need_copy, status, FALSE, name, name); MONO_EXIT_GC_UNSAFE; return result; } /** * mono_image_open_from_data_full: */ MonoImage * mono_image_open_from_data_full (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status, gboolean refonly) { if (refonly) { if (status) { *status = MONO_IMAGE_IMAGE_INVALID; return NULL; } } MonoImage *result; MONO_ENTER_GC_UNSAFE; result = mono_image_open_from_data_internal (mono_alc_get_default (), data, data_len, need_copy, status, FALSE, NULL, NULL); MONO_EXIT_GC_UNSAFE; return result; } /** * mono_image_open_from_data: */ MonoImage * mono_image_open_from_data (char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status) { MonoImage *result; MONO_ENTER_GC_UNSAFE; result = mono_image_open_from_data_internal (mono_alc_get_default (), data, data_len, need_copy, status, FALSE, NULL, NULL); MONO_EXIT_GC_UNSAFE; return result; } #ifdef HOST_WIN32 static MonoImageStorage * mono_image_storage_open_from_module_handle (HMODULE module_handle, const char *fname, gboolean has_entry_point) { char *key = g_strdup (fname); MonoImageStorage *published_storage = NULL; if (mono_image_storage_tryaddref (key, &published_storage)) { g_free (key); return published_storage; } MonoImageStorage *storage = g_new0 (MonoImageStorage, 1); mono_refcount_init (storage, mono_image_storage_dtor); storage->raw_data = (char*) module_handle; storage->is_module_handle = TRUE; storage->has_entry_point = has_entry_point; storage->key = key; MonoImageStorage *other_storage = NULL; if (!mono_image_storage_trypublish (storage, &other_storage)) { mono_image_storage_close (storage); storage = other_storage; } return storage; } /* fname is not duplicated. */ MonoImage* mono_image_open_from_module_handle (MonoAssemblyLoadContext *alc, HMODULE module_handle, char* fname, gboolean has_entry_point, MonoImageOpenStatus* status) { MonoImage* image; MonoCLIImageInfo* iinfo; MonoImageStorage *storage = mono_image_storage_open_from_module_handle (module_handle, fname, has_entry_point); image = g_new0 (MonoImage, 1); image->storage = storage; mono_image_init_raw_data (image, storage); iinfo = g_new0 (MonoCLIImageInfo, 1); image->image_info = iinfo; image->name = fname; image->filename = g_strdup (image->name); image->ref_count = has_entry_point ? 0 : 1; image->alc = alc; image = do_mono_image_load (image, status, TRUE, TRUE); if (image == NULL) return NULL; return register_image (mono_alc_get_loaded_images (alc), image); } #endif /** * mono_image_open_full: */ MonoImage * mono_image_open_full (const char *fname, MonoImageOpenStatus *status, gboolean refonly) { if (refonly) { if (status) *status = MONO_IMAGE_IMAGE_INVALID; return NULL; } return mono_image_open_a_lot (mono_alc_get_default (), fname, status); } static MonoImage * mono_image_open_a_lot_parameterized (MonoLoadedImages *li, MonoAssemblyLoadContext *alc, const char *fname, MonoImageOpenStatus *status) { MonoImage *image; GHashTable *loaded_images = mono_loaded_images_get_hash (li); char *absfname; g_return_val_if_fail (fname != NULL, NULL); #ifdef HOST_WIN32 // Win32 path: If we are running with mixed-mode assemblies enabled (ie have loaded mscoree.dll), // then assemblies need to be loaded with LoadLibrary: if (coree_module_handle) { HMODULE module_handle; gunichar2 *fname_utf16; DWORD last_error; absfname = mono_path_resolve_symlinks (fname); fname_utf16 = NULL; /* There is little overhead because the OS loader lock is held by LoadLibrary. */ mono_images_lock (); image = (MonoImage*)g_hash_table_lookup (loaded_images, absfname); if (image) { // Image already loaded g_assert (m_image_is_module_handle (image)); if (m_image_has_entry_point (image) && image->ref_count == 0) { /* Increment reference count on images loaded outside of the runtime. */ fname_utf16 = g_utf8_to_utf16 (absfname, -1, NULL, NULL, NULL); /* The image is already loaded because _CorDllMain removes images from the hash. */ module_handle = LoadLibrary (fname_utf16); g_assert (module_handle == (HMODULE) image->raw_data); } mono_image_addref (image); mono_images_unlock (); if (fname_utf16) g_free (fname_utf16); g_free (absfname); return image; } // Image not loaded, load it now fname_utf16 = g_utf8_to_utf16 (absfname, -1, NULL, NULL, NULL); module_handle = MonoLoadImage (fname_utf16); if (status && module_handle == NULL) last_error = mono_w32error_get_last (); /* mono_image_open_from_module_handle is called by _CorDllMain. */ image = (MonoImage*)g_hash_table_lookup (loaded_images, absfname); if (image) mono_image_addref (image); mono_images_unlock (); g_free (fname_utf16); if (module_handle == NULL) { g_assert (!image); g_free (absfname); if (status) { if (last_error == ERROR_BAD_EXE_FORMAT || last_error == STATUS_INVALID_IMAGE_FORMAT) { if (status) *status = MONO_IMAGE_IMAGE_INVALID; } else { if (last_error == ERROR_FILE_NOT_FOUND || last_error == ERROR_PATH_NOT_FOUND) mono_set_errno (ENOENT); else mono_set_errno (0); } } return NULL; } if (image) { g_assert (m_image_is_module_handle (image)); g_assert (m_image_has_entry_point (image)); g_free (absfname); return image; } return mono_image_open_from_module_handle (alc, module_handle, absfname, FALSE, status); } #endif absfname = mono_path_resolve_symlinks (fname); /* * The easiest solution would be to do all the loading inside the mutex, * but that would lead to scalability problems. So we let the loading * happen outside the mutex, and if multiple threads happen to load * the same image, we discard all but the first copy. */ mono_images_lock (); image = (MonoImage *)g_hash_table_lookup (loaded_images, absfname); g_free (absfname); if (image) { // Image already loaded mono_image_addref (image); mono_images_unlock (); return image; } mono_images_unlock (); // Image not loaded, load it now image = do_mono_image_open (alc, fname, status, TRUE, TRUE, FALSE); if (image == NULL) return NULL; return register_image (li, image); } MonoImage * mono_image_open_a_lot (MonoAssemblyLoadContext *alc, const char *fname, MonoImageOpenStatus *status) { MonoLoadedImages *li = mono_alc_get_loaded_images (alc); return mono_image_open_a_lot_parameterized (li, alc, fname, status); } /** * mono_image_open: * \param fname filename that points to the module we want to open * \param status An error condition is returned in this field * \returns An open image of type \c MonoImage or NULL on error. * The caller holds a temporary reference to the returned image which should be cleared * when no longer needed by calling \c mono_image_close. * if NULL, then check the value of \p status for details on the error */ MonoImage * mono_image_open (const char *fname, MonoImageOpenStatus *status) { return mono_image_open_a_lot (mono_alc_get_default (), fname, status); } /** * mono_pe_file_open: * \param fname filename that points to the module we want to open * \param status An error condition is returned in this field * \returns An open image of type \c MonoImage or NULL on error. if * NULL, then check the value of \p status for details on the error. * This variant for \c mono_image_open DOES NOT SET UP CLI METADATA. * It's just a PE file loader, used for \c FileVersionInfo. It also does * not use the image cache. */ MonoImage * mono_pe_file_open (const char *fname, MonoImageOpenStatus *status) { g_return_val_if_fail (fname != NULL, NULL); return do_mono_image_open (mono_alc_get_default (), fname, status, FALSE, TRUE, FALSE); } /** * mono_image_open_raw * \param fname filename that points to the module we want to open * \param status An error condition is returned in this field * \returns an image without loading neither pe or cli data. * Use mono_image_load_pe_data and mono_image_load_cli_data to load them. */ MonoImage * mono_image_open_raw (MonoAssemblyLoadContext *alc, const char *fname, MonoImageOpenStatus *status) { g_return_val_if_fail (fname != NULL, NULL); return do_mono_image_open (alc, fname, status, FALSE, FALSE, FALSE); } /* * mono_image_open_metadata_only: * * Open an image which contains metadata only without a PE header. */ MonoImage * mono_image_open_metadata_only (MonoAssemblyLoadContext *alc, const char *fname, MonoImageOpenStatus *status) { return do_mono_image_open (alc, fname, status, TRUE, TRUE, TRUE); } /** * mono_image_fixup_vtable: */ void mono_image_fixup_vtable (MonoImage *image) { #ifdef HOST_WIN32 MonoCLIImageInfo *iinfo; MonoPEDirEntry *de; MonoVTableFixup *vtfixup; int count; gpointer slot; guint16 slot_type; int slot_count; g_assert (m_image_is_module_handle (image)); iinfo = image->image_info; de = &iinfo->cli_cli_header.ch_vtable_fixups; if (!de->rva || !de->size) return; vtfixup = (MonoVTableFixup*) mono_image_rva_map (image, de->rva); if (!vtfixup) return; count = de->size / sizeof (MonoVTableFixup); while (count--) { if (!vtfixup->rva || !vtfixup->count) continue; slot = mono_image_rva_map (image, vtfixup->rva); g_assert (slot); slot_type = vtfixup->type; slot_count = vtfixup->count; if (slot_type & VTFIXUP_TYPE_32BIT) while (slot_count--) { *((guint32*) slot) = (guint32)(gsize)mono_marshal_get_vtfixup_ftnptr (image, *((guint32*) slot), slot_type); slot = ((guint32*) slot) + 1; } else if (slot_type & VTFIXUP_TYPE_64BIT) while (slot_count--) { *((guint64*) slot) = (guint64) mono_marshal_get_vtfixup_ftnptr (image, *((guint64*) slot), slot_type); slot = ((guint32*) slot) + 1; } else g_assert_not_reached(); vtfixup++; } #else g_assert_not_reached(); #endif } static void free_hash_table (gpointer key, gpointer val, gpointer user_data) { g_hash_table_destroy ((GHashTable*)val); } /* static void free_mr_signatures (gpointer key, gpointer val, gpointer user_data) { mono_metadata_free_method_signature ((MonoMethodSignature*)val); } */ static void free_array_cache_entry (gpointer key, gpointer val, gpointer user_data) { g_slist_free ((GSList*)val); } /** * mono_image_addref: * \param image The image file we wish to add a reference to * Increases the reference count of an image. */ void mono_image_addref (MonoImage *image) { mono_atomic_inc_i32 (&image->ref_count); } void mono_dynamic_stream_reset (MonoDynamicStream* stream) { stream->alloc_size = stream->index = stream->offset = 0; g_free (stream->data); stream->data = NULL; if (stream->hash) { g_hash_table_destroy (stream->hash); stream->hash = NULL; } } static void free_hash (GHashTable *hash) { if (hash) g_hash_table_destroy (hash); } void mono_wrapper_caches_free (MonoWrapperCaches *cache) { free_hash (cache->delegate_invoke_cache); free_hash (cache->delegate_begin_invoke_cache); free_hash (cache->delegate_end_invoke_cache); free_hash (cache->delegate_bound_static_invoke_cache); free_hash (cache->runtime_invoke_signature_cache); free_hash (cache->delegate_abstract_invoke_cache); free_hash (cache->runtime_invoke_method_cache); free_hash (cache->managed_wrapper_cache); free_hash (cache->native_wrapper_cache); free_hash (cache->native_wrapper_aot_cache); free_hash (cache->native_wrapper_check_cache); free_hash (cache->native_wrapper_aot_check_cache); free_hash (cache->native_func_wrapper_aot_cache); free_hash (cache->native_func_wrapper_indirect_cache); free_hash (cache->synchronized_cache); free_hash (cache->unbox_wrapper_cache); free_hash (cache->cominterop_invoke_cache); free_hash (cache->cominterop_wrapper_cache); free_hash (cache->thunk_invoke_cache); } static void mono_image_close_except_pools_all (MonoImage**images, int image_count) { for (int i = 0; i < image_count; ++i) { if (images [i]) { if (!mono_image_close_except_pools (images [i])) images [i] = NULL; } } } /* * Returns whether mono_image_close_finish() must be called as well. * We must unload images in two steps because clearing the domain in * SGen requires the class metadata to be intact, but we need to free * the mono_g_hash_tables in case a collection occurs during domain * unloading and the roots would trip up the GC. */ gboolean mono_image_close_except_pools (MonoImage *image) { int i; g_return_val_if_fail (image != NULL, FALSE); if (!mono_loaded_images_remove_image (image)) return FALSE; #ifdef HOST_WIN32 if (m_image_is_module_handle (image) && m_image_has_entry_point (image)) { mono_images_lock (); if (image->ref_count == 0) { /* Image will be closed by _CorDllMain. */ FreeLibrary ((HMODULE) image->raw_data); mono_images_unlock (); return FALSE; } mono_images_unlock (); } #endif MONO_PROFILER_RAISE (image_unloading, (image)); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_ASSEMBLY, "Unloading image %s [%p].", image->name, image); mono_image_invoke_unload_hook (image); mono_metadata_update_cleanup_on_close (image); /* * The caches inside a MonoImage might refer to metadata which is stored in referenced * assemblies, so we can't release these references in mono_assembly_close () since the * MonoImage might outlive its associated MonoAssembly. */ if (image->references && !image_is_dynamic (image)) { for (i = 0; i < image->nreferences; i++) { if (image->references [i] && image->references [i] != REFERENCE_MISSING) { if (!mono_assembly_close_except_image_pools (image->references [i])) image->references [i] = NULL; } } } else { if (image->references) { g_free (image->references); image->references = NULL; } } /* a MonoDynamicImage doesn't have any storage */ g_assert (image_is_dynamic (image) || image->storage != NULL); if (image->storage && m_image_is_raw_data_allocated (image)) { /* FIXME: do we need this? (image is disposed anyway) */ /* image->raw_metadata and cli_sections might lie inside image->raw_data */ MonoCLIImageInfo *ii = image->image_info; if ((image->raw_metadata > image->raw_data) && (image->raw_metadata <= (image->raw_data + image->raw_data_len))) image->raw_metadata = NULL; for (i = 0; i < ii->cli_section_count; i++) if (((char*)(ii->cli_sections [i]) > image->raw_data) && ((char*)(ii->cli_sections [i]) <= ((char*)image->raw_data + image->raw_data_len))) ii->cli_sections [i] = NULL; } if (image->storage) mono_image_storage_close (image->storage); if (debug_assembly_unload) { char *old_name = image->name; image->name = g_strdup_printf ("%s - UNLOADED", old_name); g_free (old_name); g_free (image->filename); image->filename = NULL; } else { g_free (image->name); g_free (image->filename); g_free (image->guid); g_free (image->version); } if (image->method_cache) g_hash_table_destroy (image->method_cache); if (image->methodref_cache) g_hash_table_destroy (image->methodref_cache); mono_internal_hash_table_destroy (&image->class_cache); mono_conc_hashtable_destroy (image->field_cache); if (image->array_cache) { g_hash_table_foreach (image->array_cache, free_array_cache_entry, NULL); g_hash_table_destroy (image->array_cache); } if (image->szarray_cache) g_hash_table_destroy (image->szarray_cache); if (image->ptr_cache) g_hash_table_destroy (image->ptr_cache); if (image->name_cache) { g_hash_table_foreach (image->name_cache, free_hash_table, NULL); g_hash_table_destroy (image->name_cache); } free_hash (image->icall_wrapper_cache); if (image->var_gparam_cache) mono_conc_hashtable_destroy (image->var_gparam_cache); if (image->mvar_gparam_cache) mono_conc_hashtable_destroy (image->mvar_gparam_cache); free_hash (image->wrapper_param_names); free_hash (image->native_func_wrapper_cache); mono_conc_hashtable_destroy (image->typespec_cache); #ifdef ENABLE_WEAK_ATTR free_hash (image->weak_field_indexes); #endif mono_wrapper_caches_free (&image->wrapper_caches); /* The ownership of signatures is not well defined */ g_hash_table_destroy (image->memberref_signatures); g_hash_table_destroy (image->method_signatures); if (image->rgctx_template_hash) g_hash_table_destroy (image->rgctx_template_hash); if (image->property_hash) mono_property_hash_destroy (image->property_hash); /* reflection_info_unregister_classes is only required by dynamic images, which will not be properly cleared during shutdown as we don't perform regular appdomain unload for the root one. */ g_assert (!image->reflection_info_unregister_classes || mono_runtime_is_shutting_down ()); image->reflection_info_unregister_classes = NULL; if (image->interface_bitset) { mono_unload_interface_ids (image->interface_bitset); mono_bitset_free (image->interface_bitset); } if (image->image_info){ MonoCLIImageInfo *ii = image->image_info; g_free (ii->cli_section_tables); g_free (ii->cli_sections); g_free (image->image_info); } mono_image_close_except_pools_all (image->files, image->file_count); mono_image_close_except_pools_all (image->modules, image->module_count); g_free (image->modules_loaded); if (image->has_updates) mono_metadata_update_image_close_except_pools_all (image); mono_os_mutex_destroy (&image->szarray_cache_lock); mono_os_mutex_destroy (&image->lock); /*g_print ("destroy image %p (dynamic: %d)\n", image, image->dynamic);*/ if (image_is_dynamic (image)) { /* Dynamic images are GC_MALLOCed */ g_free ((char*)image->module_name); mono_dynamic_image_free ((MonoDynamicImage*)image); } MONO_PROFILER_RAISE (image_unloaded, (image)); return TRUE; } static void mono_image_close_all (MonoImage**images, int image_count) { for (int i = 0; i < image_count; ++i) { if (images [i]) mono_image_close_finish (images [i]); } if (images) g_free (images); } void mono_image_close_finish (MonoImage *image) { int i; if (image->references && !image_is_dynamic (image)) { for (i = 0; i < image->nreferences; i++) { if (image->references [i] && image->references [i] != REFERENCE_MISSING) mono_assembly_close_finish (image->references [i]); } g_free (image->references); image->references = NULL; } mono_image_close_all (image->files, image->file_count); mono_image_close_all (image->modules, image->module_count); mono_metadata_update_image_close_all (image); #ifndef DISABLE_PERFCOUNTERS /* FIXME: use an explicit subtraction method as soon as it's available */ mono_atomic_fetch_add_i32 (&mono_perfcounters->loader_bytes, -1 * mono_mempool_get_allocated (image->mempool)); #endif if (!image_is_dynamic (image)) { if (debug_assembly_unload) mono_mempool_invalidate (image->mempool); else { mono_mempool_destroy (image->mempool); g_free (image); } } else { if (debug_assembly_unload) mono_mempool_invalidate (image->mempool); else { mono_mempool_destroy (image->mempool); mono_dynamic_image_free_image ((MonoDynamicImage*)image); } } } /** * mono_image_close: * \param image The image file we wish to close * Closes an image file, deallocates all memory consumed and * unmaps all possible sections of the file */ void mono_image_close (MonoImage *image) { if (mono_image_close_except_pools (image)) mono_image_close_finish (image); } /** * mono_image_strerror: * \param status an code indicating the result from a recent operation * \returns a string describing the error */ const char * mono_image_strerror (MonoImageOpenStatus status) { switch (status){ case MONO_IMAGE_OK: return "success"; case MONO_IMAGE_ERROR_ERRNO: return strerror (errno); case MONO_IMAGE_IMAGE_INVALID: return "File does not contain a valid CIL image"; case MONO_IMAGE_MISSING_ASSEMBLYREF: return "An assembly was referenced, but could not be found"; } return "Internal error"; } static gpointer mono_image_walk_resource_tree (MonoCLIImageInfo *info, guint32 res_id, guint32 lang_id, gunichar2 *name, MonoPEResourceDirEntry *entry, MonoPEResourceDir *root, guint32 level) { gboolean is_string, is_dir; guint32 name_offset, dir_offset; /* Level 0 holds a directory entry for each type of resource * (identified by ID or name). * * Level 1 holds a directory entry for each named resource * item, and each "anonymous" item of a particular type of * resource. * * Level 2 holds a directory entry for each language pointing to * the actual data. */ is_string = MONO_PE_RES_DIR_ENTRY_NAME_IS_STRING (*entry); name_offset = MONO_PE_RES_DIR_ENTRY_NAME_OFFSET (*entry); is_dir = MONO_PE_RES_DIR_ENTRY_IS_DIR (*entry); dir_offset = MONO_PE_RES_DIR_ENTRY_DIR_OFFSET (*entry); if(level==0) { if (is_string) return NULL; } else if (level==1) { if (res_id != name_offset) return NULL; #if 0 if(name!=NULL && is_string==TRUE && name!=lookup (name_offset)) { return(NULL); } #endif } else if (level==2) { if (is_string || (lang_id != 0 && name_offset != lang_id)) return NULL; } else { g_assert_not_reached (); } if (is_dir) { MonoPEResourceDir *res_dir=(MonoPEResourceDir *)(((char *)root)+dir_offset); MonoPEResourceDirEntry *sub_entries=(MonoPEResourceDirEntry *)(res_dir+1); guint32 entries, i; entries = GUINT16_FROM_LE (res_dir->res_named_entries) + GUINT16_FROM_LE (res_dir->res_id_entries); for(i=0; i<entries; i++) { MonoPEResourceDirEntry *sub_entry=&sub_entries[i]; gpointer ret; ret=mono_image_walk_resource_tree (info, res_id, lang_id, name, sub_entry, root, level+1); if(ret!=NULL) { return(ret); } } return(NULL); } else { MonoPEResourceDataEntry *data_entry=(MonoPEResourceDataEntry *)((char *)(root)+dir_offset); MonoPEResourceDataEntry *res; res = g_new0 (MonoPEResourceDataEntry, 1); res->rde_data_offset = GUINT32_TO_LE (data_entry->rde_data_offset); res->rde_size = GUINT32_TO_LE (data_entry->rde_size); res->rde_codepage = GUINT32_TO_LE (data_entry->rde_codepage); res->rde_reserved = GUINT32_TO_LE (data_entry->rde_reserved); return (res); } } /** * mono_image_lookup_resource: * \param image the image to look up the resource in * \param res_id A \c MONO_PE_RESOURCE_ID_ that represents the resource ID to lookup. * \param lang_id The language id. * \param name the resource name to lookup. * \returns NULL if not found, otherwise a pointer to the in-memory representation * of the given resource. The caller should free it using \c g_free when no longer * needed. */ gpointer mono_image_lookup_resource (MonoImage *image, guint32 res_id, guint32 lang_id, gunichar2 *name) { MonoCLIImageInfo *info; MonoDotNetHeader *header; MonoPEDatadir *datadir; MonoPEDirEntry *rsrc; MonoPEResourceDir *resource_dir; MonoPEResourceDirEntry *res_entries; guint32 entries, i; if(image==NULL) { return(NULL); } mono_image_ensure_section_idx (image, MONO_SECTION_RSRC); info = (MonoCLIImageInfo *)image->image_info; if(info==NULL) { return(NULL); } header=&info->cli_header; if(header==NULL) { return(NULL); } datadir=&header->datadir; if(datadir==NULL) { return(NULL); } rsrc=&datadir->pe_resource_table; if(rsrc==NULL) { return(NULL); } resource_dir=(MonoPEResourceDir *)mono_image_rva_map (image, rsrc->rva); if(resource_dir==NULL) { return(NULL); } entries = GUINT16_FROM_LE (resource_dir->res_named_entries) + GUINT16_FROM_LE (resource_dir->res_id_entries); res_entries=(MonoPEResourceDirEntry *)(resource_dir+1); for(i=0; i<entries; i++) { MonoPEResourceDirEntry *entry=&res_entries[i]; gpointer ret; ret=mono_image_walk_resource_tree (info, res_id, lang_id, name, entry, resource_dir, 0); if(ret!=NULL) { return(ret); } } return(NULL); } /** * mono_image_get_entry_point: * \param image the image where the entry point will be looked up. * Use this routine to determine the metadata token for method that * has been flagged as the entry point. * \returns the token for the entry point method in the image */ guint32 mono_image_get_entry_point (MonoImage *image) { return image->image_info->cli_cli_header.ch_entry_point; } /** * mono_image_get_resource: * \param image the image where the resource will be looked up. * \param offset The offset to add to the resource * \param size a pointer to an int where the size of the resource will be stored * * This is a low-level routine that fetches a resource from the * metadata that starts at a given \p offset. The \p size parameter is * filled with the data field as encoded in the metadata. * * \returns the pointer to the resource whose offset is \p offset. */ const char* mono_image_get_resource (MonoImage *image, guint32 offset, guint32 *size) { MonoCLIImageInfo *iinfo = image->image_info; MonoCLIHeader *ch = &iinfo->cli_cli_header; const char* data; if (!ch->ch_resources.rva || offset + 4 > ch->ch_resources.size) return NULL; data = mono_image_rva_map (image, ch->ch_resources.rva); if (!data) return NULL; data += offset; if (size) *size = read32 (data); data += 4; return data; } // Returning NULL with no error set will be interpeted as "not found" MonoImage* mono_image_load_file_for_image_checked (MonoImage *image, int fileidx, MonoError *error) { char *base_dir, *name; MonoImage *res; MonoTableInfo *t = &image->tables [MONO_TABLE_FILE]; const char *fname; guint32 fname_id; error_init (error); if (fileidx < 1 || fileidx > table_info_get_rows (t)) return NULL; mono_image_lock (image); if (image->files && image->files [fileidx - 1]) { mono_image_unlock (image); return image->files [fileidx - 1]; } mono_image_unlock (image); fname_id = mono_metadata_decode_row_col (t, fileidx - 1, MONO_FILE_NAME); fname = mono_metadata_string_heap (image, fname_id); base_dir = g_path_get_dirname (image->name); name = g_build_filename (base_dir, fname, (const char*)NULL); res = mono_image_open (name, NULL); if (!res) goto done; mono_image_lock (image); if (image->files && image->files [fileidx - 1]) { MonoImage *old = res; res = image->files [fileidx - 1]; mono_image_unlock (image); mono_image_close (old); } else { int i; /* g_print ("loaded file %s from %s (%p)\n", name, image->name, image->assembly); */ if (!assign_assembly_parent_for_netmodule (res, image, error)) { mono_image_unlock (image); mono_image_close (res); return NULL; } for (i = 0; i < res->module_count; ++i) { if (res->modules [i] && !res->modules [i]->assembly) res->modules [i]->assembly = image->assembly; } if (!image->files) { int n = table_info_get_rows (t); image->files = g_new0 (MonoImage*, n); image->file_count = n; } image->files [fileidx - 1] = res; mono_image_unlock (image); /* vtable fixup can't happen with the image lock held */ #ifdef HOST_WIN32 if (m_image_is_module_handle (res)) mono_image_fixup_vtable (res); #endif } done: g_free (name); g_free (base_dir); return res; } /** * mono_image_load_file_for_image: */ MonoImage* mono_image_load_file_for_image (MonoImage *image, int fileidx) { ERROR_DECL (error); MonoImage *result = mono_image_load_file_for_image_checked (image, fileidx, error); mono_error_assert_ok (error); return result; } /** * mono_image_get_strong_name: * \param image a MonoImage * \param size a \c guint32 pointer, or NULL. * * If the image has a strong name, and \p size is not NULL, the value * pointed to by size will have the size of the strong name. * * \returns NULL if the image does not have a strong name, or a * pointer to the public key. */ const char* mono_image_get_strong_name (MonoImage *image, guint32 *size) { MonoCLIImageInfo *iinfo = image->image_info; MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name; const char* data; if (!de->size || !de->rva) return NULL; data = mono_image_rva_map (image, de->rva); if (!data) return NULL; if (size) *size = de->size; return data; } /** * mono_image_strong_name_position: * \param image a \c MonoImage * \param size a \c guint32 pointer, or NULL. * * If the image has a strong name, and \p size is not NULL, the value * pointed to by size will have the size of the strong name. * * \returns the position within the image file where the strong name * is stored. */ guint32 mono_image_strong_name_position (MonoImage *image, guint32 *size) { MonoCLIImageInfo *iinfo = image->image_info; MonoPEDirEntry *de = &iinfo->cli_cli_header.ch_strong_name; guint32 pos; if (size) *size = de->size; if (!de->size || !de->rva) return 0; pos = mono_cli_rva_image_map (image, de->rva); return pos == INVALID_ADDRESS ? 0 : pos; } /** * mono_image_get_public_key: * \param image a \c MonoImage * \param size a \c guint32 pointer, or NULL. * * This is used to obtain the public key in the \p image. * * If the image has a public key, and \p size is not NULL, the value * pointed to by size will have the size of the public key. * * \returns NULL if the image does not have a public key, or a pointer * to the public key. */ const char* mono_image_get_public_key (MonoImage *image, guint32 *size) { const char *pubkey; guint32 len, tok; if (image_is_dynamic (image)) { if (size) *size = ((MonoDynamicImage*)image)->public_key_len; return (char*)((MonoDynamicImage*)image)->public_key; } if (table_info_get_rows (&image->tables [MONO_TABLE_ASSEMBLY]) != 1) return NULL; tok = mono_metadata_decode_row_col (&image->tables [MONO_TABLE_ASSEMBLY], 0, MONO_ASSEMBLY_PUBLIC_KEY); if (!tok) return NULL; pubkey = mono_metadata_blob_heap (image, tok); len = mono_metadata_decode_blob_size (pubkey, &pubkey); if (size) *size = len; return pubkey; } /** * mono_image_get_name: * \param name a \c MonoImage * \returns the name of the assembly. */ const char* mono_image_get_name (MonoImage *image) { return image->assembly_name; } /** * mono_image_get_filename: * \param image a \c MonoImage * Used to get the filename that hold the actual \c MonoImage * \returns the filename. */ const char* mono_image_get_filename (MonoImage *image) { return image->name; } /** * mono_image_get_guid: */ const char* mono_image_get_guid (MonoImage *image) { return image->guid; } /** * mono_image_get_table_info: */ const MonoTableInfo* mono_image_get_table_info (MonoImage *image, int table_id) { if (table_id < 0 || table_id >= MONO_TABLE_NUM) return NULL; return &image->tables [table_id]; } /** * mono_image_get_table_rows: */ int mono_image_get_table_rows (MonoImage *image, int table_id) { if (table_id < 0 || table_id >= MONO_TABLE_NUM) return 0; return table_info_get_rows (&image->tables [table_id]); } /** * mono_table_info_get_rows: */ int mono_table_info_get_rows (const MonoTableInfo *table) { return table_info_get_rows (table); } /** * mono_image_get_assembly: * \param image the \c MonoImage . * Use this routine to get the assembly that owns this image. * \returns the assembly that holds this image. */ MonoAssembly* mono_image_get_assembly (MonoImage *image) { return image->assembly; } /** * mono_image_is_dynamic: * \param image the \c MonoImage * * Determines if the given image was created dynamically through the * \c System.Reflection.Emit API * \returns TRUE if the image was created dynamically, FALSE if not. */ gboolean mono_image_is_dynamic (MonoImage *image) { return image_is_dynamic (image); } /** * mono_image_has_authenticode_entry: * \param image the \c MonoImage * Use this routine to determine if the image has a Authenticode * Certificate Table. * \returns TRUE if the image contains an authenticode entry in the PE * directory. */ gboolean mono_image_has_authenticode_entry (MonoImage *image) { MonoCLIImageInfo *iinfo = image->image_info; MonoDotNetHeader *header = &iinfo->cli_header; if (!header) return FALSE; MonoPEDirEntry *de = &header->datadir.pe_certificate_table; // the Authenticode "pre" (non ASN.1) header is 8 bytes long return ((de->rva != 0) && (de->size > 8)); } gpointer mono_image_alloc (MonoImage *image, guint size) { gpointer res; #ifndef DISABLE_PERFCOUNTERS mono_atomic_fetch_add_i32 (&mono_perfcounters->loader_bytes, size); #endif mono_image_lock (image); res = mono_mempool_alloc (image->mempool, size); mono_image_unlock (image); return res; } gpointer mono_image_alloc0 (MonoImage *image, guint size) { gpointer res; #ifndef DISABLE_PERFCOUNTERS mono_atomic_fetch_add_i32 (&mono_perfcounters->loader_bytes, size); #endif mono_image_lock (image); res = mono_mempool_alloc0 (image->mempool, size); mono_image_unlock (image); return res; } char* mono_image_strdup (MonoImage *image, const char *s) { char *res; #ifndef DISABLE_PERFCOUNTERS mono_atomic_fetch_add_i32 (&mono_perfcounters->loader_bytes, (gint32)strlen (s)); #endif mono_image_lock (image); res = mono_mempool_strdup (image->mempool, s); mono_image_unlock (image); return res; } char* mono_image_strdup_vprintf (MonoImage *image, const char *format, va_list args) { char *buf; mono_image_lock (image); buf = mono_mempool_strdup_vprintf (image->mempool, format, args); mono_image_unlock (image); #ifndef DISABLE_PERFCOUNTERS mono_atomic_fetch_add_i32 (&mono_perfcounters->loader_bytes, (gint32)strlen (buf)); #endif return buf; } char* mono_image_strdup_printf (MonoImage *image, const char *format, ...) { char *buf; va_list args; va_start (args, format); buf = mono_image_strdup_vprintf (image, format, args); va_end (args); return buf; } GList* mono_g_list_prepend_image (MonoImage *image, GList *list, gpointer data) { GList *new_list; new_list = (GList *)mono_image_alloc (image, sizeof (GList)); new_list->data = data; new_list->prev = list ? list->prev : NULL; new_list->next = list; if (new_list->prev) new_list->prev->next = new_list; if (list) list->prev = new_list; return new_list; } GSList* mono_g_slist_append_image (MonoImage *image, GSList *list, gpointer data) { GSList *new_list; new_list = (GSList *)mono_image_alloc (image, sizeof (GSList)); new_list->data = data; new_list->next = NULL; return g_slist_concat (list, new_list); } void mono_image_lock (MonoImage *image) { mono_locks_os_acquire (&image->lock, ImageDataLock); } void mono_image_unlock (MonoImage *image) { mono_locks_os_release (&image->lock, ImageDataLock); } /** * mono_image_property_lookup: * Lookup a property on \p image . Used to store very rare fields of \c MonoClass and \c MonoMethod . * * LOCKING: Takes the image lock */ gpointer mono_image_property_lookup (MonoImage *image, gpointer subject, guint32 property) { gpointer res; mono_image_lock (image); res = mono_property_hash_lookup (image->property_hash, subject, property); mono_image_unlock (image); return res; } /** * mono_image_property_insert: * Insert a new property \p property with value \p value on \p subject in \p * image. Used to store very rare fields of \c MonoClass and \c MonoMethod. * * LOCKING: Takes the image lock */ void mono_image_property_insert (MonoImage *image, gpointer subject, guint32 property, gpointer value) { CHECKED_METADATA_STORE_LOCAL (image->mempool, value); mono_image_lock (image); mono_property_hash_insert (image->property_hash, subject, property, value); mono_image_unlock (image); } /** * mono_image_property_remove: * Remove all properties associated with \p subject in \p image. Used to store very rare fields of \c MonoClass and \c MonoMethod . * * LOCKING: Takes the image lock */ void mono_image_property_remove (MonoImage *image, gpointer subject) { mono_image_lock (image); mono_property_hash_remove_object (image->property_hash, subject); mono_image_unlock (image); } void mono_image_append_class_to_reflection_info_set (MonoClass *klass) { MonoImage *image = m_class_get_image (klass); g_assert (image_is_dynamic (image)); mono_image_lock (image); image->reflection_info_unregister_classes = g_slist_prepend_mempool (image->mempool, image->reflection_info_unregister_classes, klass); mono_image_unlock (image); }
1
dotnet/runtime
66,452
[mono] Stop setting time_date_stamp field in MonoImage
We never read that field in the runtime and it was causing unnecessary disk IO during startup (5ms on my iOS device). It was also never set on Windows already.
akoeplinger
2022-03-10T15:49:37Z
2022-03-10T21:47:58Z
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
d2826308964e4ee4496d6884e09811e1f709005e
[mono] Stop setting time_date_stamp field in MonoImage. We never read that field in the runtime and it was causing unnecessary disk IO during startup (5ms on my iOS device). It was also never set on Windows already.
./src/mono/mono/metadata/metadata-internals.h
/** * \file */ #ifndef __MONO_METADATA_INTERNALS_H__ #define __MONO_METADATA_INTERNALS_H__ #include "mono/utils/mono-forward-internal.h" #include "mono/metadata/image.h" #include "mono/metadata/blob.h" #include "mono/metadata/cil-coff.h" #include "mono/metadata/mempool.h" #include "mono/metadata/domain-internals.h" #include "mono/metadata/mono-hash.h" #include "mono/utils/mono-compiler.h" #include "mono/utils/mono-dl.h" #include "mono/utils/monobitset.h" #include "mono/utils/mono-property-hash.h" #include "mono/utils/mono-value-hash.h" #include <mono/utils/mono-error.h> #include "mono/utils/mono-conc-hashtable.h" #include "mono/utils/refcount.h" struct _MonoType { union { MonoClass *klass; /* for VALUETYPE and CLASS */ MonoType *type; /* for PTR */ MonoArrayType *array; /* for ARRAY */ MonoMethodSignature *method; MonoGenericParam *generic_param; /* for VAR and MVAR */ MonoGenericClass *generic_class; /* for GENERICINST */ } data; unsigned int attrs : 16; /* param attributes or field flags */ MonoTypeEnum type : 8; unsigned int has_cmods : 1; unsigned int byref__ : 1; /* don't access directly, use m_type_is_byref */ unsigned int pinned : 1; /* valid when included in a local var signature */ }; typedef struct { unsigned int required : 1; MonoType *type; } MonoSingleCustomMod; /* Aggregate custom modifiers can happen if a generic VAR or MVAR is inflated, * and both the VAR and the type that will be used to inflated it have custom * modifiers, but they come from different images. (e.g. inflating 'class G<T> * {void Test (T modopt(IsConst) t);}' with 'int32 modopt(IsLong)' where G is * in image1 and the int32 is in image2.) * * Moreover, we can't just store an image and a type token per modifier, because * Roslyn and C++/CLI sometimes create modifiers that mention generic parameters that must be inflated, like: * void .CL1`1.Test(!0 modopt(System.Nullable`1<!0>)) * So we have to store a resolved MonoType*. * * Because the types come from different images, we allocate the aggregate * custom modifiers container object in the mempool of a MonoImageSet to ensure * that it doesn't have dangling image pointers. */ typedef struct { uint8_t count; MonoSingleCustomMod modifiers[1]; /* Actual length is count */ } MonoAggregateModContainer; /* ECMA says upto 64 custom modifiers. It's possible we could see more at * runtime due to modifiers being appended together when we inflate type. In * that case we should revisit the places where this define is used to make * sure that we don't blow up the stack (or switch to heap allocation for * temporaries). */ #define MONO_MAX_EXPECTED_CMODS 64 typedef struct { MonoType unmodified; gboolean is_aggregate; union { MonoCustomModContainer cmods; /* the actual aggregate modifiers are in a MonoImageSet mempool * that includes all the images of all the modifier types and * also the type that this aggregate container is a part of.*/ MonoAggregateModContainer *amods; } mods; } MonoTypeWithModifiers; gboolean mono_type_is_aggregate_mods (const MonoType *t); static inline void mono_type_with_mods_init (MonoType *dest, uint8_t num_mods, gboolean is_aggregate) { if (num_mods == 0) { dest->has_cmods = 0; return; } dest->has_cmods = 1; MonoTypeWithModifiers *dest_full = (MonoTypeWithModifiers *)dest; dest_full->is_aggregate = !!is_aggregate; if (is_aggregate) dest_full->mods.amods = NULL; else dest_full->mods.cmods.count = num_mods; } MonoCustomModContainer * mono_type_get_cmods (const MonoType *t); MonoAggregateModContainer * mono_type_get_amods (const MonoType *t); void mono_type_set_amods (MonoType *t, MonoAggregateModContainer *amods); static inline uint8_t mono_type_custom_modifier_count (const MonoType *t) { if (!t->has_cmods) return 0; MonoTypeWithModifiers *full = (MonoTypeWithModifiers *)t; if (full->is_aggregate) return full->mods.amods->count; else return full->mods.cmods.count; } MonoType * mono_type_get_custom_modifier (const MonoType *ty, uint8_t idx, gboolean *required, MonoError *error); // Note: sizeof (MonoType) is dangerous. It can copy the num_mods // field without copying the variably sized array. This leads to // memory unsafety on the stack and/or heap, when we try to traverse // this array. // // Use mono_sizeof_monotype // to get the size of the memory to copy. #define MONO_SIZEOF_TYPE sizeof (MonoType) size_t mono_sizeof_type_with_mods (uint8_t num_mods, gboolean aggregate); size_t mono_sizeof_type (const MonoType *ty); size_t mono_sizeof_aggregate_modifiers (uint8_t num_mods); MonoAggregateModContainer * mono_metadata_get_canonical_aggregate_modifiers (MonoAggregateModContainer *candidate); #define MONO_PUBLIC_KEY_TOKEN_LENGTH 17 #define MONO_PROCESSOR_ARCHITECTURE_NONE 0 #define MONO_PROCESSOR_ARCHITECTURE_MSIL 1 #define MONO_PROCESSOR_ARCHITECTURE_X86 2 #define MONO_PROCESSOR_ARCHITECTURE_IA64 3 #define MONO_PROCESSOR_ARCHITECTURE_AMD64 4 #define MONO_PROCESSOR_ARCHITECTURE_ARM 5 struct _MonoAssemblyName { const char *name; const char *culture; const char *hash_value; const mono_byte* public_key; // string of 16 hex chars + 1 NULL mono_byte public_key_token [MONO_PUBLIC_KEY_TOKEN_LENGTH]; uint32_t hash_alg; uint32_t hash_len; uint32_t flags; int32_t major, minor, build, revision, arch; //Add members for correct work with mono_stringify_assembly_name MonoBoolean without_version; MonoBoolean without_culture; MonoBoolean without_public_key_token; }; struct MonoTypeNameParse { char *name_space; char *name; MonoAssemblyName assembly; GList *modifiers; /* 0 -> byref, -1 -> pointer, > 0 -> array rank */ GPtrArray *type_arguments; GList *nested; }; typedef struct _MonoAssemblyContext { /* Don't fire managed load event for this assembly */ guint8 no_managed_load_event : 1; } MonoAssemblyContext; struct _MonoAssembly { /* * The number of appdomains which have this assembly loaded plus the number of * assemblies referencing this assembly through an entry in their image->references * arrays. The latter is needed because entries in the image->references array * might point to assemblies which are only loaded in some appdomains, and without * the additional reference, they can be freed at any time. * The ref_count is initially 0. */ gint32 ref_count; /* use atomic operations only */ char *basedir; MonoAssemblyName aname; MonoImage *image; GSList *friend_assembly_names; /* Computed by mono_assembly_load_friends () */ GSList *ignores_checks_assembly_names; /* Computed by mono_assembly_load_friends () */ guint8 friend_assembly_names_inited; guint8 dynamic; MonoAssemblyContext context; guint8 wrap_non_exception_throws; guint8 wrap_non_exception_throws_inited; guint8 jit_optimizer_disabled; guint8 jit_optimizer_disabled_inited; guint8 runtime_marshalling_enabled; guint8 runtime_marshalling_enabled_inited; }; typedef struct { const char* data; guint32 size; } MonoStreamHeader; struct _MonoTableInfo { const char *base; guint rows_ : 24; /* don't access directly, use table_info_get_rows */ guint row_size : 8; /* * Tables contain up to 9 columns and the possible sizes of the * fields in the documentation are 1, 2 and 4 bytes. So we * can encode in 2 bits the size. * * A 32 bit value can encode the resulting size * * The top eight bits encode the number of columns in the table. * we only need 4, but 8 is aligned no shift required. */ guint32 size_bitfield; }; #define REFERENCE_MISSING ((gpointer) -1) typedef struct { gboolean (*match) (MonoImage*); gboolean (*load_pe_data) (MonoImage*); gboolean (*load_cli_data) (MonoImage*); gboolean (*load_tables) (MonoImage*); } MonoImageLoader; /* Represents the physical bytes for an image (usually in the file system, but * could be in memory). * * The MonoImageStorage owns the raw data for an image and is responsible for * cleanup. * * May be shared by multiple MonoImage objects if they opened the same * underlying file or byte blob in memory. * * There is an abstract string key (usually a file path, but could be formed in * other ways) that is used to share MonoImageStorage objects among images. * */ typedef struct { MonoRefCount ref; /* key used for lookups. owned by this image storage. */ char *key; /* If the raw data was allocated from a source such as mmap, the allocator may store resource tracking information here. */ void *raw_data_handle; char *raw_data; guint32 raw_data_len; /* data was allocated with mono_file_map and must be unmapped */ guint8 raw_buffer_used : 1; /* data was allocated with malloc and must be freed */ guint8 raw_data_allocated : 1; /* data was allocated with mono_file_map_fileio */ guint8 fileio_used : 1; #ifdef HOST_WIN32 /* Module was loaded using LoadLibrary. */ guint8 is_module_handle : 1; /* Module entry point is _CorDllMain. */ guint8 has_entry_point : 1; #endif } MonoImageStorage; struct _MonoImage { /* * This count is incremented during these situations: * - An assembly references this MonoImage through its 'image' field * - This MonoImage is present in the 'files' field of an image * - This MonoImage is present in the 'modules' field of an image * - A thread is holding a temporary reference to this MonoImage between * calls to mono_image_open and mono_image_close () */ int ref_count; MonoImageStorage *storage; /* Aliases storage->raw_data when storage is non-NULL. Otherwise NULL. */ char *raw_data; guint32 raw_data_len; /* Whenever this is a dynamically emitted module */ guint8 dynamic : 1; /* Whenever this image contains uncompressed metadata */ guint8 uncompressed_metadata : 1; /* Whenever this image contains metadata only without PE data */ guint8 metadata_only : 1; guint8 checked_module_cctor : 1; guint8 has_module_cctor : 1; guint8 idx_string_wide : 1; guint8 idx_guid_wide : 1; guint8 idx_blob_wide : 1; /* NOT SUPPORTED: Whenever this image is considered as platform code for the CoreCLR security model */ guint8 core_clr_platform_code : 1; /* Whether a #JTD stream was present. Indicates that this image was a minimal delta and its heaps only include the new heap entries */ guint8 minimal_delta : 1; /* The path to the file for this image or an arbitrary name for images loaded from data. */ char *name; /* The path to the file for this image or NULL */ char *filename; /* The assembly name reported in the file for this image (expected to be NULL for a netmodule) */ const char *assembly_name; /* The module name reported in the file for this image (could be NULL for a malformed file) */ const char *module_name; guint32 time_date_stamp; char *version; gint16 md_version_major, md_version_minor; char *guid; MonoCLIImageInfo *image_info; MonoMemPool *mempool; /*protected by the image lock*/ char *raw_metadata; MonoStreamHeader heap_strings; MonoStreamHeader heap_us; MonoStreamHeader heap_blob; MonoStreamHeader heap_guid; MonoStreamHeader heap_tables; MonoStreamHeader heap_pdb; const char *tables_base; /* For PPDB files */ guint64 referenced_tables; int *referenced_table_rows; /**/ MonoTableInfo tables [MONO_TABLE_NUM]; /* * references is initialized only by using the mono_assembly_open * function, and not by using the lowlevel mono_image_open. * * Protected by the image lock. * * It is NULL terminated. */ MonoAssembly **references; int nreferences; /* Code files in the assembly. The main assembly has a "file" table and also a "module" * table, where the module table is a subset of the file table. We track both lists, * and because we can lazy-load them at different times we reference-increment both. */ /* No netmodules in netcore, but for System.Reflection.Emit support we still use modules */ MonoImage **modules; guint32 module_count; gboolean *modules_loaded; MonoImage **files; guint32 file_count; MonoAotModule *aot_module; guint8 aotid[16]; /* * The Assembly this image was loaded from. */ MonoAssembly *assembly; /* * The AssemblyLoadContext that this image was loaded into. */ MonoAssemblyLoadContext *alc; /* * Indexed by method tokens and typedef tokens. */ GHashTable *method_cache; /*protected by the image lock*/ MonoInternalHashTable class_cache; /* Indexed by memberref + methodspec tokens */ GHashTable *methodref_cache; /*protected by the image lock*/ /* * Indexed by fielddef and memberref tokens */ MonoConcurrentHashTable *field_cache; /*protected by the image lock*/ /* indexed by typespec tokens. */ MonoConcurrentHashTable *typespec_cache; /* protected by the image lock */ /* indexed by token */ GHashTable *memberref_signatures; /* Indexed by blob heap indexes */ GHashTable *method_signatures; /* * Indexes namespaces to hash tables that map class name to typedef token. */ GHashTable *name_cache; /*protected by the image lock*/ /* * Indexed by MonoClass */ GHashTable *array_cache; GHashTable *ptr_cache; GHashTable *szarray_cache; /* This has a separate lock to improve scalability */ mono_mutex_t szarray_cache_lock; /* * indexed by SignaturePointerPair */ GHashTable *native_func_wrapper_cache; /* * indexed by MonoMethod pointers */ GHashTable *wrapper_param_names; GHashTable *array_accessor_cache; GHashTable *icall_wrapper_cache; GHashTable *rgctx_template_hash; /* LOCKING: templates lock */ /* Contains rarely used fields of runtime structures belonging to this image */ MonoPropertyHash *property_hash; void *reflection_info; /* * user_info is a public field and is not touched by the * metadata engine */ void *user_info; #ifndef DISABLE_DLLMAP /* dll map entries */ MonoDllMap *dll_map; #endif /* interfaces IDs from this image */ /* protected by the classes lock */ MonoBitSet *interface_bitset; /* when the image is being closed, this is abused as a list of malloc'ed regions to be freed. */ GSList *reflection_info_unregister_classes; /* List of dependent image sets containing this image */ /* Protected by image_sets_lock */ GSList *image_sets; /* Caches for wrappers that DO NOT reference generic */ /* arguments */ MonoWrapperCaches wrapper_caches; /* Pre-allocated anon generic params for the first N generic * parameters, for a small N */ MonoGenericParam *var_gparam_cache_fast; MonoGenericParam *mvar_gparam_cache_fast; /* Anon generic parameters past N, if needed */ MonoConcurrentHashTable *var_gparam_cache; MonoConcurrentHashTable *mvar_gparam_cache; /* The loader used to load this image */ MonoImageLoader *loader; // Containers for MonoGenericParams associated with this image but not with any specific class or method. Created on demand. // This could happen, for example, for MonoTypes associated with TypeSpec table entries. MonoGenericContainer *anonymous_generic_class_container; MonoGenericContainer *anonymous_generic_method_container; #ifdef ENABLE_WEAK_ATTR gboolean weak_fields_inited; /* Contains 1 based indexes */ GHashTable *weak_field_indexes; #endif /* baseline images only: whether any metadata updates have been applied to this image */ gboolean has_updates; /* * No other runtime locks must be taken while holding this lock. * It's meant to be used only to mutate and query structures part of this image. */ mono_mutex_t lock; }; enum { MONO_SECTION_TEXT, MONO_SECTION_RSRC, MONO_SECTION_RELOC, MONO_SECTION_MAX }; typedef struct { GHashTable *hash; char *data; guint32 alloc_size; /* malloced bytes */ guint32 index; guint32 offset; /* from start of metadata */ } MonoDynamicStream; typedef struct { guint32 alloc_rows; guint32 rows; guint8 row_size; /* calculated later with column_sizes */ guint8 columns; guint32 next_idx; guint32 *values; /* rows * columns */ } MonoDynamicTable; /* "Dynamic" assemblies and images arise from System.Reflection.Emit */ struct _MonoDynamicAssembly { MonoAssembly assembly; char *strong_name; guint32 strong_name_size; }; struct _MonoDynamicImage { MonoImage image; guint32 meta_size; guint32 text_rva; guint32 metadata_rva; guint32 image_base; guint32 cli_header_offset; guint32 iat_offset; guint32 idt_offset; guint32 ilt_offset; guint32 imp_names_offset; struct { guint32 rva; guint32 size; guint32 offset; guint32 attrs; } sections [MONO_SECTION_MAX]; GHashTable *typespec; GHashTable *typeref; GHashTable *handleref; MonoGHashTable *tokens; GHashTable *blob_cache; GHashTable *standalonesig_cache; GList *array_methods; GHashTable *method_aux_hash; GHashTable *vararg_aux_hash; MonoGHashTable *generic_def_objects; gboolean initial_image; guint32 pe_kind, machine; char *strong_name; guint32 strong_name_size; char *win32_res; guint32 win32_res_size; guint8 *public_key; int public_key_len; MonoDynamicStream sheap; MonoDynamicStream code; /* used to store method headers and bytecode */ MonoDynamicStream resources; /* managed embedded resources */ MonoDynamicStream us; MonoDynamicStream blob; MonoDynamicStream tstream; MonoDynamicStream guid; MonoDynamicTable tables [MONO_TABLE_NUM]; MonoClass *wrappers_type; /*wrappers are bound to this type instead of <Module>*/ }; /* Contains information about assembly binding */ typedef struct _MonoAssemblyBindingInfo { char *name; char *culture; guchar public_key_token [MONO_PUBLIC_KEY_TOKEN_LENGTH]; int major; int minor; AssemblyVersionSet old_version_bottom; AssemblyVersionSet old_version_top; AssemblyVersionSet new_version; guint has_old_version_bottom : 1; guint has_old_version_top : 1; guint has_new_version : 1; guint is_valid : 1; gint32 domain_id; /*Needed to unload per-domain binding*/ } MonoAssemblyBindingInfo; struct _MonoMethodHeader { const unsigned char *code; #ifdef MONO_SMALL_CONFIG guint16 code_size; #else guint32 code_size; #endif guint16 max_stack : 15; unsigned int is_transient: 1; /* mono_metadata_free_mh () will actually free this header */ unsigned int num_clauses : 15; /* if num_locals != 0, then the following apply: */ unsigned int init_locals : 1; guint16 num_locals; MonoExceptionClause *clauses; MonoBitSet *volatile_args; MonoBitSet *volatile_locals; MonoType *locals [MONO_ZERO_LEN_ARRAY]; }; typedef struct { const unsigned char *code; guint32 code_size; guint16 max_stack; gboolean has_clauses; gboolean has_locals; } MonoMethodHeaderSummary; // FIXME? offsetof (MonoMethodHeader, locals)? #define MONO_SIZEOF_METHOD_HEADER (sizeof (struct _MonoMethodHeader) - MONO_ZERO_LEN_ARRAY * SIZEOF_VOID_P) struct _MonoMethodSignature { MonoType *ret; #ifdef MONO_SMALL_CONFIG guint8 param_count; gint8 sentinelpos; unsigned int generic_param_count : 5; #else guint16 param_count; gint16 sentinelpos; unsigned int generic_param_count : 16; #endif unsigned int call_convention : 6; unsigned int hasthis : 1; unsigned int explicit_this : 1; unsigned int pinvoke : 1; unsigned int is_inflated : 1; unsigned int has_type_parameters : 1; unsigned int suppress_gc_transition : 1; unsigned int marshalling_disabled : 1; MonoType *params [MONO_ZERO_LEN_ARRAY]; }; /* * AOT cache configuration loaded from config files. * Doesn't really belong here. */ typedef struct { /* * Enable aot caching for applications whose main assemblies are in * this list. */ GSList *apps; GSList *assemblies; char *aot_options; } MonoAotCacheConfig; #define MONO_SIZEOF_METHOD_SIGNATURE (sizeof (struct _MonoMethodSignature) - MONO_ZERO_LEN_ARRAY * SIZEOF_VOID_P) static inline gboolean image_is_dynamic (MonoImage *image) { #ifdef DISABLE_REFLECTION_EMIT return FALSE; #else return image->dynamic; #endif } static inline gboolean assembly_is_dynamic (MonoAssembly *assembly) { #ifdef DISABLE_REFLECTION_EMIT return FALSE; #else return assembly->dynamic; #endif } static inline int table_info_get_rows (const MonoTableInfo *table) { return table->rows_; } /* for use with allocated memory blocks (assumes alignment is to 8 bytes) */ MONO_COMPONENT_API guint mono_aligned_addr_hash (gconstpointer ptr); void mono_image_check_for_module_cctor (MonoImage *image); gpointer mono_image_alloc (MonoImage *image, guint size); gpointer mono_image_alloc0 (MonoImage *image, guint size); #define mono_image_new0(image,type,size) ((type *) mono_image_alloc0 (image, sizeof (type)* (size))) char* mono_image_strdup (MonoImage *image, const char *s); char* mono_image_strdup_vprintf (MonoImage *image, const char *format, va_list args); char* mono_image_strdup_printf (MonoImage *image, const char *format, ...) MONO_ATTR_FORMAT_PRINTF(2,3); GList* mono_g_list_prepend_image (MonoImage *image, GList *list, gpointer data); GSList* mono_g_slist_append_image (MonoImage *image, GSList *list, gpointer data); MONO_COMPONENT_API void mono_image_lock (MonoImage *image); MONO_COMPONENT_API void mono_image_unlock (MonoImage *image); gpointer mono_image_property_lookup (MonoImage *image, gpointer subject, guint32 property); void mono_image_property_insert (MonoImage *image, gpointer subject, guint32 property, gpointer value); void mono_image_property_remove (MonoImage *image, gpointer subject); MONO_COMPONENT_API gboolean mono_image_close_except_pools (MonoImage *image); MONO_COMPONENT_API void mono_image_close_finish (MonoImage *image); typedef void (*MonoImageUnloadFunc) (MonoImage *image, gpointer user_data); void mono_install_image_unload_hook (MonoImageUnloadFunc func, gpointer user_data); void mono_remove_image_unload_hook (MonoImageUnloadFunc func, gpointer user_data); void mono_install_image_loader (const MonoImageLoader *loader); void mono_image_append_class_to_reflection_info_set (MonoClass *klass); typedef struct _MonoMetadataUpdateData MonoMetadataUpdateData; struct _MonoMetadataUpdateData { int has_updates; }; extern MonoMetadataUpdateData mono_metadata_update_data_private; /* returns TRUE if there's at least one update */ static inline gboolean mono_metadata_has_updates (void) { return mono_metadata_update_data_private.has_updates != 0; } /* components can't call the inline function directly since the private data isn't exported */ MONO_COMPONENT_API gboolean mono_metadata_has_updates_api (void); void mono_image_effective_table_slow (const MonoTableInfo **t, int idx); gboolean mono_metadata_update_has_modified_rows (const MonoTableInfo *t); static inline void mono_image_effective_table (const MonoTableInfo **t, int idx) { if (G_UNLIKELY (mono_metadata_has_updates ())) { if (G_UNLIKELY (idx >= table_info_get_rows ((*t)) || mono_metadata_update_has_modified_rows (*t))) { mono_image_effective_table_slow (t, idx); } } } enum MonoEnCDeltaOrigin { MONO_ENC_DELTA_API = 0, MONO_ENC_DELTA_DBG = 1, }; MONO_COMPONENT_API void mono_image_load_enc_delta (int delta_origin, MonoImage *base_image, gconstpointer dmeta, uint32_t dmeta_len, gconstpointer dil, uint32_t dil_len, gconstpointer dpdb, uint32_t dpdb_len, MonoError *error); gboolean mono_image_load_cli_header (MonoImage *image, MonoCLIImageInfo *iinfo); gboolean mono_image_load_metadata (MonoImage *image, MonoCLIImageInfo *iinfo); const char* mono_metadata_string_heap_checked (MonoImage *meta, uint32_t table_index, MonoError *error); const char * mono_metadata_blob_heap_null_ok (MonoImage *meta, guint32 index); const char* mono_metadata_blob_heap_checked (MonoImage *meta, uint32_t table_index, MonoError *error); gboolean mono_metadata_decode_row_checked (const MonoImage *image, const MonoTableInfo *t, int idx, uint32_t *res, int res_size, MonoError *error); MONO_COMPONENT_API void mono_metadata_decode_row_raw (const MonoTableInfo *t, int idx, uint32_t *res, int res_size); gboolean mono_metadata_decode_row_dynamic_checked (const MonoDynamicImage *image, const MonoDynamicTable *t, int idx, guint32 *res, int res_size, MonoError *error); MonoType* mono_metadata_get_shared_type (MonoType *type); void mono_metadata_clean_generic_classes_for_image (MonoImage *image); gboolean mono_metadata_table_bounds_check_slow (MonoImage *image, int table_index, int token_index); int mono_metadata_table_num_rows_slow (MonoImage *image, int table_index); static inline int mono_metadata_table_num_rows (MonoImage *image, int table_index) { if (G_LIKELY (!image->has_updates)) return table_info_get_rows (&image->tables [table_index]); else return mono_metadata_table_num_rows_slow (image, table_index); } /* token_index is 1-based */ static inline gboolean mono_metadata_table_bounds_check (MonoImage *image, int table_index, int token_index) { /* returns true if given index is not in bounds with provided table/index pair */ if (G_LIKELY (token_index <= table_info_get_rows (&image->tables [table_index]))) return FALSE; if (G_LIKELY (!image->has_updates)) return TRUE; return mono_metadata_table_bounds_check_slow (image, table_index, token_index); } MONO_COMPONENT_API const char * mono_meta_table_name (int table); void mono_metadata_compute_table_bases (MonoImage *meta); gboolean mono_metadata_interfaces_from_typedef_full (MonoImage *image, guint32 table_index, MonoClass ***interfaces, guint *count, gboolean heap_alloc_result, MonoGenericContext *context, MonoError *error); MONO_API MonoMethodSignature * mono_metadata_parse_method_signature_full (MonoImage *image, MonoGenericContainer *generic_container, int def, const char *ptr, const char **rptr, MonoError *error); MONO_API MonoMethodHeader * mono_metadata_parse_mh_full (MonoImage *image, MonoGenericContainer *container, const char *ptr, MonoError *error); MonoMethodSignature *mono_metadata_parse_signature_checked (MonoImage *image, uint32_t token, MonoError *error); gboolean mono_method_get_header_summary (MonoMethod *method, MonoMethodHeaderSummary *summary); int* mono_metadata_get_param_attrs (MonoImage *m, int def, int param_count); gboolean mono_metadata_method_has_param_attrs (MonoImage *m, int def); guint mono_metadata_generic_context_hash (const MonoGenericContext *context); gboolean mono_metadata_generic_context_equal (const MonoGenericContext *g1, const MonoGenericContext *g2); MonoGenericInst * mono_metadata_parse_generic_inst (MonoImage *image, MonoGenericContainer *container, int count, const char *ptr, const char **rptr, MonoError *error); MONO_COMPONENT_API MonoGenericInst * mono_metadata_get_generic_inst (int type_argc, MonoType **type_argv); MonoGenericInst * mono_metadata_get_canonical_generic_inst (MonoGenericInst *candidate); MonoGenericClass * mono_metadata_lookup_generic_class (MonoClass *gclass, MonoGenericInst *inst, gboolean is_dynamic); MonoGenericInst * mono_metadata_inflate_generic_inst (MonoGenericInst *ginst, MonoGenericContext *context, MonoError *error); guint mono_metadata_generic_param_hash (MonoGenericParam *p); gboolean mono_metadata_generic_param_equal (MonoGenericParam *p1, MonoGenericParam *p2); void mono_dynamic_stream_reset (MonoDynamicStream* stream); void mono_assembly_load_friends (MonoAssembly* ass); MONO_API gint32 mono_assembly_addref (MonoAssembly *assembly); gint32 mono_assembly_decref (MonoAssembly *assembly); void mono_assembly_release_gc_roots (MonoAssembly *assembly); gboolean mono_assembly_close_except_image_pools (MonoAssembly *assembly); void mono_assembly_close_finish (MonoAssembly *assembly); gboolean mono_public_tokens_are_equal (const unsigned char *pubt1, const unsigned char *pubt2); void mono_config_parse_publisher_policy (const char *filename, MonoAssemblyBindingInfo *binding_info); gboolean mono_assembly_name_parse_full (const char *name, MonoAssemblyName *aname, gboolean save_public_key, gboolean *is_version_defined, gboolean *is_token_defined); gboolean mono_assembly_fill_assembly_name_full (MonoImage *image, MonoAssemblyName *aname, gboolean copyBlobs); MONO_API guint32 mono_metadata_get_generic_param_row (MonoImage *image, guint32 token, guint32 *owner); MonoGenericParam* mono_metadata_create_anon_gparam (MonoImage *image, gint32 param_num, gboolean is_mvar); void mono_unload_interface_ids (MonoBitSet *bitset); MonoType *mono_metadata_type_dup (MonoImage *image, const MonoType *original); MonoType *mono_metadata_type_dup_with_cmods (MonoImage *image, const MonoType *original, const MonoType *cmods_source); MonoMethodSignature *mono_metadata_signature_dup_full (MonoImage *image,MonoMethodSignature *sig); MonoMethodSignature *mono_metadata_signature_dup_mempool (MonoMemPool *mp, MonoMethodSignature *sig); MonoMethodSignature *mono_metadata_signature_dup_mem_manager (MonoMemoryManager *mem_manager, MonoMethodSignature *sig); MonoMethodSignature *mono_metadata_signature_dup_add_this (MonoImage *image, MonoMethodSignature *sig, MonoClass *klass); MonoGenericInst * mono_get_shared_generic_inst (MonoGenericContainer *container); int mono_type_stack_size_internal (MonoType *t, int *align, gboolean allow_open); MONO_API void mono_type_get_desc (GString *res, MonoType *type, mono_bool include_namespace); gboolean mono_metadata_type_equal_full (MonoType *t1, MonoType *t2, gboolean signature_only); MonoMarshalSpec * mono_metadata_parse_marshal_spec_full (MonoImage *image, MonoImage *parent_image, const char *ptr); guint mono_metadata_generic_inst_hash (gconstpointer data); gboolean mono_metadata_generic_inst_equal (gconstpointer ka, gconstpointer kb); gboolean mono_metadata_signature_equal_no_ret (MonoMethodSignature *sig1, MonoMethodSignature *sig2); MONO_API void mono_metadata_field_info_with_mempool ( MonoImage *meta, guint32 table_index, guint32 *offset, guint32 *rva, MonoMarshalSpec **marshal_spec); MonoClassField* mono_metadata_get_corresponding_field_from_generic_type_definition (MonoClassField *field); MonoEvent* mono_metadata_get_corresponding_event_from_generic_type_definition (MonoEvent *event); MonoProperty* mono_metadata_get_corresponding_property_from_generic_type_definition (MonoProperty *property); guint32 mono_metadata_signature_size (MonoMethodSignature *sig); guint mono_metadata_str_hash (gconstpointer v1); gboolean mono_image_load_pe_data (MonoImage *image); gboolean mono_image_load_cli_data (MonoImage *image); void mono_image_load_names (MonoImage *image); MonoImage *mono_image_open_raw (MonoAssemblyLoadContext *alc, const char *fname, MonoImageOpenStatus *status); MonoImage *mono_image_open_metadata_only (MonoAssemblyLoadContext *alc, const char *fname, MonoImageOpenStatus *status); MONO_COMPONENT_API MonoImage *mono_image_open_from_data_internal (MonoAssemblyLoadContext *alc, char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status, gboolean metadata_only, const char *name, const char *filename); MonoException *mono_get_exception_field_access_msg (const char *msg); MonoException *mono_get_exception_method_access_msg (const char *msg); MonoMethod* mono_method_from_method_def_or_ref (MonoImage *m, guint32 tok, MonoGenericContext *context, MonoError *error); MonoMethod *mono_get_method_constrained_with_method (MonoImage *image, MonoMethod *method, MonoClass *constrained_class, MonoGenericContext *context, MonoError *error); MonoMethod *mono_get_method_constrained_checked (MonoImage *image, guint32 token, MonoClass *constrained_class, MonoGenericContext *context, MonoMethod **cil_method, MonoError *error); void mono_type_set_alignment (MonoTypeEnum type, int align); MonoType * mono_type_create_from_typespec_checked (MonoImage *image, guint32 type_spec, MonoError *error); MonoMethodSignature* mono_method_get_signature_checked (MonoMethod *method, MonoImage *image, guint32 token, MonoGenericContext *context, MonoError *error); MONO_COMPONENT_API MonoMethod * mono_get_method_checked (MonoImage *image, guint32 token, MonoClass *klass, MonoGenericContext *context, MonoError *error); guint32 mono_metadata_localscope_from_methoddef (MonoImage *meta, guint32 index); void mono_wrapper_caches_free (MonoWrapperCaches *cache); MonoWrapperCaches* mono_method_get_wrapper_cache (MonoMethod *method); MonoWrapperCaches* mono_method_get_wrapper_cache (MonoMethod *method); MonoType* mono_metadata_parse_type_checked (MonoImage *m, MonoGenericContainer *container, short opt_attrs, gboolean transient, const char *ptr, const char **rptr, MonoError *error); MonoGenericContainer * mono_get_anonymous_container_for_image (MonoImage *image, gboolean is_mvar); void mono_loader_register_module (const char *name, MonoDl *module); void mono_ginst_get_desc (GString *str, MonoGenericInst *ginst); void mono_loader_set_strict_assembly_name_check (gboolean enabled); gboolean mono_loader_get_strict_assembly_name_check (void); MONO_COMPONENT_API gboolean mono_type_in_image (MonoType *type, MonoImage *image); gboolean mono_type_is_valid_generic_argument (MonoType *type); void mono_metadata_get_class_guid (MonoClass* klass, uint8_t* guid, MonoError *error); #define MONO_CLASS_IS_INTERFACE_INTERNAL(c) ((mono_class_get_flags (c) & TYPE_ATTRIBUTE_INTERFACE) || mono_type_is_generic_parameter (m_class_get_byval_arg (c))) static inline gboolean m_image_is_raw_data_allocated (MonoImage *image) { return image->storage ? image->storage->raw_data_allocated : FALSE; } static inline gboolean m_image_is_fileio_used (MonoImage *image) { return image->storage ? image->storage->fileio_used : FALSE; } #ifdef HOST_WIN32 static inline gboolean m_image_is_module_handle (MonoImage *image) { return image->storage ? image->storage->is_module_handle : FALSE; } static inline gboolean m_image_has_entry_point (MonoImage *image) { return image->storage ? image->storage->has_entry_point : FALSE; } #endif static inline const char * m_image_get_name (MonoImage *image) { return image->name; } static inline const char * m_image_get_filename (MonoImage *image) { return image->filename; } static inline const char * m_image_get_assembly_name (MonoImage *image) { return image->assembly_name; } static inline MonoAssemblyLoadContext * mono_image_get_alc (MonoImage *image) { return image->alc; } static inline MonoAssemblyLoadContext * mono_assembly_get_alc (MonoAssembly *assm) { return mono_image_get_alc (assm->image); } static inline MonoType* mono_signature_get_return_type_internal (MonoMethodSignature *sig) { return sig->ret; } /** * mono_type_get_type_internal: * \param type the \c MonoType operated on * \returns the IL type value for \p type. This is one of the \c MonoTypeEnum * enum members like \c MONO_TYPE_I4 or \c MONO_TYPE_STRING. */ static inline int mono_type_get_type_internal (MonoType *type) { return type->type; } /** * mono_type_get_signature: * \param type the \c MonoType operated on * It is only valid to call this function if \p type is a \c MONO_TYPE_FNPTR . * \returns the \c MonoMethodSignature pointer that describes the signature * of the function pointer \p type represents. */ static inline MonoMethodSignature* mono_type_get_signature_internal (MonoType *type) { g_assert (type->type == MONO_TYPE_FNPTR); return type->data.method; } /** * m_type_is_byref: * \param type the \c MonoType operated on * \returns TRUE if \p type represents a type passed by reference, * FALSE otherwise. */ static inline gboolean m_type_is_byref (const MonoType *type) { return type->byref__; } /** * mono_type_get_class_internal: * \param type the \c MonoType operated on * It is only valid to call this function if \p type is a \c MONO_TYPE_CLASS or a * \c MONO_TYPE_VALUETYPE . For more general functionality, use \c mono_class_from_mono_type_internal, * instead. * \returns the \c MonoClass pointer that describes the class that \p type represents. */ static inline MonoClass* mono_type_get_class_internal (MonoType *type) { /* FIXME: review the runtime users before adding the assert here */ return type->data.klass; } /** * mono_type_get_array_type_internal: * \param type the \c MonoType operated on * It is only valid to call this function if \p type is a \c MONO_TYPE_ARRAY . * \returns a \c MonoArrayType struct describing the array type that \p type * represents. The info includes details such as rank, array element type * and the sizes and bounds of multidimensional arrays. */ static inline MonoArrayType* mono_type_get_array_type_internal (MonoType *type) { return type->data.array; } static inline int mono_metadata_table_to_ptr_table (int table_num) { switch (table_num) { case MONO_TABLE_FIELD: return MONO_TABLE_FIELD_POINTER; case MONO_TABLE_METHOD: return MONO_TABLE_METHOD_POINTER; case MONO_TABLE_PARAM: return MONO_TABLE_PARAM_POINTER; case MONO_TABLE_PROPERTY: return MONO_TABLE_PROPERTY_POINTER; case MONO_TABLE_EVENT: return MONO_TABLE_EVENT_POINTER; default: g_assert_not_reached (); } } #endif /* __MONO_METADATA_INTERNALS_H__ */
/** * \file */ #ifndef __MONO_METADATA_INTERNALS_H__ #define __MONO_METADATA_INTERNALS_H__ #include "mono/utils/mono-forward-internal.h" #include "mono/metadata/image.h" #include "mono/metadata/blob.h" #include "mono/metadata/cil-coff.h" #include "mono/metadata/mempool.h" #include "mono/metadata/domain-internals.h" #include "mono/metadata/mono-hash.h" #include "mono/utils/mono-compiler.h" #include "mono/utils/mono-dl.h" #include "mono/utils/monobitset.h" #include "mono/utils/mono-property-hash.h" #include "mono/utils/mono-value-hash.h" #include <mono/utils/mono-error.h> #include "mono/utils/mono-conc-hashtable.h" #include "mono/utils/refcount.h" struct _MonoType { union { MonoClass *klass; /* for VALUETYPE and CLASS */ MonoType *type; /* for PTR */ MonoArrayType *array; /* for ARRAY */ MonoMethodSignature *method; MonoGenericParam *generic_param; /* for VAR and MVAR */ MonoGenericClass *generic_class; /* for GENERICINST */ } data; unsigned int attrs : 16; /* param attributes or field flags */ MonoTypeEnum type : 8; unsigned int has_cmods : 1; unsigned int byref__ : 1; /* don't access directly, use m_type_is_byref */ unsigned int pinned : 1; /* valid when included in a local var signature */ }; typedef struct { unsigned int required : 1; MonoType *type; } MonoSingleCustomMod; /* Aggregate custom modifiers can happen if a generic VAR or MVAR is inflated, * and both the VAR and the type that will be used to inflated it have custom * modifiers, but they come from different images. (e.g. inflating 'class G<T> * {void Test (T modopt(IsConst) t);}' with 'int32 modopt(IsLong)' where G is * in image1 and the int32 is in image2.) * * Moreover, we can't just store an image and a type token per modifier, because * Roslyn and C++/CLI sometimes create modifiers that mention generic parameters that must be inflated, like: * void .CL1`1.Test(!0 modopt(System.Nullable`1<!0>)) * So we have to store a resolved MonoType*. * * Because the types come from different images, we allocate the aggregate * custom modifiers container object in the mempool of a MonoImageSet to ensure * that it doesn't have dangling image pointers. */ typedef struct { uint8_t count; MonoSingleCustomMod modifiers[1]; /* Actual length is count */ } MonoAggregateModContainer; /* ECMA says upto 64 custom modifiers. It's possible we could see more at * runtime due to modifiers being appended together when we inflate type. In * that case we should revisit the places where this define is used to make * sure that we don't blow up the stack (or switch to heap allocation for * temporaries). */ #define MONO_MAX_EXPECTED_CMODS 64 typedef struct { MonoType unmodified; gboolean is_aggregate; union { MonoCustomModContainer cmods; /* the actual aggregate modifiers are in a MonoImageSet mempool * that includes all the images of all the modifier types and * also the type that this aggregate container is a part of.*/ MonoAggregateModContainer *amods; } mods; } MonoTypeWithModifiers; gboolean mono_type_is_aggregate_mods (const MonoType *t); static inline void mono_type_with_mods_init (MonoType *dest, uint8_t num_mods, gboolean is_aggregate) { if (num_mods == 0) { dest->has_cmods = 0; return; } dest->has_cmods = 1; MonoTypeWithModifiers *dest_full = (MonoTypeWithModifiers *)dest; dest_full->is_aggregate = !!is_aggregate; if (is_aggregate) dest_full->mods.amods = NULL; else dest_full->mods.cmods.count = num_mods; } MonoCustomModContainer * mono_type_get_cmods (const MonoType *t); MonoAggregateModContainer * mono_type_get_amods (const MonoType *t); void mono_type_set_amods (MonoType *t, MonoAggregateModContainer *amods); static inline uint8_t mono_type_custom_modifier_count (const MonoType *t) { if (!t->has_cmods) return 0; MonoTypeWithModifiers *full = (MonoTypeWithModifiers *)t; if (full->is_aggregate) return full->mods.amods->count; else return full->mods.cmods.count; } MonoType * mono_type_get_custom_modifier (const MonoType *ty, uint8_t idx, gboolean *required, MonoError *error); // Note: sizeof (MonoType) is dangerous. It can copy the num_mods // field without copying the variably sized array. This leads to // memory unsafety on the stack and/or heap, when we try to traverse // this array. // // Use mono_sizeof_monotype // to get the size of the memory to copy. #define MONO_SIZEOF_TYPE sizeof (MonoType) size_t mono_sizeof_type_with_mods (uint8_t num_mods, gboolean aggregate); size_t mono_sizeof_type (const MonoType *ty); size_t mono_sizeof_aggregate_modifiers (uint8_t num_mods); MonoAggregateModContainer * mono_metadata_get_canonical_aggregate_modifiers (MonoAggregateModContainer *candidate); #define MONO_PUBLIC_KEY_TOKEN_LENGTH 17 #define MONO_PROCESSOR_ARCHITECTURE_NONE 0 #define MONO_PROCESSOR_ARCHITECTURE_MSIL 1 #define MONO_PROCESSOR_ARCHITECTURE_X86 2 #define MONO_PROCESSOR_ARCHITECTURE_IA64 3 #define MONO_PROCESSOR_ARCHITECTURE_AMD64 4 #define MONO_PROCESSOR_ARCHITECTURE_ARM 5 struct _MonoAssemblyName { const char *name; const char *culture; const char *hash_value; const mono_byte* public_key; // string of 16 hex chars + 1 NULL mono_byte public_key_token [MONO_PUBLIC_KEY_TOKEN_LENGTH]; uint32_t hash_alg; uint32_t hash_len; uint32_t flags; int32_t major, minor, build, revision, arch; //Add members for correct work with mono_stringify_assembly_name MonoBoolean without_version; MonoBoolean without_culture; MonoBoolean without_public_key_token; }; struct MonoTypeNameParse { char *name_space; char *name; MonoAssemblyName assembly; GList *modifiers; /* 0 -> byref, -1 -> pointer, > 0 -> array rank */ GPtrArray *type_arguments; GList *nested; }; typedef struct _MonoAssemblyContext { /* Don't fire managed load event for this assembly */ guint8 no_managed_load_event : 1; } MonoAssemblyContext; struct _MonoAssembly { /* * The number of appdomains which have this assembly loaded plus the number of * assemblies referencing this assembly through an entry in their image->references * arrays. The latter is needed because entries in the image->references array * might point to assemblies which are only loaded in some appdomains, and without * the additional reference, they can be freed at any time. * The ref_count is initially 0. */ gint32 ref_count; /* use atomic operations only */ char *basedir; MonoAssemblyName aname; MonoImage *image; GSList *friend_assembly_names; /* Computed by mono_assembly_load_friends () */ GSList *ignores_checks_assembly_names; /* Computed by mono_assembly_load_friends () */ guint8 friend_assembly_names_inited; guint8 dynamic; MonoAssemblyContext context; guint8 wrap_non_exception_throws; guint8 wrap_non_exception_throws_inited; guint8 jit_optimizer_disabled; guint8 jit_optimizer_disabled_inited; guint8 runtime_marshalling_enabled; guint8 runtime_marshalling_enabled_inited; }; typedef struct { const char* data; guint32 size; } MonoStreamHeader; struct _MonoTableInfo { const char *base; guint rows_ : 24; /* don't access directly, use table_info_get_rows */ guint row_size : 8; /* * Tables contain up to 9 columns and the possible sizes of the * fields in the documentation are 1, 2 and 4 bytes. So we * can encode in 2 bits the size. * * A 32 bit value can encode the resulting size * * The top eight bits encode the number of columns in the table. * we only need 4, but 8 is aligned no shift required. */ guint32 size_bitfield; }; #define REFERENCE_MISSING ((gpointer) -1) typedef struct { gboolean (*match) (MonoImage*); gboolean (*load_pe_data) (MonoImage*); gboolean (*load_cli_data) (MonoImage*); gboolean (*load_tables) (MonoImage*); } MonoImageLoader; /* Represents the physical bytes for an image (usually in the file system, but * could be in memory). * * The MonoImageStorage owns the raw data for an image and is responsible for * cleanup. * * May be shared by multiple MonoImage objects if they opened the same * underlying file or byte blob in memory. * * There is an abstract string key (usually a file path, but could be formed in * other ways) that is used to share MonoImageStorage objects among images. * */ typedef struct { MonoRefCount ref; /* key used for lookups. owned by this image storage. */ char *key; /* If the raw data was allocated from a source such as mmap, the allocator may store resource tracking information here. */ void *raw_data_handle; char *raw_data; guint32 raw_data_len; /* data was allocated with mono_file_map and must be unmapped */ guint8 raw_buffer_used : 1; /* data was allocated with malloc and must be freed */ guint8 raw_data_allocated : 1; /* data was allocated with mono_file_map_fileio */ guint8 fileio_used : 1; #ifdef HOST_WIN32 /* Module was loaded using LoadLibrary. */ guint8 is_module_handle : 1; /* Module entry point is _CorDllMain. */ guint8 has_entry_point : 1; #endif } MonoImageStorage; struct _MonoImage { /* * This count is incremented during these situations: * - An assembly references this MonoImage through its 'image' field * - This MonoImage is present in the 'files' field of an image * - This MonoImage is present in the 'modules' field of an image * - A thread is holding a temporary reference to this MonoImage between * calls to mono_image_open and mono_image_close () */ int ref_count; MonoImageStorage *storage; /* Aliases storage->raw_data when storage is non-NULL. Otherwise NULL. */ char *raw_data; guint32 raw_data_len; /* Whenever this is a dynamically emitted module */ guint8 dynamic : 1; /* Whenever this image contains uncompressed metadata */ guint8 uncompressed_metadata : 1; /* Whenever this image contains metadata only without PE data */ guint8 metadata_only : 1; guint8 checked_module_cctor : 1; guint8 has_module_cctor : 1; guint8 idx_string_wide : 1; guint8 idx_guid_wide : 1; guint8 idx_blob_wide : 1; /* NOT SUPPORTED: Whenever this image is considered as platform code for the CoreCLR security model */ guint8 core_clr_platform_code : 1; /* Whether a #JTD stream was present. Indicates that this image was a minimal delta and its heaps only include the new heap entries */ guint8 minimal_delta : 1; /* The path to the file for this image or an arbitrary name for images loaded from data. */ char *name; /* The path to the file for this image or NULL */ char *filename; /* The assembly name reported in the file for this image (expected to be NULL for a netmodule) */ const char *assembly_name; /* The module name reported in the file for this image (could be NULL for a malformed file) */ const char *module_name; char *version; gint16 md_version_major, md_version_minor; char *guid; MonoCLIImageInfo *image_info; MonoMemPool *mempool; /*protected by the image lock*/ char *raw_metadata; MonoStreamHeader heap_strings; MonoStreamHeader heap_us; MonoStreamHeader heap_blob; MonoStreamHeader heap_guid; MonoStreamHeader heap_tables; MonoStreamHeader heap_pdb; const char *tables_base; /* For PPDB files */ guint64 referenced_tables; int *referenced_table_rows; /**/ MonoTableInfo tables [MONO_TABLE_NUM]; /* * references is initialized only by using the mono_assembly_open * function, and not by using the lowlevel mono_image_open. * * Protected by the image lock. * * It is NULL terminated. */ MonoAssembly **references; int nreferences; /* Code files in the assembly. The main assembly has a "file" table and also a "module" * table, where the module table is a subset of the file table. We track both lists, * and because we can lazy-load them at different times we reference-increment both. */ /* No netmodules in netcore, but for System.Reflection.Emit support we still use modules */ MonoImage **modules; guint32 module_count; gboolean *modules_loaded; MonoImage **files; guint32 file_count; MonoAotModule *aot_module; guint8 aotid[16]; /* * The Assembly this image was loaded from. */ MonoAssembly *assembly; /* * The AssemblyLoadContext that this image was loaded into. */ MonoAssemblyLoadContext *alc; /* * Indexed by method tokens and typedef tokens. */ GHashTable *method_cache; /*protected by the image lock*/ MonoInternalHashTable class_cache; /* Indexed by memberref + methodspec tokens */ GHashTable *methodref_cache; /*protected by the image lock*/ /* * Indexed by fielddef and memberref tokens */ MonoConcurrentHashTable *field_cache; /*protected by the image lock*/ /* indexed by typespec tokens. */ MonoConcurrentHashTable *typespec_cache; /* protected by the image lock */ /* indexed by token */ GHashTable *memberref_signatures; /* Indexed by blob heap indexes */ GHashTable *method_signatures; /* * Indexes namespaces to hash tables that map class name to typedef token. */ GHashTable *name_cache; /*protected by the image lock*/ /* * Indexed by MonoClass */ GHashTable *array_cache; GHashTable *ptr_cache; GHashTable *szarray_cache; /* This has a separate lock to improve scalability */ mono_mutex_t szarray_cache_lock; /* * indexed by SignaturePointerPair */ GHashTable *native_func_wrapper_cache; /* * indexed by MonoMethod pointers */ GHashTable *wrapper_param_names; GHashTable *array_accessor_cache; GHashTable *icall_wrapper_cache; GHashTable *rgctx_template_hash; /* LOCKING: templates lock */ /* Contains rarely used fields of runtime structures belonging to this image */ MonoPropertyHash *property_hash; void *reflection_info; /* * user_info is a public field and is not touched by the * metadata engine */ void *user_info; #ifndef DISABLE_DLLMAP /* dll map entries */ MonoDllMap *dll_map; #endif /* interfaces IDs from this image */ /* protected by the classes lock */ MonoBitSet *interface_bitset; /* when the image is being closed, this is abused as a list of malloc'ed regions to be freed. */ GSList *reflection_info_unregister_classes; /* List of dependent image sets containing this image */ /* Protected by image_sets_lock */ GSList *image_sets; /* Caches for wrappers that DO NOT reference generic */ /* arguments */ MonoWrapperCaches wrapper_caches; /* Pre-allocated anon generic params for the first N generic * parameters, for a small N */ MonoGenericParam *var_gparam_cache_fast; MonoGenericParam *mvar_gparam_cache_fast; /* Anon generic parameters past N, if needed */ MonoConcurrentHashTable *var_gparam_cache; MonoConcurrentHashTable *mvar_gparam_cache; /* The loader used to load this image */ MonoImageLoader *loader; // Containers for MonoGenericParams associated with this image but not with any specific class or method. Created on demand. // This could happen, for example, for MonoTypes associated with TypeSpec table entries. MonoGenericContainer *anonymous_generic_class_container; MonoGenericContainer *anonymous_generic_method_container; #ifdef ENABLE_WEAK_ATTR gboolean weak_fields_inited; /* Contains 1 based indexes */ GHashTable *weak_field_indexes; #endif /* baseline images only: whether any metadata updates have been applied to this image */ gboolean has_updates; /* * No other runtime locks must be taken while holding this lock. * It's meant to be used only to mutate and query structures part of this image. */ mono_mutex_t lock; }; enum { MONO_SECTION_TEXT, MONO_SECTION_RSRC, MONO_SECTION_RELOC, MONO_SECTION_MAX }; typedef struct { GHashTable *hash; char *data; guint32 alloc_size; /* malloced bytes */ guint32 index; guint32 offset; /* from start of metadata */ } MonoDynamicStream; typedef struct { guint32 alloc_rows; guint32 rows; guint8 row_size; /* calculated later with column_sizes */ guint8 columns; guint32 next_idx; guint32 *values; /* rows * columns */ } MonoDynamicTable; /* "Dynamic" assemblies and images arise from System.Reflection.Emit */ struct _MonoDynamicAssembly { MonoAssembly assembly; char *strong_name; guint32 strong_name_size; }; struct _MonoDynamicImage { MonoImage image; guint32 meta_size; guint32 text_rva; guint32 metadata_rva; guint32 image_base; guint32 cli_header_offset; guint32 iat_offset; guint32 idt_offset; guint32 ilt_offset; guint32 imp_names_offset; struct { guint32 rva; guint32 size; guint32 offset; guint32 attrs; } sections [MONO_SECTION_MAX]; GHashTable *typespec; GHashTable *typeref; GHashTable *handleref; MonoGHashTable *tokens; GHashTable *blob_cache; GHashTable *standalonesig_cache; GList *array_methods; GHashTable *method_aux_hash; GHashTable *vararg_aux_hash; MonoGHashTable *generic_def_objects; gboolean initial_image; guint32 pe_kind, machine; char *strong_name; guint32 strong_name_size; char *win32_res; guint32 win32_res_size; guint8 *public_key; int public_key_len; MonoDynamicStream sheap; MonoDynamicStream code; /* used to store method headers and bytecode */ MonoDynamicStream resources; /* managed embedded resources */ MonoDynamicStream us; MonoDynamicStream blob; MonoDynamicStream tstream; MonoDynamicStream guid; MonoDynamicTable tables [MONO_TABLE_NUM]; MonoClass *wrappers_type; /*wrappers are bound to this type instead of <Module>*/ }; /* Contains information about assembly binding */ typedef struct _MonoAssemblyBindingInfo { char *name; char *culture; guchar public_key_token [MONO_PUBLIC_KEY_TOKEN_LENGTH]; int major; int minor; AssemblyVersionSet old_version_bottom; AssemblyVersionSet old_version_top; AssemblyVersionSet new_version; guint has_old_version_bottom : 1; guint has_old_version_top : 1; guint has_new_version : 1; guint is_valid : 1; gint32 domain_id; /*Needed to unload per-domain binding*/ } MonoAssemblyBindingInfo; struct _MonoMethodHeader { const unsigned char *code; #ifdef MONO_SMALL_CONFIG guint16 code_size; #else guint32 code_size; #endif guint16 max_stack : 15; unsigned int is_transient: 1; /* mono_metadata_free_mh () will actually free this header */ unsigned int num_clauses : 15; /* if num_locals != 0, then the following apply: */ unsigned int init_locals : 1; guint16 num_locals; MonoExceptionClause *clauses; MonoBitSet *volatile_args; MonoBitSet *volatile_locals; MonoType *locals [MONO_ZERO_LEN_ARRAY]; }; typedef struct { const unsigned char *code; guint32 code_size; guint16 max_stack; gboolean has_clauses; gboolean has_locals; } MonoMethodHeaderSummary; // FIXME? offsetof (MonoMethodHeader, locals)? #define MONO_SIZEOF_METHOD_HEADER (sizeof (struct _MonoMethodHeader) - MONO_ZERO_LEN_ARRAY * SIZEOF_VOID_P) struct _MonoMethodSignature { MonoType *ret; #ifdef MONO_SMALL_CONFIG guint8 param_count; gint8 sentinelpos; unsigned int generic_param_count : 5; #else guint16 param_count; gint16 sentinelpos; unsigned int generic_param_count : 16; #endif unsigned int call_convention : 6; unsigned int hasthis : 1; unsigned int explicit_this : 1; unsigned int pinvoke : 1; unsigned int is_inflated : 1; unsigned int has_type_parameters : 1; unsigned int suppress_gc_transition : 1; unsigned int marshalling_disabled : 1; MonoType *params [MONO_ZERO_LEN_ARRAY]; }; /* * AOT cache configuration loaded from config files. * Doesn't really belong here. */ typedef struct { /* * Enable aot caching for applications whose main assemblies are in * this list. */ GSList *apps; GSList *assemblies; char *aot_options; } MonoAotCacheConfig; #define MONO_SIZEOF_METHOD_SIGNATURE (sizeof (struct _MonoMethodSignature) - MONO_ZERO_LEN_ARRAY * SIZEOF_VOID_P) static inline gboolean image_is_dynamic (MonoImage *image) { #ifdef DISABLE_REFLECTION_EMIT return FALSE; #else return image->dynamic; #endif } static inline gboolean assembly_is_dynamic (MonoAssembly *assembly) { #ifdef DISABLE_REFLECTION_EMIT return FALSE; #else return assembly->dynamic; #endif } static inline int table_info_get_rows (const MonoTableInfo *table) { return table->rows_; } /* for use with allocated memory blocks (assumes alignment is to 8 bytes) */ MONO_COMPONENT_API guint mono_aligned_addr_hash (gconstpointer ptr); void mono_image_check_for_module_cctor (MonoImage *image); gpointer mono_image_alloc (MonoImage *image, guint size); gpointer mono_image_alloc0 (MonoImage *image, guint size); #define mono_image_new0(image,type,size) ((type *) mono_image_alloc0 (image, sizeof (type)* (size))) char* mono_image_strdup (MonoImage *image, const char *s); char* mono_image_strdup_vprintf (MonoImage *image, const char *format, va_list args); char* mono_image_strdup_printf (MonoImage *image, const char *format, ...) MONO_ATTR_FORMAT_PRINTF(2,3); GList* mono_g_list_prepend_image (MonoImage *image, GList *list, gpointer data); GSList* mono_g_slist_append_image (MonoImage *image, GSList *list, gpointer data); MONO_COMPONENT_API void mono_image_lock (MonoImage *image); MONO_COMPONENT_API void mono_image_unlock (MonoImage *image); gpointer mono_image_property_lookup (MonoImage *image, gpointer subject, guint32 property); void mono_image_property_insert (MonoImage *image, gpointer subject, guint32 property, gpointer value); void mono_image_property_remove (MonoImage *image, gpointer subject); MONO_COMPONENT_API gboolean mono_image_close_except_pools (MonoImage *image); MONO_COMPONENT_API void mono_image_close_finish (MonoImage *image); typedef void (*MonoImageUnloadFunc) (MonoImage *image, gpointer user_data); void mono_install_image_unload_hook (MonoImageUnloadFunc func, gpointer user_data); void mono_remove_image_unload_hook (MonoImageUnloadFunc func, gpointer user_data); void mono_install_image_loader (const MonoImageLoader *loader); void mono_image_append_class_to_reflection_info_set (MonoClass *klass); typedef struct _MonoMetadataUpdateData MonoMetadataUpdateData; struct _MonoMetadataUpdateData { int has_updates; }; extern MonoMetadataUpdateData mono_metadata_update_data_private; /* returns TRUE if there's at least one update */ static inline gboolean mono_metadata_has_updates (void) { return mono_metadata_update_data_private.has_updates != 0; } /* components can't call the inline function directly since the private data isn't exported */ MONO_COMPONENT_API gboolean mono_metadata_has_updates_api (void); void mono_image_effective_table_slow (const MonoTableInfo **t, int idx); gboolean mono_metadata_update_has_modified_rows (const MonoTableInfo *t); static inline void mono_image_effective_table (const MonoTableInfo **t, int idx) { if (G_UNLIKELY (mono_metadata_has_updates ())) { if (G_UNLIKELY (idx >= table_info_get_rows ((*t)) || mono_metadata_update_has_modified_rows (*t))) { mono_image_effective_table_slow (t, idx); } } } enum MonoEnCDeltaOrigin { MONO_ENC_DELTA_API = 0, MONO_ENC_DELTA_DBG = 1, }; MONO_COMPONENT_API void mono_image_load_enc_delta (int delta_origin, MonoImage *base_image, gconstpointer dmeta, uint32_t dmeta_len, gconstpointer dil, uint32_t dil_len, gconstpointer dpdb, uint32_t dpdb_len, MonoError *error); gboolean mono_image_load_cli_header (MonoImage *image, MonoCLIImageInfo *iinfo); gboolean mono_image_load_metadata (MonoImage *image, MonoCLIImageInfo *iinfo); const char* mono_metadata_string_heap_checked (MonoImage *meta, uint32_t table_index, MonoError *error); const char * mono_metadata_blob_heap_null_ok (MonoImage *meta, guint32 index); const char* mono_metadata_blob_heap_checked (MonoImage *meta, uint32_t table_index, MonoError *error); gboolean mono_metadata_decode_row_checked (const MonoImage *image, const MonoTableInfo *t, int idx, uint32_t *res, int res_size, MonoError *error); MONO_COMPONENT_API void mono_metadata_decode_row_raw (const MonoTableInfo *t, int idx, uint32_t *res, int res_size); gboolean mono_metadata_decode_row_dynamic_checked (const MonoDynamicImage *image, const MonoDynamicTable *t, int idx, guint32 *res, int res_size, MonoError *error); MonoType* mono_metadata_get_shared_type (MonoType *type); void mono_metadata_clean_generic_classes_for_image (MonoImage *image); gboolean mono_metadata_table_bounds_check_slow (MonoImage *image, int table_index, int token_index); int mono_metadata_table_num_rows_slow (MonoImage *image, int table_index); static inline int mono_metadata_table_num_rows (MonoImage *image, int table_index) { if (G_LIKELY (!image->has_updates)) return table_info_get_rows (&image->tables [table_index]); else return mono_metadata_table_num_rows_slow (image, table_index); } /* token_index is 1-based */ static inline gboolean mono_metadata_table_bounds_check (MonoImage *image, int table_index, int token_index) { /* returns true if given index is not in bounds with provided table/index pair */ if (G_LIKELY (token_index <= table_info_get_rows (&image->tables [table_index]))) return FALSE; if (G_LIKELY (!image->has_updates)) return TRUE; return mono_metadata_table_bounds_check_slow (image, table_index, token_index); } MONO_COMPONENT_API const char * mono_meta_table_name (int table); void mono_metadata_compute_table_bases (MonoImage *meta); gboolean mono_metadata_interfaces_from_typedef_full (MonoImage *image, guint32 table_index, MonoClass ***interfaces, guint *count, gboolean heap_alloc_result, MonoGenericContext *context, MonoError *error); MONO_API MonoMethodSignature * mono_metadata_parse_method_signature_full (MonoImage *image, MonoGenericContainer *generic_container, int def, const char *ptr, const char **rptr, MonoError *error); MONO_API MonoMethodHeader * mono_metadata_parse_mh_full (MonoImage *image, MonoGenericContainer *container, const char *ptr, MonoError *error); MonoMethodSignature *mono_metadata_parse_signature_checked (MonoImage *image, uint32_t token, MonoError *error); gboolean mono_method_get_header_summary (MonoMethod *method, MonoMethodHeaderSummary *summary); int* mono_metadata_get_param_attrs (MonoImage *m, int def, int param_count); gboolean mono_metadata_method_has_param_attrs (MonoImage *m, int def); guint mono_metadata_generic_context_hash (const MonoGenericContext *context); gboolean mono_metadata_generic_context_equal (const MonoGenericContext *g1, const MonoGenericContext *g2); MonoGenericInst * mono_metadata_parse_generic_inst (MonoImage *image, MonoGenericContainer *container, int count, const char *ptr, const char **rptr, MonoError *error); MONO_COMPONENT_API MonoGenericInst * mono_metadata_get_generic_inst (int type_argc, MonoType **type_argv); MonoGenericInst * mono_metadata_get_canonical_generic_inst (MonoGenericInst *candidate); MonoGenericClass * mono_metadata_lookup_generic_class (MonoClass *gclass, MonoGenericInst *inst, gboolean is_dynamic); MonoGenericInst * mono_metadata_inflate_generic_inst (MonoGenericInst *ginst, MonoGenericContext *context, MonoError *error); guint mono_metadata_generic_param_hash (MonoGenericParam *p); gboolean mono_metadata_generic_param_equal (MonoGenericParam *p1, MonoGenericParam *p2); void mono_dynamic_stream_reset (MonoDynamicStream* stream); void mono_assembly_load_friends (MonoAssembly* ass); MONO_API gint32 mono_assembly_addref (MonoAssembly *assembly); gint32 mono_assembly_decref (MonoAssembly *assembly); void mono_assembly_release_gc_roots (MonoAssembly *assembly); gboolean mono_assembly_close_except_image_pools (MonoAssembly *assembly); void mono_assembly_close_finish (MonoAssembly *assembly); gboolean mono_public_tokens_are_equal (const unsigned char *pubt1, const unsigned char *pubt2); void mono_config_parse_publisher_policy (const char *filename, MonoAssemblyBindingInfo *binding_info); gboolean mono_assembly_name_parse_full (const char *name, MonoAssemblyName *aname, gboolean save_public_key, gboolean *is_version_defined, gboolean *is_token_defined); gboolean mono_assembly_fill_assembly_name_full (MonoImage *image, MonoAssemblyName *aname, gboolean copyBlobs); MONO_API guint32 mono_metadata_get_generic_param_row (MonoImage *image, guint32 token, guint32 *owner); MonoGenericParam* mono_metadata_create_anon_gparam (MonoImage *image, gint32 param_num, gboolean is_mvar); void mono_unload_interface_ids (MonoBitSet *bitset); MonoType *mono_metadata_type_dup (MonoImage *image, const MonoType *original); MonoType *mono_metadata_type_dup_with_cmods (MonoImage *image, const MonoType *original, const MonoType *cmods_source); MonoMethodSignature *mono_metadata_signature_dup_full (MonoImage *image,MonoMethodSignature *sig); MonoMethodSignature *mono_metadata_signature_dup_mempool (MonoMemPool *mp, MonoMethodSignature *sig); MonoMethodSignature *mono_metadata_signature_dup_mem_manager (MonoMemoryManager *mem_manager, MonoMethodSignature *sig); MonoMethodSignature *mono_metadata_signature_dup_add_this (MonoImage *image, MonoMethodSignature *sig, MonoClass *klass); MonoGenericInst * mono_get_shared_generic_inst (MonoGenericContainer *container); int mono_type_stack_size_internal (MonoType *t, int *align, gboolean allow_open); MONO_API void mono_type_get_desc (GString *res, MonoType *type, mono_bool include_namespace); gboolean mono_metadata_type_equal_full (MonoType *t1, MonoType *t2, gboolean signature_only); MonoMarshalSpec * mono_metadata_parse_marshal_spec_full (MonoImage *image, MonoImage *parent_image, const char *ptr); guint mono_metadata_generic_inst_hash (gconstpointer data); gboolean mono_metadata_generic_inst_equal (gconstpointer ka, gconstpointer kb); gboolean mono_metadata_signature_equal_no_ret (MonoMethodSignature *sig1, MonoMethodSignature *sig2); MONO_API void mono_metadata_field_info_with_mempool ( MonoImage *meta, guint32 table_index, guint32 *offset, guint32 *rva, MonoMarshalSpec **marshal_spec); MonoClassField* mono_metadata_get_corresponding_field_from_generic_type_definition (MonoClassField *field); MonoEvent* mono_metadata_get_corresponding_event_from_generic_type_definition (MonoEvent *event); MonoProperty* mono_metadata_get_corresponding_property_from_generic_type_definition (MonoProperty *property); guint32 mono_metadata_signature_size (MonoMethodSignature *sig); guint mono_metadata_str_hash (gconstpointer v1); gboolean mono_image_load_pe_data (MonoImage *image); gboolean mono_image_load_cli_data (MonoImage *image); void mono_image_load_names (MonoImage *image); MonoImage *mono_image_open_raw (MonoAssemblyLoadContext *alc, const char *fname, MonoImageOpenStatus *status); MonoImage *mono_image_open_metadata_only (MonoAssemblyLoadContext *alc, const char *fname, MonoImageOpenStatus *status); MONO_COMPONENT_API MonoImage *mono_image_open_from_data_internal (MonoAssemblyLoadContext *alc, char *data, guint32 data_len, gboolean need_copy, MonoImageOpenStatus *status, gboolean metadata_only, const char *name, const char *filename); MonoException *mono_get_exception_field_access_msg (const char *msg); MonoException *mono_get_exception_method_access_msg (const char *msg); MonoMethod* mono_method_from_method_def_or_ref (MonoImage *m, guint32 tok, MonoGenericContext *context, MonoError *error); MonoMethod *mono_get_method_constrained_with_method (MonoImage *image, MonoMethod *method, MonoClass *constrained_class, MonoGenericContext *context, MonoError *error); MonoMethod *mono_get_method_constrained_checked (MonoImage *image, guint32 token, MonoClass *constrained_class, MonoGenericContext *context, MonoMethod **cil_method, MonoError *error); void mono_type_set_alignment (MonoTypeEnum type, int align); MonoType * mono_type_create_from_typespec_checked (MonoImage *image, guint32 type_spec, MonoError *error); MonoMethodSignature* mono_method_get_signature_checked (MonoMethod *method, MonoImage *image, guint32 token, MonoGenericContext *context, MonoError *error); MONO_COMPONENT_API MonoMethod * mono_get_method_checked (MonoImage *image, guint32 token, MonoClass *klass, MonoGenericContext *context, MonoError *error); guint32 mono_metadata_localscope_from_methoddef (MonoImage *meta, guint32 index); void mono_wrapper_caches_free (MonoWrapperCaches *cache); MonoWrapperCaches* mono_method_get_wrapper_cache (MonoMethod *method); MonoWrapperCaches* mono_method_get_wrapper_cache (MonoMethod *method); MonoType* mono_metadata_parse_type_checked (MonoImage *m, MonoGenericContainer *container, short opt_attrs, gboolean transient, const char *ptr, const char **rptr, MonoError *error); MonoGenericContainer * mono_get_anonymous_container_for_image (MonoImage *image, gboolean is_mvar); void mono_loader_register_module (const char *name, MonoDl *module); void mono_ginst_get_desc (GString *str, MonoGenericInst *ginst); void mono_loader_set_strict_assembly_name_check (gboolean enabled); gboolean mono_loader_get_strict_assembly_name_check (void); MONO_COMPONENT_API gboolean mono_type_in_image (MonoType *type, MonoImage *image); gboolean mono_type_is_valid_generic_argument (MonoType *type); void mono_metadata_get_class_guid (MonoClass* klass, uint8_t* guid, MonoError *error); #define MONO_CLASS_IS_INTERFACE_INTERNAL(c) ((mono_class_get_flags (c) & TYPE_ATTRIBUTE_INTERFACE) || mono_type_is_generic_parameter (m_class_get_byval_arg (c))) static inline gboolean m_image_is_raw_data_allocated (MonoImage *image) { return image->storage ? image->storage->raw_data_allocated : FALSE; } static inline gboolean m_image_is_fileio_used (MonoImage *image) { return image->storage ? image->storage->fileio_used : FALSE; } #ifdef HOST_WIN32 static inline gboolean m_image_is_module_handle (MonoImage *image) { return image->storage ? image->storage->is_module_handle : FALSE; } static inline gboolean m_image_has_entry_point (MonoImage *image) { return image->storage ? image->storage->has_entry_point : FALSE; } #endif static inline const char * m_image_get_name (MonoImage *image) { return image->name; } static inline const char * m_image_get_filename (MonoImage *image) { return image->filename; } static inline const char * m_image_get_assembly_name (MonoImage *image) { return image->assembly_name; } static inline MonoAssemblyLoadContext * mono_image_get_alc (MonoImage *image) { return image->alc; } static inline MonoAssemblyLoadContext * mono_assembly_get_alc (MonoAssembly *assm) { return mono_image_get_alc (assm->image); } static inline MonoType* mono_signature_get_return_type_internal (MonoMethodSignature *sig) { return sig->ret; } /** * mono_type_get_type_internal: * \param type the \c MonoType operated on * \returns the IL type value for \p type. This is one of the \c MonoTypeEnum * enum members like \c MONO_TYPE_I4 or \c MONO_TYPE_STRING. */ static inline int mono_type_get_type_internal (MonoType *type) { return type->type; } /** * mono_type_get_signature: * \param type the \c MonoType operated on * It is only valid to call this function if \p type is a \c MONO_TYPE_FNPTR . * \returns the \c MonoMethodSignature pointer that describes the signature * of the function pointer \p type represents. */ static inline MonoMethodSignature* mono_type_get_signature_internal (MonoType *type) { g_assert (type->type == MONO_TYPE_FNPTR); return type->data.method; } /** * m_type_is_byref: * \param type the \c MonoType operated on * \returns TRUE if \p type represents a type passed by reference, * FALSE otherwise. */ static inline gboolean m_type_is_byref (const MonoType *type) { return type->byref__; } /** * mono_type_get_class_internal: * \param type the \c MonoType operated on * It is only valid to call this function if \p type is a \c MONO_TYPE_CLASS or a * \c MONO_TYPE_VALUETYPE . For more general functionality, use \c mono_class_from_mono_type_internal, * instead. * \returns the \c MonoClass pointer that describes the class that \p type represents. */ static inline MonoClass* mono_type_get_class_internal (MonoType *type) { /* FIXME: review the runtime users before adding the assert here */ return type->data.klass; } /** * mono_type_get_array_type_internal: * \param type the \c MonoType operated on * It is only valid to call this function if \p type is a \c MONO_TYPE_ARRAY . * \returns a \c MonoArrayType struct describing the array type that \p type * represents. The info includes details such as rank, array element type * and the sizes and bounds of multidimensional arrays. */ static inline MonoArrayType* mono_type_get_array_type_internal (MonoType *type) { return type->data.array; } static inline int mono_metadata_table_to_ptr_table (int table_num) { switch (table_num) { case MONO_TABLE_FIELD: return MONO_TABLE_FIELD_POINTER; case MONO_TABLE_METHOD: return MONO_TABLE_METHOD_POINTER; case MONO_TABLE_PARAM: return MONO_TABLE_PARAM_POINTER; case MONO_TABLE_PROPERTY: return MONO_TABLE_PROPERTY_POINTER; case MONO_TABLE_EVENT: return MONO_TABLE_EVENT_POINTER; default: g_assert_not_reached (); } } #endif /* __MONO_METADATA_INTERNALS_H__ */
1
dotnet/runtime
66,452
[mono] Stop setting time_date_stamp field in MonoImage
We never read that field in the runtime and it was causing unnecessary disk IO during startup (5ms on my iOS device). It was also never set on Windows already.
akoeplinger
2022-03-10T15:49:37Z
2022-03-10T21:47:58Z
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
d2826308964e4ee4496d6884e09811e1f709005e
[mono] Stop setting time_date_stamp field in MonoImage. We never read that field in the runtime and it was causing unnecessary disk IO during startup (5ms on my iOS device). It was also never set on Windows already.
./src/mono/mono/utils/mono-proclib.c
/** * \file * Copyright 2008-2011 Novell Inc * Copyright 2011 Xamarin Inc * Licensed under the MIT license. See LICENSE file in the project root for full license information. */ #include "config.h" #include "utils/mono-proclib.h" #include "utils/mono-time.h" #include "utils/mono-errno.h" #include <stdlib.h> #include <stdio.h> #include <string.h> #include <fcntl.h> #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef HAVE_SCHED_GETAFFINITY #include <sched.h> #endif #include <utils/mono-mmap.h> #include <utils/strenc-internals.h> #include <utils/strenc.h> #include <utils/mono-error-internals.h> #include <utils/mono-logger-internals.h> #if defined(_POSIX_VERSION) #ifdef HAVE_SYS_ERRNO_H #include <sys/errno.h> #endif #ifdef HAVE_SYS_PARAM_H #include <sys/param.h> #endif #include <errno.h> #ifdef HAVE_SYS_TYPES_H #include <sys/types.h> #endif #ifdef HAVE_SYS_SYSCTL_H #include <sys/sysctl.h> #endif #ifdef HAVE_SYS_RESOURCE_H #include <sys/resource.h> #endif #endif #if defined(__HAIKU__) #include <os/kernel/OS.h> #endif #if defined(_AIX) #include <procinfo.h> #endif #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) #include <sys/proc.h> #if defined(__APPLE__) #include <mach/mach.h> #endif #ifdef HAVE_SYS_USER_H #include <sys/user.h> #endif #ifdef HAVE_STRUCT_KINFO_PROC_KP_PROC # define kinfo_starttime_member kp_proc.p_starttime # define kinfo_pid_member kp_proc.p_pid # define kinfo_name_member kp_proc.p_comm #elif defined(__NetBSD__) # define kinfo_starttime_member p_ustart_sec # define kinfo_pid_member p_pid # define kinfo_name_member p_comm #elif defined(__OpenBSD__) // Can not figure out how to get the proc's start time on OpenBSD # undef kinfo_starttime_member # define kinfo_pid_member p_pid # define kinfo_name_member p_comm #else #define kinfo_starttime_member ki_start #define kinfo_pid_member ki_pid #define kinfo_name_member ki_comm #endif #define USE_SYSCTL 1 #endif #ifdef HAVE_SCHED_GETAFFINITY # ifndef HAVE_GNU_CPU_COUNT static int CPU_COUNT(cpu_set_t *set) { int i, count = 0; for (int i = 0; i < CPU_SETSIZE; i++) if (CPU_ISSET(i, set)) count++; return count; } # endif #endif /** * mono_process_list: * \param size a pointer to a location where the size of the returned array is stored * \returns an array of pid values for the processes currently running on the system. * The size of the array is stored in \p size. */ gpointer* mono_process_list (int *size) { #if USE_SYSCTL int res, i; #ifdef KERN_PROC2 int mib [6]; size_t data_len = sizeof (struct kinfo_proc2) * 400; struct kinfo_proc2 *processes = g_malloc (data_len); #else int mib [4]; size_t data_len = sizeof (struct kinfo_proc) * 16; struct kinfo_proc *processes; int limit = 8; #endif /* KERN_PROC2 */ void **buf = NULL; if (size) *size = 0; #ifdef KERN_PROC2 if (!processes) return NULL; mib [0] = CTL_KERN; mib [1] = KERN_PROC2; mib [2] = KERN_PROC_ALL; mib [3] = 0; mib [4] = sizeof(struct kinfo_proc2); mib [5] = 400; /* XXX */ res = sysctl (mib, 6, processes, &data_len, NULL, 0); if (res < 0) { g_free (processes); return NULL; } #else processes = NULL; while (limit) { mib [0] = CTL_KERN; mib [1] = KERN_PROC; mib [2] = KERN_PROC_ALL; mib [3] = 0; res = sysctl (mib, 3, NULL, &data_len, NULL, 0); if (res) return NULL; processes = (struct kinfo_proc *) g_malloc (data_len); res = sysctl (mib, 3, processes, &data_len, NULL, 0); if (res < 0) { g_free (processes); if (errno != ENOMEM) return NULL; limit --; } else { break; } } #endif /* KERN_PROC2 */ #ifdef KERN_PROC2 res = data_len/sizeof (struct kinfo_proc2); #else res = data_len/sizeof (struct kinfo_proc); #endif /* KERN_PROC2 */ buf = (void **) g_realloc (buf, res * sizeof (void*)); for (i = 0; i < res; ++i) buf [i] = GINT_TO_POINTER (processes [i].kinfo_pid_member); g_free (processes); if (size) *size = res; return buf; #elif defined(__HAIKU__) int32 cookie = 0; int32 i = 0; team_info ti; system_info si; get_system_info(&si); void **buf = g_calloc(si.used_teams, sizeof(void*)); while (get_next_team_info(&cookie, &ti) == B_OK && i < si.used_teams) { buf[i++] = GINT_TO_POINTER (ti.team); } *size = i; return buf; #elif defined(_AIX) void **buf = NULL; struct procentry64 *procs = NULL; int count = 0; int i = 0; pid_t pid = 1; // start at 1, 0 is a null process (???) // count number of procs + compensate for new ones forked in while we do it. // (it's not an atomic operation) 1000000 is the limit IBM ps seems to use // when I inspected it under truss. the second call we do to getprocs64 will // then only allocate what we need, instead of allocating some obscenely large // array on the heap. count = getprocs64(NULL, sizeof (struct procentry64), NULL, 0, &pid, 1000000); if (count < 1) goto cleanup; count += 10; pid = 1; // reset the pid cookie // 5026 bytes is the ideal size for the C struct. you may not like it, but // this is what peak allocation looks like procs = g_calloc (count, sizeof (struct procentry64)); // the man page recommends you do this in a loop, but you can also just do it // in one shot; again, like what ps does. let the returned count (in case it's // less) be what we then allocate the array of pids from (in case of ANOTHER // system-wide race condition with processes) count = getprocs64 (procs, sizeof (struct procentry64), NULL, 0, &pid, count); if (count < 1 || procs == NULL) goto cleanup; buf = g_calloc (count, sizeof (void*)); for (i = 0; i < count; i++) { buf[i] = GINT_TO_POINTER (procs[i].pi_pid); } *size = i; cleanup: g_free (procs); return buf; #else const char *name; void **buf = NULL; int count = 0; int i = 0; GDir *dir = g_dir_open ("/proc/", 0, NULL); if (!dir) { if (size) *size = 0; return NULL; } while ((name = g_dir_read_name (dir))) { int pid; char *nend; pid = strtol (name, &nend, 10); if (pid <= 0 || nend == name || *nend) continue; if (i >= count) { if (!count) count = 16; else count *= 2; buf = (void **)g_realloc (buf, count * sizeof (void*)); } buf [i++] = GINT_TO_POINTER (pid); } g_dir_close (dir); if (size) *size = i; return buf; #endif } static G_GNUC_UNUSED char* get_pid_status_item_buf (int pid, const char *item, char *rbuf, int blen, MonoProcessError *error) { char buf [256]; char *s; FILE *f; size_t len = strlen (item); g_snprintf (buf, sizeof (buf), "/proc/%d/status", pid); f = fopen (buf, "r"); if (!f) { if (error) *error = MONO_PROCESS_ERROR_NOT_FOUND; return NULL; } while ((s = fgets (buf, sizeof (buf), f))) { if (*item != *buf) continue; if (strncmp (buf, item, len)) continue; s = buf + len; while (g_ascii_isspace (*s)) s++; if (*s++ != ':') continue; while (g_ascii_isspace (*s)) s++; fclose (f); len = strlen (s); memcpy (rbuf, s, MIN (len, blen)); rbuf [MIN (len, blen) - 1] = 0; if (error) *error = MONO_PROCESS_ERROR_NONE; return rbuf; } fclose (f); if (error) *error = MONO_PROCESS_ERROR_OTHER; return NULL; } #if USE_SYSCTL #ifdef KERN_PROC2 #define KINFO_PROC struct kinfo_proc2 #else #define KINFO_PROC struct kinfo_proc #endif static gboolean sysctl_kinfo_proc (gpointer pid, KINFO_PROC* processi) { int res; size_t data_len = sizeof (KINFO_PROC); #ifdef KERN_PROC2 int mib [6]; mib [0] = CTL_KERN; mib [1] = KERN_PROC2; mib [2] = KERN_PROC_PID; mib [3] = GPOINTER_TO_UINT (pid); mib [4] = sizeof(KINFO_PROC); mib [5] = 400; /* XXX */ res = sysctl (mib, 6, processi, &data_len, NULL, 0); #else int mib [4]; mib [0] = CTL_KERN; mib [1] = KERN_PROC; mib [2] = KERN_PROC_PID; mib [3] = GPOINTER_TO_UINT (pid); res = sysctl (mib, 4, processi, &data_len, NULL, 0); #endif /* KERN_PROC2 */ if (res < 0 || data_len != sizeof (KINFO_PROC)) return FALSE; return TRUE; } #endif /* USE_SYSCTL */ /** * mono_process_get_name: * \param pid pid of the process * \param buf byte buffer where to store the name of the prcoess * \param len size of the buffer \p buf * \returns the name of the process identified by \p pid, storing it * inside \p buf for a maximum of len bytes (including the terminating 0). */ char* mono_process_get_name (gpointer pid, char *buf, int len) { #if USE_SYSCTL KINFO_PROC processi; memset (buf, 0, len); if (sysctl_kinfo_proc (pid, &processi)) memcpy (buf, processi.kinfo_name_member, len - 1); return buf; #elif defined(_AIX) struct procentry64 proc; pid_t newpid = GPOINTER_TO_INT (pid); if (getprocs64 (&proc, sizeof (struct procentry64), NULL, 0, &newpid, 1) == 1) { g_strlcpy (buf, proc.pi_comm, len - 1); } return buf; #else char fname [128]; FILE *file; char *p; size_t r; sprintf (fname, "/proc/%d/cmdline", GPOINTER_TO_INT (pid)); buf [0] = 0; file = fopen (fname, "r"); if (!file) return buf; r = fread (buf, 1, len - 1, file); fclose (file); buf [r] = 0; p = strrchr (buf, '/'); if (p) return p + 1; if (r == 0) { return get_pid_status_item_buf (GPOINTER_TO_INT (pid), "Name", buf, len, NULL); } return buf; #endif } void mono_process_get_times (gpointer pid, gint64 *start_time, gint64 *user_time, gint64 *kernel_time) { if (user_time) *user_time = mono_process_get_data (pid, MONO_PROCESS_USER_TIME); if (kernel_time) *kernel_time = mono_process_get_data (pid, MONO_PROCESS_SYSTEM_TIME); if (start_time) { *start_time = 0; #if USE_SYSCTL && defined(kinfo_starttime_member) { KINFO_PROC processi; if (sysctl_kinfo_proc (pid, &processi)) { #if defined(__NetBSD__) struct timeval tv; tv.tv_sec = processi.kinfo_starttime_member; tv.tv_usec = processi.p_ustart_usec; *start_time = mono_100ns_datetime_from_timeval(tv); #else *start_time = mono_100ns_datetime_from_timeval (processi.kinfo_starttime_member); #endif } } #endif if (*start_time == 0) { static guint64 boot_time = 0; if (!boot_time) boot_time = mono_100ns_datetime () - mono_msec_boottime () * 10000; *start_time = boot_time + mono_process_get_data (pid, MONO_PROCESS_ELAPSED); } } } /* * /proc/pid/stat format: * pid (cmdname) S * [0] ppid pgid sid tty_nr tty_pgrp flags min_flt cmin_flt maj_flt cmaj_flt * [10] utime stime cutime cstime prio nice threads 0 start_time vsize * [20] rss rsslim start_code end_code start_stack esp eip pending blocked sigign * [30] sigcatch wchan 0 0 exit_signal cpu rt_prio policy */ #define RET_ERROR(err) do { \ if (error) *error = (err); \ return 0; \ } while (0) static gint64 get_process_stat_item (int pid, int pos, int sum, MonoProcessError *error) { #if defined(__APPLE__) double process_user_time = 0, process_system_time = 0;//, process_percent = 0; task_t task; struct task_basic_info t_info; mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT, th_count; thread_array_t th_array; size_t i; kern_return_t ret; if (pid == getpid ()) { /* task_for_pid () doesn't work on ios, even for the current process */ task = mach_task_self (); } else { do { ret = task_for_pid (mach_task_self (), pid, &task); } while (ret == KERN_ABORTED); if (ret != KERN_SUCCESS) RET_ERROR (MONO_PROCESS_ERROR_NOT_FOUND); } do { ret = task_info (task, TASK_BASIC_INFO, (task_info_t)&t_info, &t_info_count); } while (ret == KERN_ABORTED); if (ret != KERN_SUCCESS) { if (pid != getpid ()) mach_port_deallocate (mach_task_self (), task); RET_ERROR (MONO_PROCESS_ERROR_OTHER); } do { ret = task_threads (task, &th_array, &th_count); } while (ret == KERN_ABORTED); if (ret != KERN_SUCCESS) { if (pid != getpid ()) mach_port_deallocate (mach_task_self (), task); RET_ERROR (MONO_PROCESS_ERROR_OTHER); } for (i = 0; i < th_count; i++) { double thread_user_time, thread_system_time;//, thread_percent; struct thread_basic_info th_info; mach_msg_type_number_t th_info_count = THREAD_BASIC_INFO_COUNT; do { ret = thread_info(th_array[i], THREAD_BASIC_INFO, (thread_info_t)&th_info, &th_info_count); } while (ret == KERN_ABORTED); if (ret == KERN_SUCCESS) { thread_user_time = th_info.user_time.seconds + th_info.user_time.microseconds / 1e6; thread_system_time = th_info.system_time.seconds + th_info.system_time.microseconds / 1e6; //thread_percent = (double)th_info.cpu_usage / TH_USAGE_SCALE; process_user_time += thread_user_time; process_system_time += thread_system_time; //process_percent += th_percent; } } for (i = 0; i < th_count; i++) mach_port_deallocate(task, th_array[i]); if (pid != getpid ()) mach_port_deallocate (mach_task_self (), task); process_user_time += t_info.user_time.seconds + t_info.user_time.microseconds / 1e6; process_system_time += t_info.system_time.seconds + t_info.system_time.microseconds / 1e6; if (pos == 10 && sum == TRUE) return (gint64)((process_user_time + process_system_time) * 10000000); else if (pos == 10) return (gint64)(process_user_time * 10000000); else if (pos == 11) return (gint64)(process_system_time * 10000000); return 0; #else char buf [512]; char *s, *end; FILE *f; size_t len; int i; gint64 value; g_snprintf (buf, sizeof (buf), "/proc/%d/stat", pid); f = fopen (buf, "r"); if (!f) RET_ERROR (MONO_PROCESS_ERROR_NOT_FOUND); len = fread (buf, 1, sizeof (buf), f); fclose (f); if (len <= 0) RET_ERROR (MONO_PROCESS_ERROR_OTHER); s = strchr (buf, ')'); if (!s) RET_ERROR (MONO_PROCESS_ERROR_OTHER); s++; while (g_ascii_isspace (*s)) s++; if (!*s) RET_ERROR (MONO_PROCESS_ERROR_OTHER); /* skip the status char */ while (*s && !g_ascii_isspace (*s)) s++; if (!*s) RET_ERROR (MONO_PROCESS_ERROR_OTHER); for (i = 0; i < pos; ++i) { while (g_ascii_isspace (*s)) s++; if (!*s) RET_ERROR (MONO_PROCESS_ERROR_OTHER); while (*s && !g_ascii_isspace (*s)) s++; if (!*s) RET_ERROR (MONO_PROCESS_ERROR_OTHER); } /* we are finally at the needed item */ value = strtoul (s, &end, 0); /* add also the following value */ if (sum) { while (g_ascii_isspace (*s)) s++; if (!*s) RET_ERROR (MONO_PROCESS_ERROR_OTHER); value += strtoul (s, &end, 0); } if (error) *error = MONO_PROCESS_ERROR_NONE; return value; #endif } static int get_user_hz (void) { static int user_hz = 0; if (user_hz == 0) { #if defined (_SC_CLK_TCK) && defined (HAVE_SYSCONF) user_hz = sysconf (_SC_CLK_TCK); #endif if (user_hz == 0) user_hz = 100; } return user_hz; } static gint64 get_process_stat_time (int pid, int pos, int sum, MonoProcessError *error) { gint64 val = get_process_stat_item (pid, pos, sum, error); #if defined(__APPLE__) return val; #else /* return 100ns ticks */ return (val * 10000000) / get_user_hz (); #endif } static gint64 get_pid_status_item (int pid, const char *item, MonoProcessError *error, int multiplier) { #if defined(__APPLE__) // ignore the multiplier gint64 ret; task_t task; task_vm_info_data_t t_info; mach_msg_type_number_t info_count = TASK_VM_INFO_COUNT; kern_return_t mach_ret; if (pid == getpid ()) { /* task_for_pid () doesn't work on ios, even for the current process */ task = mach_task_self (); } else { do { mach_ret = task_for_pid (mach_task_self (), pid, &task); } while (mach_ret == KERN_ABORTED); if (mach_ret != KERN_SUCCESS) RET_ERROR (MONO_PROCESS_ERROR_NOT_FOUND); } do { mach_ret = task_info (task, TASK_VM_INFO, (task_info_t)&t_info, &info_count); } while (mach_ret == KERN_ABORTED); if (mach_ret != KERN_SUCCESS) { if (pid != getpid ()) mach_port_deallocate (mach_task_self (), task); RET_ERROR (MONO_PROCESS_ERROR_OTHER); } if(strcmp (item, "VmData") == 0) ret = t_info.internal + t_info.compressed; else if (strcmp (item, "VmRSS") == 0) ret = t_info.resident_size; else if(strcmp (item, "VmHWM") == 0) ret = t_info.resident_size_peak; else if (strcmp (item, "VmSize") == 0 || strcmp (item, "VmPeak") == 0) ret = t_info.virtual_size; else if (strcmp (item, "Threads") == 0) { struct task_basic_info t_info; mach_msg_type_number_t th_count = TASK_BASIC_INFO_COUNT; do { mach_ret = task_info (task, TASK_BASIC_INFO, (task_info_t)&t_info, &th_count); } while (mach_ret == KERN_ABORTED); if (mach_ret != KERN_SUCCESS) { if (pid != getpid ()) mach_port_deallocate (mach_task_self (), task); RET_ERROR (MONO_PROCESS_ERROR_OTHER); } ret = th_count; } else if (strcmp (item, "VmSwap") == 0) ret = t_info.compressed; else ret = 0; if (pid != getpid ()) mach_port_deallocate (mach_task_self (), task); return ret; #else char buf [64]; char *s; s = get_pid_status_item_buf (pid, item, buf, sizeof (buf), error); if (s) return ((gint64) atol (s)) * multiplier; return 0; #endif } /** * mono_process_get_data: * \param pid pid of the process * \param data description of data to return * \returns a data item of a process like user time, memory use etc, * according to the \p data argumet. */ gint64 mono_process_get_data_with_error (gpointer pid, MonoProcessData data, MonoProcessError *error) { gint64 val; int rpid = GPOINTER_TO_INT (pid); if (error) *error = MONO_PROCESS_ERROR_OTHER; switch (data) { case MONO_PROCESS_NUM_THREADS: return get_pid_status_item (rpid, "Threads", error, 1); case MONO_PROCESS_USER_TIME: return get_process_stat_time (rpid, 10, FALSE, error); case MONO_PROCESS_SYSTEM_TIME: return get_process_stat_time (rpid, 11, FALSE, error); case MONO_PROCESS_TOTAL_TIME: return get_process_stat_time (rpid, 10, TRUE, error); case MONO_PROCESS_WORKING_SET: return get_pid_status_item (rpid, "VmRSS", error, 1024); case MONO_PROCESS_WORKING_SET_PEAK: val = get_pid_status_item (rpid, "VmHWM", error, 1024); if (val == 0) val = get_pid_status_item (rpid, "VmRSS", error, 1024); return val; case MONO_PROCESS_PRIVATE_BYTES: return get_pid_status_item (rpid, "VmData", error, 1024); case MONO_PROCESS_VIRTUAL_BYTES: return get_pid_status_item (rpid, "VmSize", error, 1024); case MONO_PROCESS_VIRTUAL_BYTES_PEAK: val = get_pid_status_item (rpid, "VmPeak", error, 1024); if (val == 0) val = get_pid_status_item (rpid, "VmSize", error, 1024); return val; case MONO_PROCESS_FAULTS: return get_process_stat_item (rpid, 6, TRUE, error); case MONO_PROCESS_ELAPSED: return get_process_stat_time (rpid, 18, FALSE, error); case MONO_PROCESS_PPID: return get_process_stat_time (rpid, 0, FALSE, error); case MONO_PROCESS_PAGED_BYTES: return get_pid_status_item (rpid, "VmSwap", error, 1024); /* Nothing yet */ case MONO_PROCESS_END: return 0; } return 0; } gint64 mono_process_get_data (gpointer pid, MonoProcessData data) { MonoProcessError error; return mono_process_get_data_with_error (pid, data, &error); } #ifndef HOST_WIN32 int mono_process_current_pid () { #if defined(HAVE_GETPID) return (int) getpid (); #elif defined(HOST_WASI) return 0; #else #error getpid #endif } #endif /* !HOST_WIN32 */ /** * mono_cpu_count: * \returns the number of processors on the system. */ #ifndef HOST_WIN32 int mono_cpu_count (void) { #ifdef HOST_ANDROID /* Android tries really hard to save power by powering off CPUs on SMP phones which * means the normal way to query cpu count returns a wrong value with userspace API. * Instead we use /sys entries to query the actual hardware CPU count. */ int count = 0; char buffer[8] = {'\0'}; int present = open ("/sys/devices/system/cpu/present", O_RDONLY); /* Format of the /sys entry is a cpulist of indexes which in the case * of present is always of the form "0-(n-1)" when there is more than * 1 core, n being the number of CPU cores in the system. Otherwise * the value is simply 0 */ if (present != -1 && read (present, (char*)buffer, sizeof (buffer)) > 3) count = strtol (((char*)buffer) + 2, NULL, 10); if (present != -1) close (present); if (count > 0) return count + 1; #endif #if defined(HOST_ARM) || defined (HOST_ARM64) /* * Recap from Alexander Köplinger <[email protected]>: * * When we merged the change from PR #2722, we started seeing random failures on ARM in * the MonoTests.System.Threading.ThreadPoolTests.SetAndGetMaxThreads and * MonoTests.System.Threading.ManualResetEventSlimTests.Constructor_Defaults tests. Both * of those tests are dealing with Environment.ProcessorCount to verify some implementation * details. * * It turns out that on the Jetson TK1 board we use on public Jenkins and on ARM kernels * in general, the value returned by sched_getaffinity (or _SC_NPROCESSORS_ONLN) doesn't * contain CPUs/cores that are powered off for power saving reasons. This is contrary to * what happens on x86, where even cores in deep-sleep state are returned [1], [2]. This * means that we would get a processor count of 1 at one point in time and a higher value * when load increases later on as the system wakes CPUs. * * Various runtime pieces like the threadpool and also user code however relies on the * value returned by Environment.ProcessorCount e.g. for deciding how many parallel tasks * to start, thereby limiting the performance when that code thinks we only have one CPU. * * Talking to a few people, this was the reason why we changed to _SC_NPROCESSORS_CONF in * mono#1688 and why we added a special case for Android in mono@de3addc to get the "real" * number of processors in the system. * * Because of those issues Android/Dalvik also switched from _ONLN to _SC_NPROCESSORS_CONF * for the Java API Runtime.availableProcessors() too [3], citing: * > Traditionally this returned the number currently online, but many mobile devices are * able to take unused cores offline to save power, so releases newer than Android 4.2 (Jelly * Bean) return the maximum number of cores that could be made available if there were no * power or heat constraints. * * The problem with sticking to _SC_NPROCESSORS_CONF however is that it breaks down in * constrained environments like Docker or with an explicit CPU affinity set by the Linux * `taskset` command, They'd get a higher CPU count than can be used, start more threads etc. * which results in unnecessary context switches and overloaded systems. That's why we need * to respect sched_getaffinity. * * So while in an ideal world we would be able to rely on sched_getaffinity/_SC_NPROCESSORS_ONLN * to return the number of theoretically available CPUs regardless of power saving measures * everywhere, we can't do this on ARM. * * I think the pragmatic solution is the following: * * use sched_getaffinity (+ fallback to _SC_NPROCESSORS_ONLN in case of error) on x86. This * ensures we're inline with what OpenJDK [4] and CoreCLR [5] do * * use _SC_NPROCESSORS_CONF exclusively on ARM (I think we could eventually even get rid of * the HOST_ANDROID special case) * * Helpful links: * * [1] https://sourceware.org/ml/libc-alpha/2013-07/msg00383.html * [2] https://lists.01.org/pipermail/powertop/2012-September/000433.html * [3] https://android.googlesource.com/platform/libcore/+/750dc634e56c58d1d04f6a138734ac2b772900b5%5E1..750dc634e56c58d1d04f6a138734ac2b772900b5/ * [4] https://bugs.openjdk.java.net/browse/JDK-6515172 * [5] https://github.com/dotnet/coreclr/blob/7058273693db2555f127ce16e6b0c5b40fb04867/src/pal/src/misc/sysinfo.cpp#L148 */ #if defined (_SC_NPROCESSORS_CONF) && defined (HAVE_SYSCONF) { int count = sysconf (_SC_NPROCESSORS_CONF); if (count > 0) return count; } #endif #else #ifdef HAVE_SCHED_GETAFFINITY { cpu_set_t set; if (sched_getaffinity (mono_process_current_pid (), sizeof (set), &set) == 0) return CPU_COUNT (&set); } #endif #if defined (_SC_NPROCESSORS_ONLN) && defined (HAVE_SYSCONF) { int count = sysconf (_SC_NPROCESSORS_ONLN); if (count > 0) return count; } #endif #endif /* defined(HOST_ARM) || defined (HOST_ARM64) */ #ifdef USE_SYSCTL { int count; int mib [2]; size_t len = sizeof (int); mib [0] = CTL_HW; mib [1] = HW_NCPU; if (sysctl (mib, 2, &count, &len, NULL, 0) == 0) return count; } #endif /* FIXME: warn */ return 1; } #endif /* !HOST_WIN32 */ static void get_cpu_times (int cpu_id, gint64 *user, gint64 *systemt, gint64 *irq, gint64 *sirq, gint64 *idle) { char buf [256]; char *s; int uhz = get_user_hz (); guint64 user_ticks = 0, nice_ticks = 0, system_ticks = 0, idle_ticks = 0, irq_ticks = 0, sirq_ticks = 0; FILE *f = fopen ("/proc/stat", "r"); if (!f) return; if (cpu_id < 0) uhz *= mono_cpu_count (); while ((s = fgets (buf, sizeof (buf), f))) { char *data = NULL; if (cpu_id < 0 && strncmp (s, "cpu", 3) == 0 && g_ascii_isspace (s [3])) { data = s + 4; } else if (cpu_id >= 0 && strncmp (s, "cpu", 3) == 0 && strtol (s + 3, &data, 10) == cpu_id) { if (data == s + 3) continue; data++; } else { continue; } user_ticks = strtoull (data, &data, 10); nice_ticks = strtoull (data, &data, 10); system_ticks = strtoull (data, &data, 10); idle_ticks = strtoull (data, &data, 10); /* iowait_ticks = strtoull (data, &data, 10); */ irq_ticks = strtoull (data, &data, 10); sirq_ticks = strtoull (data, &data, 10); break; } fclose (f); if (user) *user = (user_ticks + nice_ticks) * 10000000 / uhz; if (systemt) *systemt = (system_ticks) * 10000000 / uhz; if (irq) *irq = (irq_ticks) * 10000000 / uhz; if (sirq) *sirq = (sirq_ticks) * 10000000 / uhz; if (idle) *idle = (idle_ticks) * 10000000 / uhz; } /** * mono_cpu_get_data: * \param cpu_id processor number or -1 to get a summary of all the processors * \param data type of data to retrieve * Get data about a processor on the system, like time spent in user space or idle time. */ gint64 mono_cpu_get_data (int cpu_id, MonoCpuData data, MonoProcessError *error) { gint64 value = 0; if (error) *error = MONO_PROCESS_ERROR_NONE; switch (data) { case MONO_CPU_USER_TIME: get_cpu_times (cpu_id, &value, NULL, NULL, NULL, NULL); break; case MONO_CPU_PRIV_TIME: get_cpu_times (cpu_id, NULL, &value, NULL, NULL, NULL); break; case MONO_CPU_INTR_TIME: get_cpu_times (cpu_id, NULL, NULL, &value, NULL, NULL); break; case MONO_CPU_DCP_TIME: get_cpu_times (cpu_id, NULL, NULL, NULL, &value, NULL); break; case MONO_CPU_IDLE_TIME: get_cpu_times (cpu_id, NULL, NULL, NULL, NULL, &value); break; case MONO_CPU_END: /* Nothing yet */ return 0; } return value; } int mono_atexit (void (*func)(void)) { #if defined(HOST_ANDROID) || !defined(HAVE_ATEXIT) /* Some versions of android libc doesn't define atexit () */ return 0; #else return atexit (func); #endif } #ifndef HOST_WIN32 gboolean mono_pe_file_time_date_stamp (const gunichar2 *filename, guint32 *out) { void *map_handle; guint32 map_size; gpointer file_map = mono_pe_file_map (filename, &map_size, &map_handle); if (!file_map) return FALSE; /* Figure this out when we support 64bit PE files */ if (1) { IMAGE_DOS_HEADER *dos_header = (IMAGE_DOS_HEADER *)file_map; if (dos_header->e_magic != IMAGE_DOS_SIGNATURE) { mono_pe_file_unmap (file_map, map_handle); return FALSE; } IMAGE_NT_HEADERS32 *nt_headers = (IMAGE_NT_HEADERS32 *)((guint8 *)file_map + GUINT32_FROM_LE (dos_header->e_lfanew)); if (nt_headers->Signature != IMAGE_NT_SIGNATURE) { mono_pe_file_unmap (file_map, map_handle); return FALSE; } *out = nt_headers->FileHeader.TimeDateStamp; } else { g_assert_not_reached (); } mono_pe_file_unmap (file_map, map_handle); return TRUE; } gpointer mono_pe_file_map (const gunichar2 *filename, guint32 *map_size, void **handle) { gchar *filename_ext = NULL; gchar *located_filename = NULL; guint64 fsize = 0; gpointer file_map = NULL; ERROR_DECL (error); MonoFileMap *filed = NULL; /* According to the MSDN docs, a search path is applied to * filename. FIXME: implement this, for now just pass it * straight to open */ filename_ext = mono_unicode_to_external_checked (filename, error); // This block was added to diagnose https://github.com/mono/mono/issues/14730, remove after resolved if (G_UNLIKELY (filename_ext == NULL)) { GString *raw_bytes = g_string_new (NULL); const gunichar2 *p = filename; while (*p) g_string_append_printf (raw_bytes, "%04X ", *p++); g_assertf (filename_ext != NULL, "%s: unicode conversion returned NULL; %s; input was: %s", __func__, mono_error_get_message (error), raw_bytes->str); g_string_free (raw_bytes, TRUE); } if (filename_ext == NULL) { mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: unicode conversion returned NULL; %s", __func__, mono_error_get_message (error)); mono_error_cleanup (error); goto exit; } if ((filed = mono_file_map_open (filename_ext)) == NULL) { mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: Error opening file %s (3): %s", __func__, filename_ext, strerror (errno)); goto exit; } fsize = mono_file_map_size (filed); if (fsize == 0) { mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: Error stat()ing file %s: %s", __func__, filename_ext, strerror (errno)); goto exit; } g_assert (fsize <= G_MAXUINT32); *map_size = fsize; /* Check basic file size */ if (fsize < sizeof(IMAGE_DOS_HEADER)) { mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: File %s is too small: %" PRId64, __func__, filename_ext, fsize); goto exit; } file_map = mono_file_map (fsize, MONO_MMAP_READ | MONO_MMAP_PRIVATE, mono_file_map_fd (filed), 0, handle); if (file_map == NULL) { mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: Error mmap()int file %s: %s", __func__, filename_ext, strerror (errno)); goto exit; } exit: if (filed) mono_file_map_close (filed); g_free (located_filename); g_free (filename_ext); return file_map; } void mono_pe_file_unmap (gpointer file_map, void *handle) { gint res; res = mono_file_unmap (file_map, handle); if (G_UNLIKELY (res != 0)) g_error ("%s: mono_file_unmap failed, error: \"%s\" (%d)", __func__, g_strerror (errno), errno); } #endif /* HOST_WIN32 */ /* * This function returns the cpu usage in percentage, * normalized on the number of cores. * * Warning : the percentage returned can be > 100%. This * might happens on systems like Android which, for * battery and performance reasons, shut down cores and * lie about the number of active cores. */ #ifndef HOST_WIN32 gint32 mono_cpu_usage (MonoCpuUsageState *prev) { gint32 cpu_usage = 0; #ifdef HAVE_GETRUSAGE gint64 cpu_total_time; gint64 cpu_busy_time; struct rusage resource_usage; gint64 current_time; gint64 kernel_time; gint64 user_time; if (getrusage (RUSAGE_SELF, &resource_usage) == -1) { g_error ("getrusage() failed, errno is %d (%s)\n", errno, strerror (errno)); return -1; } current_time = mono_100ns_ticks (); kernel_time = resource_usage.ru_stime.tv_sec * 1000 * 1000 * 10 + resource_usage.ru_stime.tv_usec * 10; user_time = resource_usage.ru_utime.tv_sec * 1000 * 1000 * 10 + resource_usage.ru_utime.tv_usec * 10; cpu_busy_time = (user_time - (prev ? prev->user_time : 0)) + (kernel_time - (prev ? prev->kernel_time : 0)); cpu_total_time = (current_time - (prev ? prev->current_time : 0)) * mono_cpu_count (); if (prev) { prev->kernel_time = kernel_time; prev->user_time = user_time; prev->current_time = current_time; } if (cpu_total_time > 0 && cpu_busy_time > 0) cpu_usage = (gint32)(cpu_busy_time * 100 / cpu_total_time); #endif return cpu_usage; } #endif /* !HOST_WIN32 */
/** * \file * Copyright 2008-2011 Novell Inc * Copyright 2011 Xamarin Inc * Licensed under the MIT license. See LICENSE file in the project root for full license information. */ #include "config.h" #include "utils/mono-proclib.h" #include "utils/mono-time.h" #include "utils/mono-errno.h" #include <stdlib.h> #include <stdio.h> #include <string.h> #include <fcntl.h> #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef HAVE_SCHED_GETAFFINITY #include <sched.h> #endif #include <utils/mono-mmap.h> #include <utils/strenc-internals.h> #include <utils/strenc.h> #include <utils/mono-error-internals.h> #include <utils/mono-logger-internals.h> #if defined(_POSIX_VERSION) #ifdef HAVE_SYS_ERRNO_H #include <sys/errno.h> #endif #ifdef HAVE_SYS_PARAM_H #include <sys/param.h> #endif #include <errno.h> #ifdef HAVE_SYS_TYPES_H #include <sys/types.h> #endif #ifdef HAVE_SYS_SYSCTL_H #include <sys/sysctl.h> #endif #ifdef HAVE_SYS_RESOURCE_H #include <sys/resource.h> #endif #endif #if defined(__HAIKU__) #include <os/kernel/OS.h> #endif #if defined(_AIX) #include <procinfo.h> #endif #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) #include <sys/proc.h> #if defined(__APPLE__) #include <mach/mach.h> #endif #ifdef HAVE_SYS_USER_H #include <sys/user.h> #endif #ifdef HAVE_STRUCT_KINFO_PROC_KP_PROC # define kinfo_starttime_member kp_proc.p_starttime # define kinfo_pid_member kp_proc.p_pid # define kinfo_name_member kp_proc.p_comm #elif defined(__NetBSD__) # define kinfo_starttime_member p_ustart_sec # define kinfo_pid_member p_pid # define kinfo_name_member p_comm #elif defined(__OpenBSD__) // Can not figure out how to get the proc's start time on OpenBSD # undef kinfo_starttime_member # define kinfo_pid_member p_pid # define kinfo_name_member p_comm #else #define kinfo_starttime_member ki_start #define kinfo_pid_member ki_pid #define kinfo_name_member ki_comm #endif #define USE_SYSCTL 1 #endif #ifdef HAVE_SCHED_GETAFFINITY # ifndef HAVE_GNU_CPU_COUNT static int CPU_COUNT(cpu_set_t *set) { int i, count = 0; for (int i = 0; i < CPU_SETSIZE; i++) if (CPU_ISSET(i, set)) count++; return count; } # endif #endif /** * mono_process_list: * \param size a pointer to a location where the size of the returned array is stored * \returns an array of pid values for the processes currently running on the system. * The size of the array is stored in \p size. */ gpointer* mono_process_list (int *size) { #if USE_SYSCTL int res, i; #ifdef KERN_PROC2 int mib [6]; size_t data_len = sizeof (struct kinfo_proc2) * 400; struct kinfo_proc2 *processes = g_malloc (data_len); #else int mib [4]; size_t data_len = sizeof (struct kinfo_proc) * 16; struct kinfo_proc *processes; int limit = 8; #endif /* KERN_PROC2 */ void **buf = NULL; if (size) *size = 0; #ifdef KERN_PROC2 if (!processes) return NULL; mib [0] = CTL_KERN; mib [1] = KERN_PROC2; mib [2] = KERN_PROC_ALL; mib [3] = 0; mib [4] = sizeof(struct kinfo_proc2); mib [5] = 400; /* XXX */ res = sysctl (mib, 6, processes, &data_len, NULL, 0); if (res < 0) { g_free (processes); return NULL; } #else processes = NULL; while (limit) { mib [0] = CTL_KERN; mib [1] = KERN_PROC; mib [2] = KERN_PROC_ALL; mib [3] = 0; res = sysctl (mib, 3, NULL, &data_len, NULL, 0); if (res) return NULL; processes = (struct kinfo_proc *) g_malloc (data_len); res = sysctl (mib, 3, processes, &data_len, NULL, 0); if (res < 0) { g_free (processes); if (errno != ENOMEM) return NULL; limit --; } else { break; } } #endif /* KERN_PROC2 */ #ifdef KERN_PROC2 res = data_len/sizeof (struct kinfo_proc2); #else res = data_len/sizeof (struct kinfo_proc); #endif /* KERN_PROC2 */ buf = (void **) g_realloc (buf, res * sizeof (void*)); for (i = 0; i < res; ++i) buf [i] = GINT_TO_POINTER (processes [i].kinfo_pid_member); g_free (processes); if (size) *size = res; return buf; #elif defined(__HAIKU__) int32 cookie = 0; int32 i = 0; team_info ti; system_info si; get_system_info(&si); void **buf = g_calloc(si.used_teams, sizeof(void*)); while (get_next_team_info(&cookie, &ti) == B_OK && i < si.used_teams) { buf[i++] = GINT_TO_POINTER (ti.team); } *size = i; return buf; #elif defined(_AIX) void **buf = NULL; struct procentry64 *procs = NULL; int count = 0; int i = 0; pid_t pid = 1; // start at 1, 0 is a null process (???) // count number of procs + compensate for new ones forked in while we do it. // (it's not an atomic operation) 1000000 is the limit IBM ps seems to use // when I inspected it under truss. the second call we do to getprocs64 will // then only allocate what we need, instead of allocating some obscenely large // array on the heap. count = getprocs64(NULL, sizeof (struct procentry64), NULL, 0, &pid, 1000000); if (count < 1) goto cleanup; count += 10; pid = 1; // reset the pid cookie // 5026 bytes is the ideal size for the C struct. you may not like it, but // this is what peak allocation looks like procs = g_calloc (count, sizeof (struct procentry64)); // the man page recommends you do this in a loop, but you can also just do it // in one shot; again, like what ps does. let the returned count (in case it's // less) be what we then allocate the array of pids from (in case of ANOTHER // system-wide race condition with processes) count = getprocs64 (procs, sizeof (struct procentry64), NULL, 0, &pid, count); if (count < 1 || procs == NULL) goto cleanup; buf = g_calloc (count, sizeof (void*)); for (i = 0; i < count; i++) { buf[i] = GINT_TO_POINTER (procs[i].pi_pid); } *size = i; cleanup: g_free (procs); return buf; #else const char *name; void **buf = NULL; int count = 0; int i = 0; GDir *dir = g_dir_open ("/proc/", 0, NULL); if (!dir) { if (size) *size = 0; return NULL; } while ((name = g_dir_read_name (dir))) { int pid; char *nend; pid = strtol (name, &nend, 10); if (pid <= 0 || nend == name || *nend) continue; if (i >= count) { if (!count) count = 16; else count *= 2; buf = (void **)g_realloc (buf, count * sizeof (void*)); } buf [i++] = GINT_TO_POINTER (pid); } g_dir_close (dir); if (size) *size = i; return buf; #endif } static G_GNUC_UNUSED char* get_pid_status_item_buf (int pid, const char *item, char *rbuf, int blen, MonoProcessError *error) { char buf [256]; char *s; FILE *f; size_t len = strlen (item); g_snprintf (buf, sizeof (buf), "/proc/%d/status", pid); f = fopen (buf, "r"); if (!f) { if (error) *error = MONO_PROCESS_ERROR_NOT_FOUND; return NULL; } while ((s = fgets (buf, sizeof (buf), f))) { if (*item != *buf) continue; if (strncmp (buf, item, len)) continue; s = buf + len; while (g_ascii_isspace (*s)) s++; if (*s++ != ':') continue; while (g_ascii_isspace (*s)) s++; fclose (f); len = strlen (s); memcpy (rbuf, s, MIN (len, blen)); rbuf [MIN (len, blen) - 1] = 0; if (error) *error = MONO_PROCESS_ERROR_NONE; return rbuf; } fclose (f); if (error) *error = MONO_PROCESS_ERROR_OTHER; return NULL; } #if USE_SYSCTL #ifdef KERN_PROC2 #define KINFO_PROC struct kinfo_proc2 #else #define KINFO_PROC struct kinfo_proc #endif static gboolean sysctl_kinfo_proc (gpointer pid, KINFO_PROC* processi) { int res; size_t data_len = sizeof (KINFO_PROC); #ifdef KERN_PROC2 int mib [6]; mib [0] = CTL_KERN; mib [1] = KERN_PROC2; mib [2] = KERN_PROC_PID; mib [3] = GPOINTER_TO_UINT (pid); mib [4] = sizeof(KINFO_PROC); mib [5] = 400; /* XXX */ res = sysctl (mib, 6, processi, &data_len, NULL, 0); #else int mib [4]; mib [0] = CTL_KERN; mib [1] = KERN_PROC; mib [2] = KERN_PROC_PID; mib [3] = GPOINTER_TO_UINT (pid); res = sysctl (mib, 4, processi, &data_len, NULL, 0); #endif /* KERN_PROC2 */ if (res < 0 || data_len != sizeof (KINFO_PROC)) return FALSE; return TRUE; } #endif /* USE_SYSCTL */ /** * mono_process_get_name: * \param pid pid of the process * \param buf byte buffer where to store the name of the prcoess * \param len size of the buffer \p buf * \returns the name of the process identified by \p pid, storing it * inside \p buf for a maximum of len bytes (including the terminating 0). */ char* mono_process_get_name (gpointer pid, char *buf, int len) { #if USE_SYSCTL KINFO_PROC processi; memset (buf, 0, len); if (sysctl_kinfo_proc (pid, &processi)) memcpy (buf, processi.kinfo_name_member, len - 1); return buf; #elif defined(_AIX) struct procentry64 proc; pid_t newpid = GPOINTER_TO_INT (pid); if (getprocs64 (&proc, sizeof (struct procentry64), NULL, 0, &newpid, 1) == 1) { g_strlcpy (buf, proc.pi_comm, len - 1); } return buf; #else char fname [128]; FILE *file; char *p; size_t r; sprintf (fname, "/proc/%d/cmdline", GPOINTER_TO_INT (pid)); buf [0] = 0; file = fopen (fname, "r"); if (!file) return buf; r = fread (buf, 1, len - 1, file); fclose (file); buf [r] = 0; p = strrchr (buf, '/'); if (p) return p + 1; if (r == 0) { return get_pid_status_item_buf (GPOINTER_TO_INT (pid), "Name", buf, len, NULL); } return buf; #endif } void mono_process_get_times (gpointer pid, gint64 *start_time, gint64 *user_time, gint64 *kernel_time) { if (user_time) *user_time = mono_process_get_data (pid, MONO_PROCESS_USER_TIME); if (kernel_time) *kernel_time = mono_process_get_data (pid, MONO_PROCESS_SYSTEM_TIME); if (start_time) { *start_time = 0; #if USE_SYSCTL && defined(kinfo_starttime_member) { KINFO_PROC processi; if (sysctl_kinfo_proc (pid, &processi)) { #if defined(__NetBSD__) struct timeval tv; tv.tv_sec = processi.kinfo_starttime_member; tv.tv_usec = processi.p_ustart_usec; *start_time = mono_100ns_datetime_from_timeval(tv); #else *start_time = mono_100ns_datetime_from_timeval (processi.kinfo_starttime_member); #endif } } #endif if (*start_time == 0) { static guint64 boot_time = 0; if (!boot_time) boot_time = mono_100ns_datetime () - mono_msec_boottime () * 10000; *start_time = boot_time + mono_process_get_data (pid, MONO_PROCESS_ELAPSED); } } } /* * /proc/pid/stat format: * pid (cmdname) S * [0] ppid pgid sid tty_nr tty_pgrp flags min_flt cmin_flt maj_flt cmaj_flt * [10] utime stime cutime cstime prio nice threads 0 start_time vsize * [20] rss rsslim start_code end_code start_stack esp eip pending blocked sigign * [30] sigcatch wchan 0 0 exit_signal cpu rt_prio policy */ #define RET_ERROR(err) do { \ if (error) *error = (err); \ return 0; \ } while (0) static gint64 get_process_stat_item (int pid, int pos, int sum, MonoProcessError *error) { #if defined(__APPLE__) double process_user_time = 0, process_system_time = 0;//, process_percent = 0; task_t task; struct task_basic_info t_info; mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT, th_count; thread_array_t th_array; size_t i; kern_return_t ret; if (pid == getpid ()) { /* task_for_pid () doesn't work on ios, even for the current process */ task = mach_task_self (); } else { do { ret = task_for_pid (mach_task_self (), pid, &task); } while (ret == KERN_ABORTED); if (ret != KERN_SUCCESS) RET_ERROR (MONO_PROCESS_ERROR_NOT_FOUND); } do { ret = task_info (task, TASK_BASIC_INFO, (task_info_t)&t_info, &t_info_count); } while (ret == KERN_ABORTED); if (ret != KERN_SUCCESS) { if (pid != getpid ()) mach_port_deallocate (mach_task_self (), task); RET_ERROR (MONO_PROCESS_ERROR_OTHER); } do { ret = task_threads (task, &th_array, &th_count); } while (ret == KERN_ABORTED); if (ret != KERN_SUCCESS) { if (pid != getpid ()) mach_port_deallocate (mach_task_self (), task); RET_ERROR (MONO_PROCESS_ERROR_OTHER); } for (i = 0; i < th_count; i++) { double thread_user_time, thread_system_time;//, thread_percent; struct thread_basic_info th_info; mach_msg_type_number_t th_info_count = THREAD_BASIC_INFO_COUNT; do { ret = thread_info(th_array[i], THREAD_BASIC_INFO, (thread_info_t)&th_info, &th_info_count); } while (ret == KERN_ABORTED); if (ret == KERN_SUCCESS) { thread_user_time = th_info.user_time.seconds + th_info.user_time.microseconds / 1e6; thread_system_time = th_info.system_time.seconds + th_info.system_time.microseconds / 1e6; //thread_percent = (double)th_info.cpu_usage / TH_USAGE_SCALE; process_user_time += thread_user_time; process_system_time += thread_system_time; //process_percent += th_percent; } } for (i = 0; i < th_count; i++) mach_port_deallocate(task, th_array[i]); if (pid != getpid ()) mach_port_deallocate (mach_task_self (), task); process_user_time += t_info.user_time.seconds + t_info.user_time.microseconds / 1e6; process_system_time += t_info.system_time.seconds + t_info.system_time.microseconds / 1e6; if (pos == 10 && sum == TRUE) return (gint64)((process_user_time + process_system_time) * 10000000); else if (pos == 10) return (gint64)(process_user_time * 10000000); else if (pos == 11) return (gint64)(process_system_time * 10000000); return 0; #else char buf [512]; char *s, *end; FILE *f; size_t len; int i; gint64 value; g_snprintf (buf, sizeof (buf), "/proc/%d/stat", pid); f = fopen (buf, "r"); if (!f) RET_ERROR (MONO_PROCESS_ERROR_NOT_FOUND); len = fread (buf, 1, sizeof (buf), f); fclose (f); if (len <= 0) RET_ERROR (MONO_PROCESS_ERROR_OTHER); s = strchr (buf, ')'); if (!s) RET_ERROR (MONO_PROCESS_ERROR_OTHER); s++; while (g_ascii_isspace (*s)) s++; if (!*s) RET_ERROR (MONO_PROCESS_ERROR_OTHER); /* skip the status char */ while (*s && !g_ascii_isspace (*s)) s++; if (!*s) RET_ERROR (MONO_PROCESS_ERROR_OTHER); for (i = 0; i < pos; ++i) { while (g_ascii_isspace (*s)) s++; if (!*s) RET_ERROR (MONO_PROCESS_ERROR_OTHER); while (*s && !g_ascii_isspace (*s)) s++; if (!*s) RET_ERROR (MONO_PROCESS_ERROR_OTHER); } /* we are finally at the needed item */ value = strtoul (s, &end, 0); /* add also the following value */ if (sum) { while (g_ascii_isspace (*s)) s++; if (!*s) RET_ERROR (MONO_PROCESS_ERROR_OTHER); value += strtoul (s, &end, 0); } if (error) *error = MONO_PROCESS_ERROR_NONE; return value; #endif } static int get_user_hz (void) { static int user_hz = 0; if (user_hz == 0) { #if defined (_SC_CLK_TCK) && defined (HAVE_SYSCONF) user_hz = sysconf (_SC_CLK_TCK); #endif if (user_hz == 0) user_hz = 100; } return user_hz; } static gint64 get_process_stat_time (int pid, int pos, int sum, MonoProcessError *error) { gint64 val = get_process_stat_item (pid, pos, sum, error); #if defined(__APPLE__) return val; #else /* return 100ns ticks */ return (val * 10000000) / get_user_hz (); #endif } static gint64 get_pid_status_item (int pid, const char *item, MonoProcessError *error, int multiplier) { #if defined(__APPLE__) // ignore the multiplier gint64 ret; task_t task; task_vm_info_data_t t_info; mach_msg_type_number_t info_count = TASK_VM_INFO_COUNT; kern_return_t mach_ret; if (pid == getpid ()) { /* task_for_pid () doesn't work on ios, even for the current process */ task = mach_task_self (); } else { do { mach_ret = task_for_pid (mach_task_self (), pid, &task); } while (mach_ret == KERN_ABORTED); if (mach_ret != KERN_SUCCESS) RET_ERROR (MONO_PROCESS_ERROR_NOT_FOUND); } do { mach_ret = task_info (task, TASK_VM_INFO, (task_info_t)&t_info, &info_count); } while (mach_ret == KERN_ABORTED); if (mach_ret != KERN_SUCCESS) { if (pid != getpid ()) mach_port_deallocate (mach_task_self (), task); RET_ERROR (MONO_PROCESS_ERROR_OTHER); } if(strcmp (item, "VmData") == 0) ret = t_info.internal + t_info.compressed; else if (strcmp (item, "VmRSS") == 0) ret = t_info.resident_size; else if(strcmp (item, "VmHWM") == 0) ret = t_info.resident_size_peak; else if (strcmp (item, "VmSize") == 0 || strcmp (item, "VmPeak") == 0) ret = t_info.virtual_size; else if (strcmp (item, "Threads") == 0) { struct task_basic_info t_info; mach_msg_type_number_t th_count = TASK_BASIC_INFO_COUNT; do { mach_ret = task_info (task, TASK_BASIC_INFO, (task_info_t)&t_info, &th_count); } while (mach_ret == KERN_ABORTED); if (mach_ret != KERN_SUCCESS) { if (pid != getpid ()) mach_port_deallocate (mach_task_self (), task); RET_ERROR (MONO_PROCESS_ERROR_OTHER); } ret = th_count; } else if (strcmp (item, "VmSwap") == 0) ret = t_info.compressed; else ret = 0; if (pid != getpid ()) mach_port_deallocate (mach_task_self (), task); return ret; #else char buf [64]; char *s; s = get_pid_status_item_buf (pid, item, buf, sizeof (buf), error); if (s) return ((gint64) atol (s)) * multiplier; return 0; #endif } /** * mono_process_get_data: * \param pid pid of the process * \param data description of data to return * \returns a data item of a process like user time, memory use etc, * according to the \p data argumet. */ gint64 mono_process_get_data_with_error (gpointer pid, MonoProcessData data, MonoProcessError *error) { gint64 val; int rpid = GPOINTER_TO_INT (pid); if (error) *error = MONO_PROCESS_ERROR_OTHER; switch (data) { case MONO_PROCESS_NUM_THREADS: return get_pid_status_item (rpid, "Threads", error, 1); case MONO_PROCESS_USER_TIME: return get_process_stat_time (rpid, 10, FALSE, error); case MONO_PROCESS_SYSTEM_TIME: return get_process_stat_time (rpid, 11, FALSE, error); case MONO_PROCESS_TOTAL_TIME: return get_process_stat_time (rpid, 10, TRUE, error); case MONO_PROCESS_WORKING_SET: return get_pid_status_item (rpid, "VmRSS", error, 1024); case MONO_PROCESS_WORKING_SET_PEAK: val = get_pid_status_item (rpid, "VmHWM", error, 1024); if (val == 0) val = get_pid_status_item (rpid, "VmRSS", error, 1024); return val; case MONO_PROCESS_PRIVATE_BYTES: return get_pid_status_item (rpid, "VmData", error, 1024); case MONO_PROCESS_VIRTUAL_BYTES: return get_pid_status_item (rpid, "VmSize", error, 1024); case MONO_PROCESS_VIRTUAL_BYTES_PEAK: val = get_pid_status_item (rpid, "VmPeak", error, 1024); if (val == 0) val = get_pid_status_item (rpid, "VmSize", error, 1024); return val; case MONO_PROCESS_FAULTS: return get_process_stat_item (rpid, 6, TRUE, error); case MONO_PROCESS_ELAPSED: return get_process_stat_time (rpid, 18, FALSE, error); case MONO_PROCESS_PPID: return get_process_stat_time (rpid, 0, FALSE, error); case MONO_PROCESS_PAGED_BYTES: return get_pid_status_item (rpid, "VmSwap", error, 1024); /* Nothing yet */ case MONO_PROCESS_END: return 0; } return 0; } gint64 mono_process_get_data (gpointer pid, MonoProcessData data) { MonoProcessError error; return mono_process_get_data_with_error (pid, data, &error); } #ifndef HOST_WIN32 int mono_process_current_pid () { #if defined(HAVE_GETPID) return (int) getpid (); #elif defined(HOST_WASI) return 0; #else #error getpid #endif } #endif /* !HOST_WIN32 */ /** * mono_cpu_count: * \returns the number of processors on the system. */ #ifndef HOST_WIN32 int mono_cpu_count (void) { #ifdef HOST_ANDROID /* Android tries really hard to save power by powering off CPUs on SMP phones which * means the normal way to query cpu count returns a wrong value with userspace API. * Instead we use /sys entries to query the actual hardware CPU count. */ int count = 0; char buffer[8] = {'\0'}; int present = open ("/sys/devices/system/cpu/present", O_RDONLY); /* Format of the /sys entry is a cpulist of indexes which in the case * of present is always of the form "0-(n-1)" when there is more than * 1 core, n being the number of CPU cores in the system. Otherwise * the value is simply 0 */ if (present != -1 && read (present, (char*)buffer, sizeof (buffer)) > 3) count = strtol (((char*)buffer) + 2, NULL, 10); if (present != -1) close (present); if (count > 0) return count + 1; #endif #if defined(HOST_ARM) || defined (HOST_ARM64) /* * Recap from Alexander Köplinger <[email protected]>: * * When we merged the change from PR #2722, we started seeing random failures on ARM in * the MonoTests.System.Threading.ThreadPoolTests.SetAndGetMaxThreads and * MonoTests.System.Threading.ManualResetEventSlimTests.Constructor_Defaults tests. Both * of those tests are dealing with Environment.ProcessorCount to verify some implementation * details. * * It turns out that on the Jetson TK1 board we use on public Jenkins and on ARM kernels * in general, the value returned by sched_getaffinity (or _SC_NPROCESSORS_ONLN) doesn't * contain CPUs/cores that are powered off for power saving reasons. This is contrary to * what happens on x86, where even cores in deep-sleep state are returned [1], [2]. This * means that we would get a processor count of 1 at one point in time and a higher value * when load increases later on as the system wakes CPUs. * * Various runtime pieces like the threadpool and also user code however relies on the * value returned by Environment.ProcessorCount e.g. for deciding how many parallel tasks * to start, thereby limiting the performance when that code thinks we only have one CPU. * * Talking to a few people, this was the reason why we changed to _SC_NPROCESSORS_CONF in * mono#1688 and why we added a special case for Android in mono@de3addc to get the "real" * number of processors in the system. * * Because of those issues Android/Dalvik also switched from _ONLN to _SC_NPROCESSORS_CONF * for the Java API Runtime.availableProcessors() too [3], citing: * > Traditionally this returned the number currently online, but many mobile devices are * able to take unused cores offline to save power, so releases newer than Android 4.2 (Jelly * Bean) return the maximum number of cores that could be made available if there were no * power or heat constraints. * * The problem with sticking to _SC_NPROCESSORS_CONF however is that it breaks down in * constrained environments like Docker or with an explicit CPU affinity set by the Linux * `taskset` command, They'd get a higher CPU count than can be used, start more threads etc. * which results in unnecessary context switches and overloaded systems. That's why we need * to respect sched_getaffinity. * * So while in an ideal world we would be able to rely on sched_getaffinity/_SC_NPROCESSORS_ONLN * to return the number of theoretically available CPUs regardless of power saving measures * everywhere, we can't do this on ARM. * * I think the pragmatic solution is the following: * * use sched_getaffinity (+ fallback to _SC_NPROCESSORS_ONLN in case of error) on x86. This * ensures we're inline with what OpenJDK [4] and CoreCLR [5] do * * use _SC_NPROCESSORS_CONF exclusively on ARM (I think we could eventually even get rid of * the HOST_ANDROID special case) * * Helpful links: * * [1] https://sourceware.org/ml/libc-alpha/2013-07/msg00383.html * [2] https://lists.01.org/pipermail/powertop/2012-September/000433.html * [3] https://android.googlesource.com/platform/libcore/+/750dc634e56c58d1d04f6a138734ac2b772900b5%5E1..750dc634e56c58d1d04f6a138734ac2b772900b5/ * [4] https://bugs.openjdk.java.net/browse/JDK-6515172 * [5] https://github.com/dotnet/coreclr/blob/7058273693db2555f127ce16e6b0c5b40fb04867/src/pal/src/misc/sysinfo.cpp#L148 */ #if defined (_SC_NPROCESSORS_CONF) && defined (HAVE_SYSCONF) { int count = sysconf (_SC_NPROCESSORS_CONF); if (count > 0) return count; } #endif #else #ifdef HAVE_SCHED_GETAFFINITY { cpu_set_t set; if (sched_getaffinity (mono_process_current_pid (), sizeof (set), &set) == 0) return CPU_COUNT (&set); } #endif #if defined (_SC_NPROCESSORS_ONLN) && defined (HAVE_SYSCONF) { int count = sysconf (_SC_NPROCESSORS_ONLN); if (count > 0) return count; } #endif #endif /* defined(HOST_ARM) || defined (HOST_ARM64) */ #ifdef USE_SYSCTL { int count; int mib [2]; size_t len = sizeof (int); mib [0] = CTL_HW; mib [1] = HW_NCPU; if (sysctl (mib, 2, &count, &len, NULL, 0) == 0) return count; } #endif /* FIXME: warn */ return 1; } #endif /* !HOST_WIN32 */ static void get_cpu_times (int cpu_id, gint64 *user, gint64 *systemt, gint64 *irq, gint64 *sirq, gint64 *idle) { char buf [256]; char *s; int uhz = get_user_hz (); guint64 user_ticks = 0, nice_ticks = 0, system_ticks = 0, idle_ticks = 0, irq_ticks = 0, sirq_ticks = 0; FILE *f = fopen ("/proc/stat", "r"); if (!f) return; if (cpu_id < 0) uhz *= mono_cpu_count (); while ((s = fgets (buf, sizeof (buf), f))) { char *data = NULL; if (cpu_id < 0 && strncmp (s, "cpu", 3) == 0 && g_ascii_isspace (s [3])) { data = s + 4; } else if (cpu_id >= 0 && strncmp (s, "cpu", 3) == 0 && strtol (s + 3, &data, 10) == cpu_id) { if (data == s + 3) continue; data++; } else { continue; } user_ticks = strtoull (data, &data, 10); nice_ticks = strtoull (data, &data, 10); system_ticks = strtoull (data, &data, 10); idle_ticks = strtoull (data, &data, 10); /* iowait_ticks = strtoull (data, &data, 10); */ irq_ticks = strtoull (data, &data, 10); sirq_ticks = strtoull (data, &data, 10); break; } fclose (f); if (user) *user = (user_ticks + nice_ticks) * 10000000 / uhz; if (systemt) *systemt = (system_ticks) * 10000000 / uhz; if (irq) *irq = (irq_ticks) * 10000000 / uhz; if (sirq) *sirq = (sirq_ticks) * 10000000 / uhz; if (idle) *idle = (idle_ticks) * 10000000 / uhz; } /** * mono_cpu_get_data: * \param cpu_id processor number or -1 to get a summary of all the processors * \param data type of data to retrieve * Get data about a processor on the system, like time spent in user space or idle time. */ gint64 mono_cpu_get_data (int cpu_id, MonoCpuData data, MonoProcessError *error) { gint64 value = 0; if (error) *error = MONO_PROCESS_ERROR_NONE; switch (data) { case MONO_CPU_USER_TIME: get_cpu_times (cpu_id, &value, NULL, NULL, NULL, NULL); break; case MONO_CPU_PRIV_TIME: get_cpu_times (cpu_id, NULL, &value, NULL, NULL, NULL); break; case MONO_CPU_INTR_TIME: get_cpu_times (cpu_id, NULL, NULL, &value, NULL, NULL); break; case MONO_CPU_DCP_TIME: get_cpu_times (cpu_id, NULL, NULL, NULL, &value, NULL); break; case MONO_CPU_IDLE_TIME: get_cpu_times (cpu_id, NULL, NULL, NULL, NULL, &value); break; case MONO_CPU_END: /* Nothing yet */ return 0; } return value; } int mono_atexit (void (*func)(void)) { #if defined(HOST_ANDROID) || !defined(HAVE_ATEXIT) /* Some versions of android libc doesn't define atexit () */ return 0; #else return atexit (func); #endif } /* * This function returns the cpu usage in percentage, * normalized on the number of cores. * * Warning : the percentage returned can be > 100%. This * might happens on systems like Android which, for * battery and performance reasons, shut down cores and * lie about the number of active cores. */ #ifndef HOST_WIN32 gint32 mono_cpu_usage (MonoCpuUsageState *prev) { gint32 cpu_usage = 0; #ifdef HAVE_GETRUSAGE gint64 cpu_total_time; gint64 cpu_busy_time; struct rusage resource_usage; gint64 current_time; gint64 kernel_time; gint64 user_time; if (getrusage (RUSAGE_SELF, &resource_usage) == -1) { g_error ("getrusage() failed, errno is %d (%s)\n", errno, strerror (errno)); return -1; } current_time = mono_100ns_ticks (); kernel_time = resource_usage.ru_stime.tv_sec * 1000 * 1000 * 10 + resource_usage.ru_stime.tv_usec * 10; user_time = resource_usage.ru_utime.tv_sec * 1000 * 1000 * 10 + resource_usage.ru_utime.tv_usec * 10; cpu_busy_time = (user_time - (prev ? prev->user_time : 0)) + (kernel_time - (prev ? prev->kernel_time : 0)); cpu_total_time = (current_time - (prev ? prev->current_time : 0)) * mono_cpu_count (); if (prev) { prev->kernel_time = kernel_time; prev->user_time = user_time; prev->current_time = current_time; } if (cpu_total_time > 0 && cpu_busy_time > 0) cpu_usage = (gint32)(cpu_busy_time * 100 / cpu_total_time); #endif return cpu_usage; } #endif /* !HOST_WIN32 */
1
dotnet/runtime
66,452
[mono] Stop setting time_date_stamp field in MonoImage
We never read that field in the runtime and it was causing unnecessary disk IO during startup (5ms on my iOS device). It was also never set on Windows already.
akoeplinger
2022-03-10T15:49:37Z
2022-03-10T21:47:58Z
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
d2826308964e4ee4496d6884e09811e1f709005e
[mono] Stop setting time_date_stamp field in MonoImage. We never read that field in the runtime and it was causing unnecessary disk IO during startup (5ms on my iOS device). It was also never set on Windows already.
./src/mono/mono/utils/mono-proclib.h
/** * \file */ #ifndef __MONO_PROC_LIB_H__ #define __MONO_PROC_LIB_H__ /* * Utility functions to access processes information and other info about the system. */ #include <glib.h> #include <mono/utils/mono-compiler.h> #include <mono/utils/mono-publib.h> /* never remove or reorder these enums values: they are used in corlib/System */ typedef enum { MONO_PROCESS_NUM_THREADS, MONO_PROCESS_USER_TIME, /* milliseconds */ MONO_PROCESS_SYSTEM_TIME, /* milliseconds */ MONO_PROCESS_TOTAL_TIME, /* milliseconds */ MONO_PROCESS_WORKING_SET, MONO_PROCESS_WORKING_SET_PEAK, /* 5 */ MONO_PROCESS_PRIVATE_BYTES, MONO_PROCESS_VIRTUAL_BYTES, MONO_PROCESS_VIRTUAL_BYTES_PEAK, MONO_PROCESS_FAULTS, MONO_PROCESS_ELAPSED, /* 10 */ MONO_PROCESS_PPID, MONO_PROCESS_PAGED_BYTES, MONO_PROCESS_END } MonoProcessData; typedef enum { MONO_CPU_USER_TIME, MONO_CPU_PRIV_TIME, MONO_CPU_INTR_TIME, MONO_CPU_DCP_TIME, MONO_CPU_IDLE_TIME, MONO_CPU_END } MonoCpuData; typedef enum { MONO_PROCESS_ERROR_NONE, /* no error happened */ MONO_PROCESS_ERROR_NOT_FOUND, /* process not found */ MONO_PROCESS_ERROR_OTHER } MonoProcessError; typedef struct _MonoCpuUsageState MonoCpuUsageState; #ifndef HOST_WIN32 struct _MonoCpuUsageState { gint64 kernel_time; gint64 user_time; gint64 current_time; }; #else struct _MonoCpuUsageState { guint64 kernel_time; guint64 user_time; guint64 idle_time; }; #endif gpointer* mono_process_list (int *size); void mono_process_get_times (gpointer pid, gint64 *start_time, gint64 *user_time, gint64 *kernel_time); char* mono_process_get_name (gpointer pid, char *buf, int len); gint64 mono_process_get_data (gpointer pid, MonoProcessData data); gint64 mono_process_get_data_with_error (gpointer pid, MonoProcessData data, MonoProcessError *error); MONO_COMPONENT_API int mono_process_current_pid (void); MONO_API int mono_cpu_count (void); gint64 mono_cpu_get_data (int cpu_id, MonoCpuData data, MonoProcessError *error); gint32 mono_cpu_usage (MonoCpuUsageState *prev); int mono_atexit (void (*func)(void)); #ifndef HOST_WIN32 #include <sys/stat.h> #include <unistd.h> #define IMAGE_NUMBEROF_DIRECTORY_ENTRIES 16 #define IMAGE_DIRECTORY_ENTRY_EXPORT 0 #define IMAGE_DIRECTORY_ENTRY_IMPORT 1 #define IMAGE_DIRECTORY_ENTRY_RESOURCE 2 #define IMAGE_SIZEOF_SHORT_NAME 8 #if G_BYTE_ORDER != G_LITTLE_ENDIAN #define IMAGE_DOS_SIGNATURE 0x4d5a #define IMAGE_NT_SIGNATURE 0x50450000 #define IMAGE_NT_OPTIONAL_HDR32_MAGIC 0xb10 #define IMAGE_NT_OPTIONAL_HDR64_MAGIC 0xb20 #else #define IMAGE_DOS_SIGNATURE 0x5a4d #define IMAGE_NT_SIGNATURE 0x00004550 #define IMAGE_NT_OPTIONAL_HDR32_MAGIC 0x10b #define IMAGE_NT_OPTIONAL_HDR64_MAGIC 0x20b #endif typedef struct { guint16 e_magic; guint16 e_cblp; guint16 e_cp; guint16 e_crlc; guint16 e_cparhdr; guint16 e_minalloc; guint16 e_maxalloc; guint16 e_ss; guint16 e_sp; guint16 e_csum; guint16 e_ip; guint16 e_cs; guint16 e_lfarlc; guint16 e_ovno; guint16 e_res[4]; guint16 e_oemid; guint16 e_oeminfo; guint16 e_res2[10]; guint32 e_lfanew; } IMAGE_DOS_HEADER; typedef struct { guint16 Machine; guint16 NumberOfSections; guint32 TimeDateStamp; guint32 PointerToSymbolTable; guint32 NumberOfSymbols; guint16 SizeOfOptionalHeader; guint16 Characteristics; } IMAGE_FILE_HEADER; typedef struct { guint32 VirtualAddress; guint32 Size; } IMAGE_DATA_DIRECTORY; typedef struct { guint16 Magic; guint8 MajorLinkerVersion; guint8 MinorLinkerVersion; guint32 SizeOfCode; guint32 SizeOfInitializedData; guint32 SizeOfUninitializedData; guint32 AddressOfEntryPoint; guint32 BaseOfCode; guint32 BaseOfData; guint32 ImageBase; guint32 SectionAlignment; guint32 FileAlignment; guint16 MajorOperatingSystemVersion; guint16 MinorOperatingSystemVersion; guint16 MajorImageVersion; guint16 MinorImageVersion; guint16 MajorSubsystemVersion; guint16 MinorSubsystemVersion; guint32 Win32VersionValue; guint32 SizeOfImage; guint32 SizeOfHeaders; guint32 CheckSum; guint16 Subsystem; guint16 DllCharacteristics; guint32 SizeOfStackReserve; guint32 SizeOfStackCommit; guint32 SizeOfHeapReserve; guint32 SizeOfHeapCommit; guint32 LoaderFlags; guint32 NumberOfRvaAndSizes; IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES]; } IMAGE_OPTIONAL_HEADER32; typedef struct { guint16 Magic; guint8 MajorLinkerVersion; guint8 MinorLinkerVersion; guint32 SizeOfCode; guint32 SizeOfInitializedData; guint32 SizeOfUninitializedData; guint32 AddressOfEntryPoint; guint32 BaseOfCode; guint64 ImageBase; guint32 SectionAlignment; guint32 FileAlignment; guint16 MajorOperatingSystemVersion; guint16 MinorOperatingSystemVersion; guint16 MajorImageVersion; guint16 MinorImageVersion; guint16 MajorSubsystemVersion; guint16 MinorSubsystemVersion; guint32 Win32VersionValue; guint32 SizeOfImage; guint32 SizeOfHeaders; guint32 CheckSum; guint16 Subsystem; guint16 DllCharacteristics; guint64 SizeOfStackReserve; guint64 SizeOfStackCommit; guint64 SizeOfHeapReserve; guint64 SizeOfHeapCommit; guint32 LoaderFlags; guint32 NumberOfRvaAndSizes; IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES]; } IMAGE_OPTIONAL_HEADER64; #if SIZEOF_VOID_P == 8 typedef IMAGE_OPTIONAL_HEADER64 IMAGE_OPTIONAL_HEADER; #else typedef IMAGE_OPTIONAL_HEADER32 IMAGE_OPTIONAL_HEADER; #endif typedef struct { guint32 Signature; IMAGE_FILE_HEADER FileHeader; IMAGE_OPTIONAL_HEADER32 OptionalHeader; } IMAGE_NT_HEADERS32; typedef struct { guint32 Signature; IMAGE_FILE_HEADER FileHeader; IMAGE_OPTIONAL_HEADER64 OptionalHeader; } IMAGE_NT_HEADERS64; #if SIZEOF_VOID_P == 8 typedef IMAGE_NT_HEADERS64 IMAGE_NT_HEADERS; #else typedef IMAGE_NT_HEADERS32 IMAGE_NT_HEADERS; #endif typedef struct { guint8 Name[IMAGE_SIZEOF_SHORT_NAME]; union { guint32 PhysicalAddress; guint32 VirtualSize; } Misc; guint32 VirtualAddress; guint32 SizeOfRawData; guint32 PointerToRawData; guint32 PointerToRelocations; guint32 PointerToLinenumbers; guint16 NumberOfRelocations; guint16 NumberOfLinenumbers; guint32 Characteristics; } IMAGE_SECTION_HEADER; #define IMAGE_FIRST_SECTION32(header) ((IMAGE_SECTION_HEADER *)((gsize)(header) + G_STRUCT_OFFSET (IMAGE_NT_HEADERS32, OptionalHeader) + GUINT16_FROM_LE (((IMAGE_NT_HEADERS32 *)(header))->FileHeader.SizeOfOptionalHeader))) #define RT_CURSOR 0x01 #define RT_BITMAP 0x02 #define RT_ICON 0x03 #define RT_MENU 0x04 #define RT_DIALOG 0x05 #define RT_STRING 0x06 #define RT_FONTDIR 0x07 #define RT_FONT 0x08 #define RT_ACCELERATOR 0x09 #define RT_RCDATA 0x0a #define RT_MESSAGETABLE 0x0b #define RT_GROUP_CURSOR 0x0c #define RT_GROUP_ICON 0x0e #define RT_VERSION 0x10 #define RT_DLGINCLUDE 0x11 #define RT_PLUGPLAY 0x13 #define RT_VXD 0x14 #define RT_ANICURSOR 0x15 #define RT_ANIICON 0x16 #define RT_HTML 0x17 #define RT_MANIFEST 0x18 typedef struct { guint32 Characteristics; guint32 TimeDateStamp; guint16 MajorVersion; guint16 MinorVersion; guint16 NumberOfNamedEntries; guint16 NumberOfIdEntries; } IMAGE_RESOURCE_DIRECTORY; typedef struct { union { struct { #if G_BYTE_ORDER == G_BIG_ENDIAN guint32 NameIsString:1; guint32 NameOffset:31; #else guint32 NameOffset:31; guint32 NameIsString:1; #endif }; guint32 Name; #if G_BYTE_ORDER == G_BIG_ENDIAN struct { guint16 __wapi_big_endian_padding; guint16 Id; }; #else guint16 Id; #endif }; union { guint32 OffsetToData; struct { #if G_BYTE_ORDER == G_BIG_ENDIAN guint32 DataIsDirectory:1; guint32 OffsetToDirectory:31; #else guint32 OffsetToDirectory:31; guint32 DataIsDirectory:1; #endif }; }; } IMAGE_RESOURCE_DIRECTORY_ENTRY; typedef struct { guint32 OffsetToData; guint32 Size; guint32 CodePage; guint32 Reserved; } IMAGE_RESOURCE_DATA_ENTRY; gboolean mono_pe_file_time_date_stamp (const gunichar2 *filename, guint32 *out); gpointer mono_pe_file_map (const gunichar2 *filename, guint32 *map_size, void **handle); void mono_pe_file_unmap (gpointer file_map, void *handle); #endif /* HOST_WIN32 */ #endif /* __MONO_PROC_LIB_H__ */
/** * \file */ #ifndef __MONO_PROC_LIB_H__ #define __MONO_PROC_LIB_H__ /* * Utility functions to access processes information and other info about the system. */ #include <glib.h> #include <mono/utils/mono-compiler.h> #include <mono/utils/mono-publib.h> /* never remove or reorder these enums values: they are used in corlib/System */ typedef enum { MONO_PROCESS_NUM_THREADS, MONO_PROCESS_USER_TIME, /* milliseconds */ MONO_PROCESS_SYSTEM_TIME, /* milliseconds */ MONO_PROCESS_TOTAL_TIME, /* milliseconds */ MONO_PROCESS_WORKING_SET, MONO_PROCESS_WORKING_SET_PEAK, /* 5 */ MONO_PROCESS_PRIVATE_BYTES, MONO_PROCESS_VIRTUAL_BYTES, MONO_PROCESS_VIRTUAL_BYTES_PEAK, MONO_PROCESS_FAULTS, MONO_PROCESS_ELAPSED, /* 10 */ MONO_PROCESS_PPID, MONO_PROCESS_PAGED_BYTES, MONO_PROCESS_END } MonoProcessData; typedef enum { MONO_CPU_USER_TIME, MONO_CPU_PRIV_TIME, MONO_CPU_INTR_TIME, MONO_CPU_DCP_TIME, MONO_CPU_IDLE_TIME, MONO_CPU_END } MonoCpuData; typedef enum { MONO_PROCESS_ERROR_NONE, /* no error happened */ MONO_PROCESS_ERROR_NOT_FOUND, /* process not found */ MONO_PROCESS_ERROR_OTHER } MonoProcessError; typedef struct _MonoCpuUsageState MonoCpuUsageState; #ifndef HOST_WIN32 struct _MonoCpuUsageState { gint64 kernel_time; gint64 user_time; gint64 current_time; }; #else struct _MonoCpuUsageState { guint64 kernel_time; guint64 user_time; guint64 idle_time; }; #endif gpointer* mono_process_list (int *size); void mono_process_get_times (gpointer pid, gint64 *start_time, gint64 *user_time, gint64 *kernel_time); char* mono_process_get_name (gpointer pid, char *buf, int len); gint64 mono_process_get_data (gpointer pid, MonoProcessData data); gint64 mono_process_get_data_with_error (gpointer pid, MonoProcessData data, MonoProcessError *error); MONO_COMPONENT_API int mono_process_current_pid (void); MONO_API int mono_cpu_count (void); gint64 mono_cpu_get_data (int cpu_id, MonoCpuData data, MonoProcessError *error); gint32 mono_cpu_usage (MonoCpuUsageState *prev); int mono_atexit (void (*func)(void)); #ifndef HOST_WIN32 #include <sys/stat.h> #include <unistd.h> #define IMAGE_NUMBEROF_DIRECTORY_ENTRIES 16 #define IMAGE_DIRECTORY_ENTRY_EXPORT 0 #define IMAGE_DIRECTORY_ENTRY_IMPORT 1 #define IMAGE_DIRECTORY_ENTRY_RESOURCE 2 #define IMAGE_SIZEOF_SHORT_NAME 8 #if G_BYTE_ORDER != G_LITTLE_ENDIAN #define IMAGE_DOS_SIGNATURE 0x4d5a #define IMAGE_NT_SIGNATURE 0x50450000 #define IMAGE_NT_OPTIONAL_HDR32_MAGIC 0xb10 #define IMAGE_NT_OPTIONAL_HDR64_MAGIC 0xb20 #else #define IMAGE_DOS_SIGNATURE 0x5a4d #define IMAGE_NT_SIGNATURE 0x00004550 #define IMAGE_NT_OPTIONAL_HDR32_MAGIC 0x10b #define IMAGE_NT_OPTIONAL_HDR64_MAGIC 0x20b #endif typedef struct { guint16 e_magic; guint16 e_cblp; guint16 e_cp; guint16 e_crlc; guint16 e_cparhdr; guint16 e_minalloc; guint16 e_maxalloc; guint16 e_ss; guint16 e_sp; guint16 e_csum; guint16 e_ip; guint16 e_cs; guint16 e_lfarlc; guint16 e_ovno; guint16 e_res[4]; guint16 e_oemid; guint16 e_oeminfo; guint16 e_res2[10]; guint32 e_lfanew; } IMAGE_DOS_HEADER; typedef struct { guint16 Machine; guint16 NumberOfSections; guint32 TimeDateStamp; guint32 PointerToSymbolTable; guint32 NumberOfSymbols; guint16 SizeOfOptionalHeader; guint16 Characteristics; } IMAGE_FILE_HEADER; typedef struct { guint32 VirtualAddress; guint32 Size; } IMAGE_DATA_DIRECTORY; typedef struct { guint16 Magic; guint8 MajorLinkerVersion; guint8 MinorLinkerVersion; guint32 SizeOfCode; guint32 SizeOfInitializedData; guint32 SizeOfUninitializedData; guint32 AddressOfEntryPoint; guint32 BaseOfCode; guint32 BaseOfData; guint32 ImageBase; guint32 SectionAlignment; guint32 FileAlignment; guint16 MajorOperatingSystemVersion; guint16 MinorOperatingSystemVersion; guint16 MajorImageVersion; guint16 MinorImageVersion; guint16 MajorSubsystemVersion; guint16 MinorSubsystemVersion; guint32 Win32VersionValue; guint32 SizeOfImage; guint32 SizeOfHeaders; guint32 CheckSum; guint16 Subsystem; guint16 DllCharacteristics; guint32 SizeOfStackReserve; guint32 SizeOfStackCommit; guint32 SizeOfHeapReserve; guint32 SizeOfHeapCommit; guint32 LoaderFlags; guint32 NumberOfRvaAndSizes; IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES]; } IMAGE_OPTIONAL_HEADER32; typedef struct { guint16 Magic; guint8 MajorLinkerVersion; guint8 MinorLinkerVersion; guint32 SizeOfCode; guint32 SizeOfInitializedData; guint32 SizeOfUninitializedData; guint32 AddressOfEntryPoint; guint32 BaseOfCode; guint64 ImageBase; guint32 SectionAlignment; guint32 FileAlignment; guint16 MajorOperatingSystemVersion; guint16 MinorOperatingSystemVersion; guint16 MajorImageVersion; guint16 MinorImageVersion; guint16 MajorSubsystemVersion; guint16 MinorSubsystemVersion; guint32 Win32VersionValue; guint32 SizeOfImage; guint32 SizeOfHeaders; guint32 CheckSum; guint16 Subsystem; guint16 DllCharacteristics; guint64 SizeOfStackReserve; guint64 SizeOfStackCommit; guint64 SizeOfHeapReserve; guint64 SizeOfHeapCommit; guint32 LoaderFlags; guint32 NumberOfRvaAndSizes; IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES]; } IMAGE_OPTIONAL_HEADER64; #if SIZEOF_VOID_P == 8 typedef IMAGE_OPTIONAL_HEADER64 IMAGE_OPTIONAL_HEADER; #else typedef IMAGE_OPTIONAL_HEADER32 IMAGE_OPTIONAL_HEADER; #endif typedef struct { guint32 Signature; IMAGE_FILE_HEADER FileHeader; IMAGE_OPTIONAL_HEADER32 OptionalHeader; } IMAGE_NT_HEADERS32; typedef struct { guint32 Signature; IMAGE_FILE_HEADER FileHeader; IMAGE_OPTIONAL_HEADER64 OptionalHeader; } IMAGE_NT_HEADERS64; #if SIZEOF_VOID_P == 8 typedef IMAGE_NT_HEADERS64 IMAGE_NT_HEADERS; #else typedef IMAGE_NT_HEADERS32 IMAGE_NT_HEADERS; #endif typedef struct { guint8 Name[IMAGE_SIZEOF_SHORT_NAME]; union { guint32 PhysicalAddress; guint32 VirtualSize; } Misc; guint32 VirtualAddress; guint32 SizeOfRawData; guint32 PointerToRawData; guint32 PointerToRelocations; guint32 PointerToLinenumbers; guint16 NumberOfRelocations; guint16 NumberOfLinenumbers; guint32 Characteristics; } IMAGE_SECTION_HEADER; #define IMAGE_FIRST_SECTION32(header) ((IMAGE_SECTION_HEADER *)((gsize)(header) + G_STRUCT_OFFSET (IMAGE_NT_HEADERS32, OptionalHeader) + GUINT16_FROM_LE (((IMAGE_NT_HEADERS32 *)(header))->FileHeader.SizeOfOptionalHeader))) #define RT_CURSOR 0x01 #define RT_BITMAP 0x02 #define RT_ICON 0x03 #define RT_MENU 0x04 #define RT_DIALOG 0x05 #define RT_STRING 0x06 #define RT_FONTDIR 0x07 #define RT_FONT 0x08 #define RT_ACCELERATOR 0x09 #define RT_RCDATA 0x0a #define RT_MESSAGETABLE 0x0b #define RT_GROUP_CURSOR 0x0c #define RT_GROUP_ICON 0x0e #define RT_VERSION 0x10 #define RT_DLGINCLUDE 0x11 #define RT_PLUGPLAY 0x13 #define RT_VXD 0x14 #define RT_ANICURSOR 0x15 #define RT_ANIICON 0x16 #define RT_HTML 0x17 #define RT_MANIFEST 0x18 typedef struct { guint32 Characteristics; guint32 TimeDateStamp; guint16 MajorVersion; guint16 MinorVersion; guint16 NumberOfNamedEntries; guint16 NumberOfIdEntries; } IMAGE_RESOURCE_DIRECTORY; typedef struct { union { struct { #if G_BYTE_ORDER == G_BIG_ENDIAN guint32 NameIsString:1; guint32 NameOffset:31; #else guint32 NameOffset:31; guint32 NameIsString:1; #endif }; guint32 Name; #if G_BYTE_ORDER == G_BIG_ENDIAN struct { guint16 __wapi_big_endian_padding; guint16 Id; }; #else guint16 Id; #endif }; union { guint32 OffsetToData; struct { #if G_BYTE_ORDER == G_BIG_ENDIAN guint32 DataIsDirectory:1; guint32 OffsetToDirectory:31; #else guint32 OffsetToDirectory:31; guint32 DataIsDirectory:1; #endif }; }; } IMAGE_RESOURCE_DIRECTORY_ENTRY; typedef struct { guint32 OffsetToData; guint32 Size; guint32 CodePage; guint32 Reserved; } IMAGE_RESOURCE_DATA_ENTRY; #endif /* HOST_WIN32 */ #endif /* __MONO_PROC_LIB_H__ */
1
dotnet/runtime
66,452
[mono] Stop setting time_date_stamp field in MonoImage
We never read that field in the runtime and it was causing unnecessary disk IO during startup (5ms on my iOS device). It was also never set on Windows already.
akoeplinger
2022-03-10T15:49:37Z
2022-03-10T21:47:58Z
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
d2826308964e4ee4496d6884e09811e1f709005e
[mono] Stop setting time_date_stamp field in MonoImage. We never read that field in the runtime and it was causing unnecessary disk IO during startup (5ms on my iOS device). It was also never set on Windows already.
./src/coreclr/pal/tests/palsuite/c_runtime/fwprintf/fwprintf.h
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*============================================================================ ** ** Source: fwprintf.h ** ** Purpose: Containts common testing functions for fwprintf ** ** **==========================================================================*/ #ifndef __fwprintf_H__ #define __fwprintf_H__ inline void DoStrTest_fwprintf(const WCHAR *formatstr, char* param, const char *checkstr) { FILE *fp; char buf[256] = { 0 }; if ((fp = fopen("testfile.txt", "w+")) == NULL ) { Fail("ERROR: fopen failed to create testfile\n"); } if ((fwprintf(fp, formatstr, param)) < 0) { Fail("ERROR: fwprintf failed\n"); } if ((fseek(fp, 0, SEEK_SET)) != 0) { Fail("ERROR: fseek failed\n"); } if ((fgets(buf, 100, fp)) == NULL) { Fail("ERROR: fseek failed\n"); } if (memcmp(buf, checkstr, strlen(checkstr) + 1) != 0) { Fail("ERROR: failed to insert string \"%\" into \"%S\"\n" "Expected \"%s\" got \"%s\".\n", param, formatstr, checkstr, buf); } fclose(fp); } #define DoStrTest DoStrTest_fwprintf inline void DoWStrTest_fwprintf(const WCHAR *formatstr, WCHAR* param, const char *checkstr) { FILE *fp; char buf[256] = { 0 }; if ((fp = fopen("testfile.txt", "w+")) == NULL ) { Fail("ERROR: fopen failed to create testfile\n"); } if ((fwprintf(fp, formatstr, param)) < 0) { Fail("ERROR: fwprintf failed\n"); } if ((fseek(fp, 0, SEEK_SET)) != 0) { Fail("ERROR: fseek failed\n"); } if ((fgets(buf, 100, fp)) == NULL) { Fail("ERROR: fseek failed\n"); } if (memcmp(buf, checkstr, strlen(checkstr) + 1) != 0) { Fail("ERROR: failed to insert wide string \"%s\" into \"%S\"\n" "Expected \"%s\" got \"%s\".\n", convertC(param), formatstr, checkstr, buf); } fclose(fp); } #define DoWStrTest DoWStrTest_fwprintf inline void DoPointerTest_fwprintf(const WCHAR *formatstr, void* param, char* paramstr, const char *checkstr1, const char *checkstr2) { FILE *fp; char buf[256] = { 0 }; if ((fp = fopen("testfile.txt", "w+")) == NULL ) { Fail("ERROR: fopen failed to create testfile\n"); } if ((fwprintf(fp, formatstr, param)) < 0) { Fail("ERROR: fwprintf failed\n"); } if ((fseek(fp, 0, SEEK_SET)) != 0) { Fail("ERROR: fseek failed\n"); } if ((fgets(buf, 100, fp)) == NULL) { Fail("ERROR: fseek failed\n"); } if (memcmp(buf, checkstr1, strlen(checkstr1) + 1) != 0 && memcmp(buf, checkstr2, strlen(checkstr2) + 1) != 0 ) { Fail("ERROR: failed to insert %s into \"%s\"\n" "Expected \"%s\" or \"%s\" got \"%s\".\n", paramstr, formatstr, checkstr1, checkstr2, buf); } if ((fclose( fp )) != 0) { Fail("ERROR: fclose failed to close \"testfile.txt\"\n"); } } #define DoPointerTest DoPointerTest_fwprintf inline void DoCountTest_fwprintf(const WCHAR *formatstr, int param, const char *checkstr) { FILE *fp; char buf[512] = { 0 }; int n = -1; if ((fp = fopen("testfile.txt", "w+")) == NULL ) { Fail("ERROR: fopen failed to create testfile\n"); } if ((fwprintf(fp, formatstr, &n)) < 0) { Fail("ERROR: fwprintf failed\n"); } if ((fseek(fp, 0, SEEK_SET)) != 0) { Fail("ERROR: fseek failed\n"); } if ((fgets(buf, sizeof(buf), fp)) == NULL) { Fail("ERROR: fseek failed\n"); } if (n != param) { Fail("ERROR: Expected count parameter to resolve to %d, got %X\n", param, n); } if (memcmp(buf, checkstr, strlen(checkstr) + 1) != 0) { Fail("ERROR: Expected \"%s\" got \"%s\".\n", checkstr, buf); } if ((fclose( fp )) != 0) { Fail("ERROR: fclose failed to close \"testfile.txt\"\n"); } } #define DoCountTest DoCountTest_fwprintf inline void DoShortCountTest_fwprintf(const WCHAR *formatstr, int param, const char *checkstr) { FILE *fp; char buf[512] = { 0 }; short int n = -1; if ((fp = fopen("testfile.txt", "w+")) == NULL ) { Fail("ERROR: fopen failed to create testfile\n"); } if ((fwprintf(fp, formatstr, &n)) < 0) { Fail("ERROR: fwprintf failed\n"); } if ((fseek(fp, 0, SEEK_SET)) != 0) { Fail("ERROR: fseek failed\n"); } if ((fgets(buf, 100, fp)) == NULL) { Fail("ERROR: fseek failed\n"); } if (n != param) { Fail("ERROR: Expected count parameter to resolve to %d, got %X\n", param, n); } if (memcmp(buf, checkstr, strlen(checkstr) + 1) != 0) { Fail("ERROR: Expected \"%s\" got \"%s\".\n", checkstr, buf); } if ((fclose( fp )) != 0) { Fail("ERROR: fclose failed to close \"testfile.txt\"\n"); } } #define DoShortCountTest DoShortCountTest_fwprintf inline void DoCharTest_fwprintf(const WCHAR *formatstr, char param, const char *checkstr) { FILE *fp; char buf[256] = { 0 }; if ((fp = fopen("testfile.txt", "w+")) == NULL ) { Fail("ERROR: fopen failed to create testfile\n"); } if ((fwprintf(fp, formatstr, param)) < 0) { Fail("ERROR: fwprintf failed\n"); } if ((fseek(fp, 0, SEEK_SET)) != 0) { Fail("ERROR: fseek failed\n"); } if ((fgets(buf, 100, fp)) == NULL) { Fail("ERROR: fseek failed\n"); } if (memcmp(buf, checkstr, strlen(checkstr) + 1) != 0) { Fail("ERROR: failed to insert char \'%c\' (%d) into \"%S\"\n" "Expected \"%s\" got \"%s\".\n", param, param, formatstr, checkstr, buf); } fclose(fp); } #define DoCharTest DoCharTest_fwprintf inline void DoWCharTest_fwprintf(const WCHAR *formatstr, WCHAR param, const char *checkstr) { FILE *fp; char buf[256] = { 0 }; if ((fp = fopen("testfile.txt", "w+")) == NULL ) { Fail("ERROR: fopen failed to create testfile\n"); } if ((fwprintf(fp, formatstr, param)) < 0) { Fail("ERROR: fwprintf failed\n"); } if ((fseek(fp, 0, SEEK_SET)) != 0) { Fail("ERROR: fseek failed\n"); } if ((fgets(buf, 100, fp)) == NULL) { Fail("ERROR: fseek failed\n"); } if (memcmp(buf, checkstr, strlen(checkstr) + 1) != 0) { Fail("ERROR: failed to insert wide char \'%c\' (%d) into \"%S\"\n" "Expected \"%s\" got \"%s\".\n", (char)param, param, formatstr, checkstr, buf); } fclose(fp); } #define DoWCharTest DoWCharTest_fwprintf inline void DoNumTest_fwprintf(const WCHAR *formatstr, int value, const char *checkstr) { FILE *fp; char buf[256] = { 0 }; if ((fp = fopen("testfile.txt", "w+")) == NULL ) { Fail("ERROR: fopen failed to create testfile\n"); } if ((fwprintf(fp, formatstr, value)) < 0) { Fail("ERROR: fwprintf failed\n"); } if ((fseek(fp, 0, SEEK_SET)) != 0) { Fail("ERROR: fseek failed\n"); } if ((fgets(buf, 100, fp)) == NULL) { Fail("ERROR: fseek failed\n"); } if (memcmp(buf, checkstr, strlen(checkstr) + 1) != 0) { Fail("ERROR: failed to insert %#x into \"%S\"\n" "Expected \"%s\" got \"%s\".\n", value, formatstr, checkstr, buf); } fclose(fp); } #define DoNumTest DoNumTest_fwprintf inline void DoI64Test_fwprintf(const WCHAR *formatstr, INT64 value, char *valuestr, const char *checkstr1, const char *checkstr2) { FILE *fp; char buf[256] = { 0 }; if ((fp = fopen("testfile.txt", "w+")) == NULL ) { Fail("ERROR: fopen failed to create testfile\n"); } if ((fwprintf(fp, formatstr, value)) < 0) { Fail("ERROR: fwprintf failed\n"); } if ((fseek(fp, 0, SEEK_SET)) != 0) { Fail("ERROR: fseek failed\n"); } if ((fgets(buf, 100, fp)) == NULL) { Fail("ERROR: fseek failed\n"); } if (memcmp(buf, checkstr1, strlen(checkstr1) + 1) != 0 && memcmp(buf, checkstr2, strlen(checkstr2) + 1) != 0) { Fail("ERROR: failed to insert %s into \"%S\"\n" "Expected \"%s\" or \"%s\", got \"%s\".\n", valuestr, formatstr, checkstr1, checkstr2, buf); } fclose(fp); } #define DoI64Test DoI64Test_fwprintf inline void DoDoubleTest_fwprintf(const WCHAR *formatstr, double value, const char *checkstr1, const char *checkstr2) { FILE *fp; char buf[256] = { 0 }; if ((fp = fopen("testfile.txt", "w+")) == NULL ) { Fail("ERROR: fopen failed to create testfile\n"); } if ((fwprintf(fp, formatstr, value)) < 0) { Fail("ERROR: fwprintf failed\n"); } if ((fseek(fp, 0, SEEK_SET)) != 0) { Fail("ERROR: fseek failed\n"); } if ((fgets(buf, 100, fp)) == NULL) { Fail("ERROR: fseek failed\n"); } if (memcmp(buf, checkstr1, strlen(checkstr1) + 1) != 0 && memcmp(buf, checkstr2, strlen(checkstr2) + 1) != 0) { Fail("ERROR: failed to insert %f into \"%S\"\n" "Expected \"%s\" or \"%s\", got \"%s\".\n", value, formatstr, checkstr1, checkstr2, buf); } fclose(fp); } #define DoDoubleTest DoDoubleTest_fwprintf inline void DoArgumentPrecTest_fwprintf(const WCHAR *formatstr, int precision, void *param, char *paramstr, const char *checkstr1, const char *checkstr2) { FILE *fp; char buf[256]; if ((fp = fopen("testfile.txt", "w+")) == NULL ) { Fail("ERROR: fopen failed to create testfile\n"); } if ((fwprintf(fp, formatstr, precision, param)) < 0) { Fail("ERROR: fwprintf failed\n"); } if ((fseek(fp, 0, SEEK_SET)) != 0) { Fail("ERROR: fseek failed\n"); } if ((fgets(buf, 100, fp)) == NULL) { Fail("ERROR: fseek failed\n"); } if (memcmp(buf, checkstr1, strlen(checkstr1) + 1) != 0 && memcmp(buf, checkstr2, strlen(checkstr2) + 1) != 0) { Fail("ERROR: failed to insert %s into \"%s\" with precision %d\n" "Expected \"%s\" or \"%s\", got \"%s\".\n", paramstr, formatstr, precision, checkstr1, checkstr2, buf); } if ((fclose( fp )) != 0) { Fail("ERROR: fclose failed to close \"testfile.txt\"\n"); } } #define DoArgumentPrecTest DoArgumentPrecTest_fwprintf inline void DoArgumentPrecDoubleTest_fwprintf(const WCHAR *formatstr, int precision, double param, const char *checkstr1, const char *checkstr2) { FILE *fp; char buf[256]; if ((fp = fopen("testfile.txt", "w+")) == NULL ) { Fail("ERROR: fopen failed to create testfile\n"); } if ((fwprintf(fp, formatstr, precision, param)) < 0) { Fail("ERROR: fwprintf failed\n"); } if ((fseek(fp, 0, SEEK_SET)) != 0) { Fail("ERROR: fseek failed\n"); } if ((fgets(buf, 100, fp)) == NULL) { Fail("ERROR: fseek failed\n"); } if (memcmp(buf, checkstr1, strlen(checkstr1) + 1) != 0 && memcmp(buf, checkstr2, strlen(checkstr2) + 1) != 0) { Fail("ERROR: failed to insert %f into \"%s\" with precision %d\n" "Expected \"%s\" or \"%s\", got \"%s\".\n", param, formatstr, precision, checkstr1, checkstr2, buf); } if ((fclose( fp )) != 0) { Fail("ERROR: fclose failed to close \"testfile.txt\"\n"); } } #define DoArgumentPrecDoubleTest DoArgumentPrecDoubleTest_fwprintf #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*============================================================================ ** ** Source: fwprintf.h ** ** Purpose: Containts common testing functions for fwprintf ** ** **==========================================================================*/ #ifndef __fwprintf_H__ #define __fwprintf_H__ inline void DoStrTest_fwprintf(const WCHAR *formatstr, char* param, const char *checkstr) { FILE *fp; char buf[256] = { 0 }; if ((fp = fopen("testfile.txt", "w+")) == NULL ) { Fail("ERROR: fopen failed to create testfile\n"); } if ((fwprintf(fp, formatstr, param)) < 0) { Fail("ERROR: fwprintf failed\n"); } if ((fseek(fp, 0, SEEK_SET)) != 0) { Fail("ERROR: fseek failed\n"); } if ((fgets(buf, 100, fp)) == NULL) { Fail("ERROR: fseek failed\n"); } if (memcmp(buf, checkstr, strlen(checkstr) + 1) != 0) { Fail("ERROR: failed to insert string \"%\" into \"%S\"\n" "Expected \"%s\" got \"%s\".\n", param, formatstr, checkstr, buf); } fclose(fp); } #define DoStrTest DoStrTest_fwprintf inline void DoWStrTest_fwprintf(const WCHAR *formatstr, WCHAR* param, const char *checkstr) { FILE *fp; char buf[256] = { 0 }; if ((fp = fopen("testfile.txt", "w+")) == NULL ) { Fail("ERROR: fopen failed to create testfile\n"); } if ((fwprintf(fp, formatstr, param)) < 0) { Fail("ERROR: fwprintf failed\n"); } if ((fseek(fp, 0, SEEK_SET)) != 0) { Fail("ERROR: fseek failed\n"); } if ((fgets(buf, 100, fp)) == NULL) { Fail("ERROR: fseek failed\n"); } if (memcmp(buf, checkstr, strlen(checkstr) + 1) != 0) { Fail("ERROR: failed to insert wide string \"%s\" into \"%S\"\n" "Expected \"%s\" got \"%s\".\n", convertC(param), formatstr, checkstr, buf); } fclose(fp); } #define DoWStrTest DoWStrTest_fwprintf inline void DoPointerTest_fwprintf(const WCHAR *formatstr, void* param, char* paramstr, const char *checkstr1, const char *checkstr2) { FILE *fp; char buf[256] = { 0 }; if ((fp = fopen("testfile.txt", "w+")) == NULL ) { Fail("ERROR: fopen failed to create testfile\n"); } if ((fwprintf(fp, formatstr, param)) < 0) { Fail("ERROR: fwprintf failed\n"); } if ((fseek(fp, 0, SEEK_SET)) != 0) { Fail("ERROR: fseek failed\n"); } if ((fgets(buf, 100, fp)) == NULL) { Fail("ERROR: fseek failed\n"); } if (memcmp(buf, checkstr1, strlen(checkstr1) + 1) != 0 && memcmp(buf, checkstr2, strlen(checkstr2) + 1) != 0 ) { Fail("ERROR: failed to insert %s into \"%s\"\n" "Expected \"%s\" or \"%s\" got \"%s\".\n", paramstr, formatstr, checkstr1, checkstr2, buf); } if ((fclose( fp )) != 0) { Fail("ERROR: fclose failed to close \"testfile.txt\"\n"); } } #define DoPointerTest DoPointerTest_fwprintf inline void DoCountTest_fwprintf(const WCHAR *formatstr, int param, const char *checkstr) { FILE *fp; char buf[512] = { 0 }; int n = -1; if ((fp = fopen("testfile.txt", "w+")) == NULL ) { Fail("ERROR: fopen failed to create testfile\n"); } if ((fwprintf(fp, formatstr, &n)) < 0) { Fail("ERROR: fwprintf failed\n"); } if ((fseek(fp, 0, SEEK_SET)) != 0) { Fail("ERROR: fseek failed\n"); } if ((fgets(buf, sizeof(buf), fp)) == NULL) { Fail("ERROR: fseek failed\n"); } if (n != param) { Fail("ERROR: Expected count parameter to resolve to %d, got %X\n", param, n); } if (memcmp(buf, checkstr, strlen(checkstr) + 1) != 0) { Fail("ERROR: Expected \"%s\" got \"%s\".\n", checkstr, buf); } if ((fclose( fp )) != 0) { Fail("ERROR: fclose failed to close \"testfile.txt\"\n"); } } #define DoCountTest DoCountTest_fwprintf inline void DoShortCountTest_fwprintf(const WCHAR *formatstr, int param, const char *checkstr) { FILE *fp; char buf[512] = { 0 }; short int n = -1; if ((fp = fopen("testfile.txt", "w+")) == NULL ) { Fail("ERROR: fopen failed to create testfile\n"); } if ((fwprintf(fp, formatstr, &n)) < 0) { Fail("ERROR: fwprintf failed\n"); } if ((fseek(fp, 0, SEEK_SET)) != 0) { Fail("ERROR: fseek failed\n"); } if ((fgets(buf, 100, fp)) == NULL) { Fail("ERROR: fseek failed\n"); } if (n != param) { Fail("ERROR: Expected count parameter to resolve to %d, got %X\n", param, n); } if (memcmp(buf, checkstr, strlen(checkstr) + 1) != 0) { Fail("ERROR: Expected \"%s\" got \"%s\".\n", checkstr, buf); } if ((fclose( fp )) != 0) { Fail("ERROR: fclose failed to close \"testfile.txt\"\n"); } } #define DoShortCountTest DoShortCountTest_fwprintf inline void DoCharTest_fwprintf(const WCHAR *formatstr, char param, const char *checkstr) { FILE *fp; char buf[256] = { 0 }; if ((fp = fopen("testfile.txt", "w+")) == NULL ) { Fail("ERROR: fopen failed to create testfile\n"); } if ((fwprintf(fp, formatstr, param)) < 0) { Fail("ERROR: fwprintf failed\n"); } if ((fseek(fp, 0, SEEK_SET)) != 0) { Fail("ERROR: fseek failed\n"); } if ((fgets(buf, 100, fp)) == NULL) { Fail("ERROR: fseek failed\n"); } if (memcmp(buf, checkstr, strlen(checkstr) + 1) != 0) { Fail("ERROR: failed to insert char \'%c\' (%d) into \"%S\"\n" "Expected \"%s\" got \"%s\".\n", param, param, formatstr, checkstr, buf); } fclose(fp); } #define DoCharTest DoCharTest_fwprintf inline void DoWCharTest_fwprintf(const WCHAR *formatstr, WCHAR param, const char *checkstr) { FILE *fp; char buf[256] = { 0 }; if ((fp = fopen("testfile.txt", "w+")) == NULL ) { Fail("ERROR: fopen failed to create testfile\n"); } if ((fwprintf(fp, formatstr, param)) < 0) { Fail("ERROR: fwprintf failed\n"); } if ((fseek(fp, 0, SEEK_SET)) != 0) { Fail("ERROR: fseek failed\n"); } if ((fgets(buf, 100, fp)) == NULL) { Fail("ERROR: fseek failed\n"); } if (memcmp(buf, checkstr, strlen(checkstr) + 1) != 0) { Fail("ERROR: failed to insert wide char \'%c\' (%d) into \"%S\"\n" "Expected \"%s\" got \"%s\".\n", (char)param, param, formatstr, checkstr, buf); } fclose(fp); } #define DoWCharTest DoWCharTest_fwprintf inline void DoNumTest_fwprintf(const WCHAR *formatstr, int value, const char *checkstr) { FILE *fp; char buf[256] = { 0 }; if ((fp = fopen("testfile.txt", "w+")) == NULL ) { Fail("ERROR: fopen failed to create testfile\n"); } if ((fwprintf(fp, formatstr, value)) < 0) { Fail("ERROR: fwprintf failed\n"); } if ((fseek(fp, 0, SEEK_SET)) != 0) { Fail("ERROR: fseek failed\n"); } if ((fgets(buf, 100, fp)) == NULL) { Fail("ERROR: fseek failed\n"); } if (memcmp(buf, checkstr, strlen(checkstr) + 1) != 0) { Fail("ERROR: failed to insert %#x into \"%S\"\n" "Expected \"%s\" got \"%s\".\n", value, formatstr, checkstr, buf); } fclose(fp); } #define DoNumTest DoNumTest_fwprintf inline void DoI64Test_fwprintf(const WCHAR *formatstr, INT64 value, char *valuestr, const char *checkstr1, const char *checkstr2) { FILE *fp; char buf[256] = { 0 }; if ((fp = fopen("testfile.txt", "w+")) == NULL ) { Fail("ERROR: fopen failed to create testfile\n"); } if ((fwprintf(fp, formatstr, value)) < 0) { Fail("ERROR: fwprintf failed\n"); } if ((fseek(fp, 0, SEEK_SET)) != 0) { Fail("ERROR: fseek failed\n"); } if ((fgets(buf, 100, fp)) == NULL) { Fail("ERROR: fseek failed\n"); } if (memcmp(buf, checkstr1, strlen(checkstr1) + 1) != 0 && memcmp(buf, checkstr2, strlen(checkstr2) + 1) != 0) { Fail("ERROR: failed to insert %s into \"%S\"\n" "Expected \"%s\" or \"%s\", got \"%s\".\n", valuestr, formatstr, checkstr1, checkstr2, buf); } fclose(fp); } #define DoI64Test DoI64Test_fwprintf inline void DoDoubleTest_fwprintf(const WCHAR *formatstr, double value, const char *checkstr1, const char *checkstr2) { FILE *fp; char buf[256] = { 0 }; if ((fp = fopen("testfile.txt", "w+")) == NULL ) { Fail("ERROR: fopen failed to create testfile\n"); } if ((fwprintf(fp, formatstr, value)) < 0) { Fail("ERROR: fwprintf failed\n"); } if ((fseek(fp, 0, SEEK_SET)) != 0) { Fail("ERROR: fseek failed\n"); } if ((fgets(buf, 100, fp)) == NULL) { Fail("ERROR: fseek failed\n"); } if (memcmp(buf, checkstr1, strlen(checkstr1) + 1) != 0 && memcmp(buf, checkstr2, strlen(checkstr2) + 1) != 0) { Fail("ERROR: failed to insert %f into \"%S\"\n" "Expected \"%s\" or \"%s\", got \"%s\".\n", value, formatstr, checkstr1, checkstr2, buf); } fclose(fp); } #define DoDoubleTest DoDoubleTest_fwprintf inline void DoArgumentPrecTest_fwprintf(const WCHAR *formatstr, int precision, void *param, char *paramstr, const char *checkstr1, const char *checkstr2) { FILE *fp; char buf[256]; if ((fp = fopen("testfile.txt", "w+")) == NULL ) { Fail("ERROR: fopen failed to create testfile\n"); } if ((fwprintf(fp, formatstr, precision, param)) < 0) { Fail("ERROR: fwprintf failed\n"); } if ((fseek(fp, 0, SEEK_SET)) != 0) { Fail("ERROR: fseek failed\n"); } if ((fgets(buf, 100, fp)) == NULL) { Fail("ERROR: fseek failed\n"); } if (memcmp(buf, checkstr1, strlen(checkstr1) + 1) != 0 && memcmp(buf, checkstr2, strlen(checkstr2) + 1) != 0) { Fail("ERROR: failed to insert %s into \"%s\" with precision %d\n" "Expected \"%s\" or \"%s\", got \"%s\".\n", paramstr, formatstr, precision, checkstr1, checkstr2, buf); } if ((fclose( fp )) != 0) { Fail("ERROR: fclose failed to close \"testfile.txt\"\n"); } } #define DoArgumentPrecTest DoArgumentPrecTest_fwprintf inline void DoArgumentPrecDoubleTest_fwprintf(const WCHAR *formatstr, int precision, double param, const char *checkstr1, const char *checkstr2) { FILE *fp; char buf[256]; if ((fp = fopen("testfile.txt", "w+")) == NULL ) { Fail("ERROR: fopen failed to create testfile\n"); } if ((fwprintf(fp, formatstr, precision, param)) < 0) { Fail("ERROR: fwprintf failed\n"); } if ((fseek(fp, 0, SEEK_SET)) != 0) { Fail("ERROR: fseek failed\n"); } if ((fgets(buf, 100, fp)) == NULL) { Fail("ERROR: fseek failed\n"); } if (memcmp(buf, checkstr1, strlen(checkstr1) + 1) != 0 && memcmp(buf, checkstr2, strlen(checkstr2) + 1) != 0) { Fail("ERROR: failed to insert %f into \"%s\" with precision %d\n" "Expected \"%s\" or \"%s\", got \"%s\".\n", param, formatstr, precision, checkstr1, checkstr2, buf); } if ((fclose( fp )) != 0) { Fail("ERROR: fclose failed to close \"testfile.txt\"\n"); } } #define DoArgumentPrecDoubleTest DoArgumentPrecDoubleTest_fwprintf #endif
-1
dotnet/runtime
66,452
[mono] Stop setting time_date_stamp field in MonoImage
We never read that field in the runtime and it was causing unnecessary disk IO during startup (5ms on my iOS device). It was also never set on Windows already.
akoeplinger
2022-03-10T15:49:37Z
2022-03-10T21:47:58Z
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
d2826308964e4ee4496d6884e09811e1f709005e
[mono] Stop setting time_date_stamp field in MonoImage. We never read that field in the runtime and it was causing unnecessary disk IO during startup (5ms on my iOS device). It was also never set on Windows already.
./src/coreclr/pal/src/libunwind/src/ppc32/Lresume.c
#define UNW_LOCAL_ONLY #include <libunwind.h> #if defined(UNW_LOCAL_ONLY) && !defined(UNW_REMOTE_ONLY) #include "Gresume.c" #endif
#define UNW_LOCAL_ONLY #include <libunwind.h> #if defined(UNW_LOCAL_ONLY) && !defined(UNW_REMOTE_ONLY) #include "Gresume.c" #endif
-1
dotnet/runtime
66,452
[mono] Stop setting time_date_stamp field in MonoImage
We never read that field in the runtime and it was causing unnecessary disk IO during startup (5ms on my iOS device). It was also never set on Windows already.
akoeplinger
2022-03-10T15:49:37Z
2022-03-10T21:47:58Z
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
d2826308964e4ee4496d6884e09811e1f709005e
[mono] Stop setting time_date_stamp field in MonoImage. We never read that field in the runtime and it was causing unnecessary disk IO during startup (5ms on my iOS device). It was also never set on Windows already.
./src/coreclr/pal/src/libunwind/include/tdep-ppc64/jmpbuf.h
/* libunwind - a platform-independent unwind library Copyright (C) 2006-2007 IBM Contributed by Corey Ashford <[email protected]> Jose Flavio Aguilar Paulino <[email protected]> <[email protected]> Copied from libunwind-x86_64.h, modified slightly for building frysk successfully on ppc64, by Wu Zhou <[email protected]> Will be replaced when libunwind is ready on ppc64 platform. This file is part of libunwind. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* Use glibc's jump-buffer indices; NPTL peeks at SP: */ #define JB_SP 6 #define JB_RP 7 #define JB_MASK_SAVED 8 #define JB_MASK 9
/* libunwind - a platform-independent unwind library Copyright (C) 2006-2007 IBM Contributed by Corey Ashford <[email protected]> Jose Flavio Aguilar Paulino <[email protected]> <[email protected]> Copied from libunwind-x86_64.h, modified slightly for building frysk successfully on ppc64, by Wu Zhou <[email protected]> Will be replaced when libunwind is ready on ppc64 platform. This file is part of libunwind. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* Use glibc's jump-buffer indices; NPTL peeks at SP: */ #define JB_SP 6 #define JB_RP 7 #define JB_MASK_SAVED 8 #define JB_MASK 9
-1
dotnet/runtime
66,452
[mono] Stop setting time_date_stamp field in MonoImage
We never read that field in the runtime and it was causing unnecessary disk IO during startup (5ms on my iOS device). It was also never set on Windows already.
akoeplinger
2022-03-10T15:49:37Z
2022-03-10T21:47:58Z
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
d2826308964e4ee4496d6884e09811e1f709005e
[mono] Stop setting time_date_stamp field in MonoImage. We never read that field in the runtime and it was causing unnecessary disk IO during startup (5ms on my iOS device). It was also never set on Windows already.
./src/native/libs/System.Security.Cryptography.Native.Apple/pal_ssl.c
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include "pal_ssl.h" #include <dlfcn.h> // 10.13.4 introduced public API but linking would fail on all prior versions. // For that reason we use function pointers instead of direct call. // This can be revisited after we drop support for 10.12 and iOS 10 static OSStatus (*SSLSetALPNProtocolsPtr)(SSLContextRef context, CFArrayRef protocols) = NULL; static OSStatus (*SSLCopyALPNProtocolsPtr)(SSLContextRef context, CFArrayRef* protocols) = NULL; // end of ALPN. SSLContextRef AppleCryptoNative_SslCreateContext(int32_t isServer) { if (isServer != 0 && isServer != 1) return NULL; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" return SSLCreateContext(NULL, isServer ? kSSLServerSide : kSSLClientSide, kSSLStreamType); #pragma clang diagnostic pop } int32_t AppleCryptoNative_SslSetConnection(SSLContextRef sslContext, SSLConnectionRef sslConnection) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" return SSLSetConnection(sslContext, sslConnection); #pragma clang diagnostic pop } int32_t AppleCryptoNative_SslSetAcceptClientCert(SSLContextRef sslContext) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" // NULL and other illegal values are handled by the underlying API return SSLSetClientSideAuthenticate(sslContext, kTryAuthenticate); #pragma clang diagnostic pop } static SSLProtocol PalSslProtocolToSslProtocol(PAL_SslProtocol palProtocolId) { switch (palProtocolId) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" case PAL_SslProtocol_Tls13: return kTLSProtocol13; case PAL_SslProtocol_Tls12: return kTLSProtocol12; case PAL_SslProtocol_Tls11: return kTLSProtocol11; case PAL_SslProtocol_Tls10: return kTLSProtocol1; case PAL_SslProtocol_Ssl3: return kSSLProtocol3; case PAL_SslProtocol_Ssl2: return kSSLProtocol2; case PAL_SslProtocol_None: default: return kSSLProtocolUnknown; #pragma clang diagnostic pop } } int32_t AppleCryptoNative_SslSetMinProtocolVersion(SSLContextRef sslContext, PAL_SslProtocol sslProtocol) { SSLProtocol protocol = PalSslProtocolToSslProtocol(sslProtocol); #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" if (protocol == kSSLProtocolUnknown) return errSecParam; // NULL and other illegal values are handled by the underlying API return SSLSetProtocolVersionMin(sslContext, protocol); #pragma clang diagnostic pop } int32_t AppleCryptoNative_SslSetMaxProtocolVersion(SSLContextRef sslContext, PAL_SslProtocol sslProtocol) { SSLProtocol protocol = PalSslProtocolToSslProtocol(sslProtocol); #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" if (protocol == kSSLProtocolUnknown) return errSecParam; // NULL and other illegal values are handled by the underlying API return SSLSetProtocolVersionMax(sslContext, protocol); #pragma clang diagnostic pop } int32_t AppleCryptoNative_SslCopyCertChain(SSLContextRef sslContext, SecTrustRef* pChainOut, int32_t* pOSStatus) { if (pChainOut != NULL) *pChainOut = NULL; if (pOSStatus != NULL) *pOSStatus = noErr; if (sslContext == NULL || pChainOut == NULL || pOSStatus == NULL) return -1; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" *pOSStatus = SSLCopyPeerTrust(sslContext, pChainOut); #pragma clang diagnostic pop return *pOSStatus == noErr; } int32_t AppleCryptoNative_SslCopyCADistinguishedNames(SSLContextRef sslContext, CFArrayRef* pArrayOut, int32_t* pOSStatus) { if (pArrayOut != NULL) *pArrayOut = NULL; if (pOSStatus != NULL) *pOSStatus = noErr; if (sslContext == NULL || pArrayOut == NULL || pOSStatus == NULL) return -1; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" *pOSStatus = SSLCopyDistinguishedNames(sslContext, pArrayOut); #pragma clang diagnostic pop return *pOSStatus == noErr; } static int32_t SslSetSessionOption(SSLContextRef sslContext, SSLSessionOption option, int32_t value, int32_t* pOSStatus) { if (sslContext == NULL) return -1; if (value != 0 && value != 1) return -2; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" *pOSStatus = SSLSetSessionOption(sslContext, option, !!value); #pragma clang diagnostic pop return *pOSStatus == noErr; } int32_t AppleCryptoNative_SslSetBreakOnServerAuth(SSLContextRef sslContext, int32_t setBreak, int32_t* pOSStatus) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" return SslSetSessionOption(sslContext, kSSLSessionOptionBreakOnServerAuth, setBreak, pOSStatus); #pragma clang diagnostic pop } int32_t AppleCryptoNative_SslSetBreakOnCertRequested(SSLContextRef sslContext, int32_t setBreak, int32_t* pOSStatus) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" return SslSetSessionOption(sslContext, kSSLSessionOptionBreakOnCertRequested, setBreak, pOSStatus); #pragma clang diagnostic pop } int32_t AppleCryptoNative_SslSetBreakOnClientAuth(SSLContextRef sslContext, int32_t setBreak, int32_t* pOSStatus) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" return SslSetSessionOption(sslContext, kSSLSessionOptionBreakOnClientAuth, setBreak, pOSStatus); #pragma clang diagnostic pop } int32_t AppleCryptoNative_SslSetCertificate(SSLContextRef sslContext, CFArrayRef certRefs) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" // The underlying call handles NULL inputs, so just pass it through return SSLSetCertificate(sslContext, certRefs); #pragma clang diagnostic pop } int32_t AppleCryptoNative_SslSetTargetName(SSLContextRef sslContext, const char* pszTargetName, int32_t cbTargetName, int32_t* pOSStatus) { if (pOSStatus != NULL) *pOSStatus = noErr; if (sslContext == NULL || pszTargetName == NULL || pOSStatus == NULL) return -1; if (cbTargetName < 0) return -2; size_t currentLength; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" *pOSStatus = SSLGetPeerDomainNameLength(sslContext, &currentLength); // We'll end up walking down the path that sets the hostname more than once during // the handshake dance. But once the handshake starts Secure Transport isn't willing to // listen to this. So, if we've already set it, don't set it again. if (*pOSStatus == noErr && currentLength == 0) { *pOSStatus = SSLSetPeerDomainName(sslContext, pszTargetName, (size_t)cbTargetName); } #pragma clang diagnostic pop return *pOSStatus == noErr; } int32_t AppleCryptoNative_SSLSetALPNProtocols(SSLContextRef sslContext, CFArrayRef protocols, int32_t* pOSStatus) { if (sslContext == NULL || protocols == NULL || pOSStatus == NULL) return -1; if (!SSLSetALPNProtocolsPtr) { // not available. *pOSStatus = 0; return 1; } // The underlying call handles NULL inputs, so just pass it through *pOSStatus = (*SSLSetALPNProtocolsPtr)(sslContext, protocols); return *pOSStatus == noErr; } int32_t AppleCryptoNative_SslGetAlpnSelected(SSLContextRef sslContext, CFDataRef* protocol) { if (sslContext == NULL || protocol == NULL) return -1; *protocol = NULL; if (!SSLCopyALPNProtocolsPtr) { // not available. return 0; } CFArrayRef protocols = NULL; OSStatus osStatus = (*SSLCopyALPNProtocolsPtr)(sslContext, &protocols); if (osStatus == noErr && protocols != NULL && CFArrayGetCount(protocols) > 0) { *protocol = CFStringCreateExternalRepresentation(NULL, CFArrayGetValueAtIndex(protocols, 0), kCFStringEncodingASCII, 0); } if (protocols) CFRelease(protocols); return *protocol != NULL; } int32_t AppleCryptoNative_SslSetIoCallbacks(SSLContextRef sslContext, SSLReadFunc readFunc, SSLWriteFunc writeFunc) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" return SSLSetIOFuncs(sslContext, readFunc, writeFunc); #pragma clang diagnostic pop } PAL_TlsHandshakeState AppleCryptoNative_SslHandshake(SSLContextRef sslContext) { if (sslContext == NULL) return PAL_TlsHandshakeState_Unknown; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" OSStatus osStatus = SSLHandshake(sslContext); #pragma clang diagnostic pop switch (osStatus) { case noErr: return PAL_TlsHandshakeState_Complete; case errSSLWouldBlock: return PAL_TlsHandshakeState_WouldBlock; case errSSLServerAuthCompleted: return PAL_TlsHandshakeState_ServerAuthCompleted; case errSSLClientCertRequested: return PAL_TlsHandshakeState_ClientCertRequested; default: return osStatus; } } static PAL_TlsIo OSStatusToPAL_TlsIo(OSStatus status) { switch (status) { case noErr: return PAL_TlsIo_Success; case errSSLWouldBlock: return PAL_TlsIo_WouldBlock; case errSSLClosedGraceful: return PAL_TlsIo_ClosedGracefully; default: return status; } } PAL_TlsIo AppleCryptoNative_SslWrite(SSLContextRef sslContext, const uint8_t* buf, uint32_t bufLen, uint32_t* bytesWritten) { if (bytesWritten == NULL) return PAL_TlsIo_Unknown; size_t expected = (size_t)bufLen; size_t totalWritten; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" OSStatus status = SSLWrite(sslContext, buf, expected, &totalWritten); #pragma clang diagnostic pop if (status != noErr) { *bytesWritten = (uint32_t)totalWritten; return OSStatusToPAL_TlsIo(status); } return PAL_TlsIo_Success; } PAL_TlsIo AppleCryptoNative_SslRead(SSLContextRef sslContext, uint8_t* buf, uint32_t bufLen, uint32_t* written) { if (written == NULL) return PAL_TlsIo_Unknown; size_t writtenSize = 0; size_t bufSize = (size_t)bufLen; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" OSStatus status = SSLRead(sslContext, buf, bufSize, &writtenSize); #pragma clang diagnostic pop if (writtenSize > UINT_MAX) { // This shouldn't happen, because we passed a uint32_t as the initial buffer size. // But, just in case it does, report back that we're no longer in a known state. return PAL_TlsIo_Unknown; } *written = (uint32_t)writtenSize; if (writtenSize == 0 && status == errSSLWouldBlock) { SSLSessionState state; memset(&state, 0, sizeof(SSLSessionState)); #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" OSStatus localStatus = SSLGetSessionState(sslContext, &state); if (localStatus == noErr && state == kSSLHandshake) { return PAL_TlsIo_Renegotiate; } #pragma clang diagnostic pop } return OSStatusToPAL_TlsIo(status); } int32_t AppleCryptoNative_SslIsHostnameMatch(SSLContextRef sslContext, CFStringRef cfHostname, CFDateRef notBefore, int32_t* pOSStatus) { if (pOSStatus != NULL) *pOSStatus = noErr; if (sslContext == NULL || notBefore == NULL || pOSStatus == NULL) return -1; if (cfHostname == NULL) return -2; SecPolicyRef sslPolicy = SecPolicyCreateSSL(true, cfHostname); if (sslPolicy == NULL) return -3; CFMutableArrayRef certs = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks); if (certs == NULL) return -4; SecTrustRef existingTrust = NULL; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" OSStatus osStatus = SSLCopyPeerTrust(sslContext, &existingTrust); #pragma clang diagnostic pop if (osStatus != noErr) { CFRelease(certs); *pOSStatus = osStatus; return -5; } CFMutableArrayRef anchors = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks); if (anchors == NULL) { CFRelease(certs); CFRelease(existingTrust); return -6; } CFIndex certificateCount = SecTrustGetCertificateCount(existingTrust); for (CFIndex i = 0; i < certificateCount; i++) { SecCertificateRef item = SecTrustGetCertificateAtIndex(existingTrust, i); CFArrayAppendValue(certs, item); // Copy the EE cert into the anchors set, this will make the chain part // always return true. if (i == 0) { CFArrayAppendValue(anchors, item); } } SecTrustRef trust = NULL; osStatus = SecTrustCreateWithCertificates(certs, sslPolicy, &trust); int32_t ret = INT_MIN; if (osStatus == noErr) { osStatus = SecTrustSetAnchorCertificates(trust, anchors); } if (osStatus == noErr) { osStatus = SecTrustSetVerifyDate(trust, notBefore); } if (osStatus == noErr) { SecTrustResultType trustResult; memset(&trustResult, 0, sizeof(SecTrustResultType)); #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" osStatus = SecTrustEvaluate(trust, &trustResult); if (trustResult == kSecTrustResultRecoverableTrustFailure && osStatus == noErr && certificateCount > 1) { // If we get recoverable failure, let's try it again with full anchor list. // We already stored just the first certificate into anchors; now we store the rest. for (CFIndex i = 1; i < certificateCount; i++) { CFArrayAppendValue(anchors, SecTrustGetCertificateAtIndex(existingTrust, i)); } osStatus = SecTrustSetAnchorCertificates(trust, anchors); if (osStatus == noErr) { memset(&trustResult, 0, sizeof(SecTrustResultType)); osStatus = SecTrustEvaluate(trust, &trustResult); } } #pragma clang diagnostic pop if (osStatus == noErr && trustResult != kSecTrustResultUnspecified && trustResult != kSecTrustResultProceed) { // If evaluation succeeded but result is not trusted try to get details. CFDictionaryRef detailsAndStuff = SecTrustCopyResult(trust); if (detailsAndStuff != NULL) { CFArrayRef details = CFDictionaryGetValue(detailsAndStuff, CFSTR("TrustResultDetails")); if (details != NULL && CFArrayGetCount(details) > 0) { CFArrayRef statusCodes = CFDictionaryGetValue(CFArrayGetValueAtIndex(details,0), CFSTR("StatusCodes")); if (statusCodes != NULL) { OSStatus status = 0; // look for first failure to keep it simple. Normally, there will be exactly one. for (int i = 0; i < CFArrayGetCount(statusCodes); i++) { CFNumberGetValue(CFArrayGetValueAtIndex(statusCodes, i), kCFNumberSInt32Type, &status); if (status != noErr) { *pOSStatus = status; break; } } } } CFRelease(detailsAndStuff); } } if (osStatus != noErr) { ret = -7; *pOSStatus = osStatus; } else if (trustResult == kSecTrustResultUnspecified || trustResult == kSecTrustResultProceed) { ret = 1; } else if (trustResult == kSecTrustResultDeny || trustResult == kSecTrustResultRecoverableTrustFailure) { ret = 0; } else { ret = -8; } } else { *pOSStatus = osStatus; } if (trust != NULL) CFRelease(trust); if (certs != NULL) CFRelease(certs); if (anchors != NULL) CFRelease(anchors); if (existingTrust != NULL) CFRelease(existingTrust); CFRelease(sslPolicy); return ret; } int32_t AppleCryptoNative_SslShutdown(SSLContextRef sslContext) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" return SSLClose(sslContext); #pragma clang diagnostic pop } int32_t AppleCryptoNative_SslGetProtocolVersion(SSLContextRef sslContext, PAL_SslProtocol* pProtocol) { if (pProtocol != NULL) *pProtocol = 0; if (sslContext == NULL || pProtocol == NULL) return errSecParam; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" SSLProtocol protocol = kSSLProtocolUnknown; OSStatus osStatus = SSLGetNegotiatedProtocolVersion(sslContext, &protocol); if (osStatus == noErr) { PAL_SslProtocol matchedProtocol = PAL_SslProtocol_None; if (protocol == kTLSProtocol13) matchedProtocol = PAL_SslProtocol_Tls13; else if (protocol == kTLSProtocol12) matchedProtocol = PAL_SslProtocol_Tls12; else if (protocol == kTLSProtocol11) matchedProtocol = PAL_SslProtocol_Tls11; else if (protocol == kTLSProtocol1) matchedProtocol = PAL_SslProtocol_Tls10; else if (protocol == kSSLProtocol3) matchedProtocol = PAL_SslProtocol_Ssl3; else if (protocol == kSSLProtocol2) matchedProtocol = PAL_SslProtocol_Ssl2; *pProtocol = matchedProtocol; } #pragma clang diagnostic pop return osStatus; } int32_t AppleCryptoNative_SslGetCipherSuite(SSLContextRef sslContext, uint16_t* pCipherSuiteOut) { if (pCipherSuiteOut == NULL) { return errSecParam; } SSLCipherSuite cipherSuite; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" OSStatus status = SSLGetNegotiatedCipher(sslContext, &cipherSuite); #pragma clang diagnostic pop *pCipherSuiteOut = (uint16_t)cipherSuite; return status; } int32_t AppleCryptoNative_SslSetEnabledCipherSuites(SSLContextRef sslContext, const uint32_t* cipherSuites, int32_t numCipherSuites) { // Max numCipherSuites is 2^16 (all possible cipher suites) assert(numCipherSuites < (1 << 16)); #if !defined(TARGET_ARM64) && !defined(TARGET_IOS) && !defined(TARGET_TVOS) if (sizeof(SSLCipherSuite) == sizeof(uint32_t)) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" // macOS & MacCatalyst x64 return SSLSetEnabledCiphers(sslContext, (const SSLCipherSuite *)cipherSuites, (size_t)numCipherSuites); #pragma clang diagnostic pop } else #endif { // MacCatalyst arm64, iOS, tvOS, watchOS SSLCipherSuite* cipherSuites16 = (SSLCipherSuite*)calloc((size_t)numCipherSuites, sizeof(SSLCipherSuite)); if (cipherSuites16 == NULL) { return errSSLInternal; } for (int i = 0; i < numCipherSuites; i++) { cipherSuites16[i] = (SSLCipherSuite)cipherSuites[i]; } #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" OSStatus status = SSLSetEnabledCiphers(sslContext, cipherSuites16, (size_t)numCipherSuites); #pragma clang diagnostic pop free(cipherSuites16); return status; } } // This API is present on macOS 10.5 and newer only static OSStatus (*SSLSetCertificateAuthoritiesPtr)(SSLContextRef context, CFArrayRef certificates, int32_t replaceExisting) = NULL; PALEXPORT int32_t AppleCryptoNative_SslSetCertificateAuthorities(SSLContextRef sslContext, CFArrayRef certificates, int32_t replaceExisting) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" // The underlying call handles NULL inputs, so just pass it through if (!SSLSetCertificateAuthoritiesPtr) { // not available. return 0; } return SSLSetCertificateAuthoritiesPtr(sslContext, certificates, replaceExisting); #pragma clang diagnostic pop } __attribute__((constructor)) static void InitializeAppleCryptoSslShim() { SSLSetCertificateAuthoritiesPtr = (OSStatus(*)(SSLContextRef, CFArrayRef, int32_t))dlsym(RTLD_DEFAULT, "SSLSetCertificateAuthorities"); SSLSetALPNProtocolsPtr = (OSStatus(*)(SSLContextRef, CFArrayRef))dlsym(RTLD_DEFAULT, "SSLSetALPNProtocols"); SSLCopyALPNProtocolsPtr = (OSStatus(*)(SSLContextRef, CFArrayRef*))dlsym(RTLD_DEFAULT, "SSLCopyALPNProtocols"); }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include "pal_ssl.h" #include <dlfcn.h> // 10.13.4 introduced public API but linking would fail on all prior versions. // For that reason we use function pointers instead of direct call. // This can be revisited after we drop support for 10.12 and iOS 10 static OSStatus (*SSLSetALPNProtocolsPtr)(SSLContextRef context, CFArrayRef protocols) = NULL; static OSStatus (*SSLCopyALPNProtocolsPtr)(SSLContextRef context, CFArrayRef* protocols) = NULL; // end of ALPN. SSLContextRef AppleCryptoNative_SslCreateContext(int32_t isServer) { if (isServer != 0 && isServer != 1) return NULL; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" return SSLCreateContext(NULL, isServer ? kSSLServerSide : kSSLClientSide, kSSLStreamType); #pragma clang diagnostic pop } int32_t AppleCryptoNative_SslSetConnection(SSLContextRef sslContext, SSLConnectionRef sslConnection) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" return SSLSetConnection(sslContext, sslConnection); #pragma clang diagnostic pop } int32_t AppleCryptoNative_SslSetAcceptClientCert(SSLContextRef sslContext) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" // NULL and other illegal values are handled by the underlying API return SSLSetClientSideAuthenticate(sslContext, kTryAuthenticate); #pragma clang diagnostic pop } static SSLProtocol PalSslProtocolToSslProtocol(PAL_SslProtocol palProtocolId) { switch (palProtocolId) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" case PAL_SslProtocol_Tls13: return kTLSProtocol13; case PAL_SslProtocol_Tls12: return kTLSProtocol12; case PAL_SslProtocol_Tls11: return kTLSProtocol11; case PAL_SslProtocol_Tls10: return kTLSProtocol1; case PAL_SslProtocol_Ssl3: return kSSLProtocol3; case PAL_SslProtocol_Ssl2: return kSSLProtocol2; case PAL_SslProtocol_None: default: return kSSLProtocolUnknown; #pragma clang diagnostic pop } } int32_t AppleCryptoNative_SslSetMinProtocolVersion(SSLContextRef sslContext, PAL_SslProtocol sslProtocol) { SSLProtocol protocol = PalSslProtocolToSslProtocol(sslProtocol); #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" if (protocol == kSSLProtocolUnknown) return errSecParam; // NULL and other illegal values are handled by the underlying API return SSLSetProtocolVersionMin(sslContext, protocol); #pragma clang diagnostic pop } int32_t AppleCryptoNative_SslSetMaxProtocolVersion(SSLContextRef sslContext, PAL_SslProtocol sslProtocol) { SSLProtocol protocol = PalSslProtocolToSslProtocol(sslProtocol); #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" if (protocol == kSSLProtocolUnknown) return errSecParam; // NULL and other illegal values are handled by the underlying API return SSLSetProtocolVersionMax(sslContext, protocol); #pragma clang diagnostic pop } int32_t AppleCryptoNative_SslCopyCertChain(SSLContextRef sslContext, SecTrustRef* pChainOut, int32_t* pOSStatus) { if (pChainOut != NULL) *pChainOut = NULL; if (pOSStatus != NULL) *pOSStatus = noErr; if (sslContext == NULL || pChainOut == NULL || pOSStatus == NULL) return -1; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" *pOSStatus = SSLCopyPeerTrust(sslContext, pChainOut); #pragma clang diagnostic pop return *pOSStatus == noErr; } int32_t AppleCryptoNative_SslCopyCADistinguishedNames(SSLContextRef sslContext, CFArrayRef* pArrayOut, int32_t* pOSStatus) { if (pArrayOut != NULL) *pArrayOut = NULL; if (pOSStatus != NULL) *pOSStatus = noErr; if (sslContext == NULL || pArrayOut == NULL || pOSStatus == NULL) return -1; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" *pOSStatus = SSLCopyDistinguishedNames(sslContext, pArrayOut); #pragma clang diagnostic pop return *pOSStatus == noErr; } static int32_t SslSetSessionOption(SSLContextRef sslContext, SSLSessionOption option, int32_t value, int32_t* pOSStatus) { if (sslContext == NULL) return -1; if (value != 0 && value != 1) return -2; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" *pOSStatus = SSLSetSessionOption(sslContext, option, !!value); #pragma clang diagnostic pop return *pOSStatus == noErr; } int32_t AppleCryptoNative_SslSetBreakOnServerAuth(SSLContextRef sslContext, int32_t setBreak, int32_t* pOSStatus) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" return SslSetSessionOption(sslContext, kSSLSessionOptionBreakOnServerAuth, setBreak, pOSStatus); #pragma clang diagnostic pop } int32_t AppleCryptoNative_SslSetBreakOnCertRequested(SSLContextRef sslContext, int32_t setBreak, int32_t* pOSStatus) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" return SslSetSessionOption(sslContext, kSSLSessionOptionBreakOnCertRequested, setBreak, pOSStatus); #pragma clang diagnostic pop } int32_t AppleCryptoNative_SslSetBreakOnClientAuth(SSLContextRef sslContext, int32_t setBreak, int32_t* pOSStatus) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" return SslSetSessionOption(sslContext, kSSLSessionOptionBreakOnClientAuth, setBreak, pOSStatus); #pragma clang diagnostic pop } int32_t AppleCryptoNative_SslSetCertificate(SSLContextRef sslContext, CFArrayRef certRefs) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" // The underlying call handles NULL inputs, so just pass it through return SSLSetCertificate(sslContext, certRefs); #pragma clang diagnostic pop } int32_t AppleCryptoNative_SslSetTargetName(SSLContextRef sslContext, const char* pszTargetName, int32_t cbTargetName, int32_t* pOSStatus) { if (pOSStatus != NULL) *pOSStatus = noErr; if (sslContext == NULL || pszTargetName == NULL || pOSStatus == NULL) return -1; if (cbTargetName < 0) return -2; size_t currentLength; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" *pOSStatus = SSLGetPeerDomainNameLength(sslContext, &currentLength); // We'll end up walking down the path that sets the hostname more than once during // the handshake dance. But once the handshake starts Secure Transport isn't willing to // listen to this. So, if we've already set it, don't set it again. if (*pOSStatus == noErr && currentLength == 0) { *pOSStatus = SSLSetPeerDomainName(sslContext, pszTargetName, (size_t)cbTargetName); } #pragma clang diagnostic pop return *pOSStatus == noErr; } int32_t AppleCryptoNative_SSLSetALPNProtocols(SSLContextRef sslContext, CFArrayRef protocols, int32_t* pOSStatus) { if (sslContext == NULL || protocols == NULL || pOSStatus == NULL) return -1; if (!SSLSetALPNProtocolsPtr) { // not available. *pOSStatus = 0; return 1; } // The underlying call handles NULL inputs, so just pass it through *pOSStatus = (*SSLSetALPNProtocolsPtr)(sslContext, protocols); return *pOSStatus == noErr; } int32_t AppleCryptoNative_SslGetAlpnSelected(SSLContextRef sslContext, CFDataRef* protocol) { if (sslContext == NULL || protocol == NULL) return -1; *protocol = NULL; if (!SSLCopyALPNProtocolsPtr) { // not available. return 0; } CFArrayRef protocols = NULL; OSStatus osStatus = (*SSLCopyALPNProtocolsPtr)(sslContext, &protocols); if (osStatus == noErr && protocols != NULL && CFArrayGetCount(protocols) > 0) { *protocol = CFStringCreateExternalRepresentation(NULL, CFArrayGetValueAtIndex(protocols, 0), kCFStringEncodingASCII, 0); } if (protocols) CFRelease(protocols); return *protocol != NULL; } int32_t AppleCryptoNative_SslSetIoCallbacks(SSLContextRef sslContext, SSLReadFunc readFunc, SSLWriteFunc writeFunc) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" return SSLSetIOFuncs(sslContext, readFunc, writeFunc); #pragma clang diagnostic pop } PAL_TlsHandshakeState AppleCryptoNative_SslHandshake(SSLContextRef sslContext) { if (sslContext == NULL) return PAL_TlsHandshakeState_Unknown; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" OSStatus osStatus = SSLHandshake(sslContext); #pragma clang diagnostic pop switch (osStatus) { case noErr: return PAL_TlsHandshakeState_Complete; case errSSLWouldBlock: return PAL_TlsHandshakeState_WouldBlock; case errSSLServerAuthCompleted: return PAL_TlsHandshakeState_ServerAuthCompleted; case errSSLClientCertRequested: return PAL_TlsHandshakeState_ClientCertRequested; default: return osStatus; } } static PAL_TlsIo OSStatusToPAL_TlsIo(OSStatus status) { switch (status) { case noErr: return PAL_TlsIo_Success; case errSSLWouldBlock: return PAL_TlsIo_WouldBlock; case errSSLClosedGraceful: return PAL_TlsIo_ClosedGracefully; default: return status; } } PAL_TlsIo AppleCryptoNative_SslWrite(SSLContextRef sslContext, const uint8_t* buf, uint32_t bufLen, uint32_t* bytesWritten) { if (bytesWritten == NULL) return PAL_TlsIo_Unknown; size_t expected = (size_t)bufLen; size_t totalWritten; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" OSStatus status = SSLWrite(sslContext, buf, expected, &totalWritten); #pragma clang diagnostic pop if (status != noErr) { *bytesWritten = (uint32_t)totalWritten; return OSStatusToPAL_TlsIo(status); } return PAL_TlsIo_Success; } PAL_TlsIo AppleCryptoNative_SslRead(SSLContextRef sslContext, uint8_t* buf, uint32_t bufLen, uint32_t* written) { if (written == NULL) return PAL_TlsIo_Unknown; size_t writtenSize = 0; size_t bufSize = (size_t)bufLen; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" OSStatus status = SSLRead(sslContext, buf, bufSize, &writtenSize); #pragma clang diagnostic pop if (writtenSize > UINT_MAX) { // This shouldn't happen, because we passed a uint32_t as the initial buffer size. // But, just in case it does, report back that we're no longer in a known state. return PAL_TlsIo_Unknown; } *written = (uint32_t)writtenSize; if (writtenSize == 0 && status == errSSLWouldBlock) { SSLSessionState state; memset(&state, 0, sizeof(SSLSessionState)); #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" OSStatus localStatus = SSLGetSessionState(sslContext, &state); if (localStatus == noErr && state == kSSLHandshake) { return PAL_TlsIo_Renegotiate; } #pragma clang diagnostic pop } return OSStatusToPAL_TlsIo(status); } int32_t AppleCryptoNative_SslIsHostnameMatch(SSLContextRef sslContext, CFStringRef cfHostname, CFDateRef notBefore, int32_t* pOSStatus) { if (pOSStatus != NULL) *pOSStatus = noErr; if (sslContext == NULL || notBefore == NULL || pOSStatus == NULL) return -1; if (cfHostname == NULL) return -2; SecPolicyRef sslPolicy = SecPolicyCreateSSL(true, cfHostname); if (sslPolicy == NULL) return -3; CFMutableArrayRef certs = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks); if (certs == NULL) return -4; SecTrustRef existingTrust = NULL; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" OSStatus osStatus = SSLCopyPeerTrust(sslContext, &existingTrust); #pragma clang diagnostic pop if (osStatus != noErr) { CFRelease(certs); *pOSStatus = osStatus; return -5; } CFMutableArrayRef anchors = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks); if (anchors == NULL) { CFRelease(certs); CFRelease(existingTrust); return -6; } CFIndex certificateCount = SecTrustGetCertificateCount(existingTrust); for (CFIndex i = 0; i < certificateCount; i++) { SecCertificateRef item = SecTrustGetCertificateAtIndex(existingTrust, i); CFArrayAppendValue(certs, item); // Copy the EE cert into the anchors set, this will make the chain part // always return true. if (i == 0) { CFArrayAppendValue(anchors, item); } } SecTrustRef trust = NULL; osStatus = SecTrustCreateWithCertificates(certs, sslPolicy, &trust); int32_t ret = INT_MIN; if (osStatus == noErr) { osStatus = SecTrustSetAnchorCertificates(trust, anchors); } if (osStatus == noErr) { osStatus = SecTrustSetVerifyDate(trust, notBefore); } if (osStatus == noErr) { SecTrustResultType trustResult; memset(&trustResult, 0, sizeof(SecTrustResultType)); #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" osStatus = SecTrustEvaluate(trust, &trustResult); if (trustResult == kSecTrustResultRecoverableTrustFailure && osStatus == noErr && certificateCount > 1) { // If we get recoverable failure, let's try it again with full anchor list. // We already stored just the first certificate into anchors; now we store the rest. for (CFIndex i = 1; i < certificateCount; i++) { CFArrayAppendValue(anchors, SecTrustGetCertificateAtIndex(existingTrust, i)); } osStatus = SecTrustSetAnchorCertificates(trust, anchors); if (osStatus == noErr) { memset(&trustResult, 0, sizeof(SecTrustResultType)); osStatus = SecTrustEvaluate(trust, &trustResult); } } #pragma clang diagnostic pop if (osStatus == noErr && trustResult != kSecTrustResultUnspecified && trustResult != kSecTrustResultProceed) { // If evaluation succeeded but result is not trusted try to get details. CFDictionaryRef detailsAndStuff = SecTrustCopyResult(trust); if (detailsAndStuff != NULL) { CFArrayRef details = CFDictionaryGetValue(detailsAndStuff, CFSTR("TrustResultDetails")); if (details != NULL && CFArrayGetCount(details) > 0) { CFArrayRef statusCodes = CFDictionaryGetValue(CFArrayGetValueAtIndex(details,0), CFSTR("StatusCodes")); if (statusCodes != NULL) { OSStatus status = 0; // look for first failure to keep it simple. Normally, there will be exactly one. for (int i = 0; i < CFArrayGetCount(statusCodes); i++) { CFNumberGetValue(CFArrayGetValueAtIndex(statusCodes, i), kCFNumberSInt32Type, &status); if (status != noErr) { *pOSStatus = status; break; } } } } CFRelease(detailsAndStuff); } } if (osStatus != noErr) { ret = -7; *pOSStatus = osStatus; } else if (trustResult == kSecTrustResultUnspecified || trustResult == kSecTrustResultProceed) { ret = 1; } else if (trustResult == kSecTrustResultDeny || trustResult == kSecTrustResultRecoverableTrustFailure) { ret = 0; } else { ret = -8; } } else { *pOSStatus = osStatus; } if (trust != NULL) CFRelease(trust); if (certs != NULL) CFRelease(certs); if (anchors != NULL) CFRelease(anchors); if (existingTrust != NULL) CFRelease(existingTrust); CFRelease(sslPolicy); return ret; } int32_t AppleCryptoNative_SslShutdown(SSLContextRef sslContext) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" return SSLClose(sslContext); #pragma clang diagnostic pop } int32_t AppleCryptoNative_SslGetProtocolVersion(SSLContextRef sslContext, PAL_SslProtocol* pProtocol) { if (pProtocol != NULL) *pProtocol = 0; if (sslContext == NULL || pProtocol == NULL) return errSecParam; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" SSLProtocol protocol = kSSLProtocolUnknown; OSStatus osStatus = SSLGetNegotiatedProtocolVersion(sslContext, &protocol); if (osStatus == noErr) { PAL_SslProtocol matchedProtocol = PAL_SslProtocol_None; if (protocol == kTLSProtocol13) matchedProtocol = PAL_SslProtocol_Tls13; else if (protocol == kTLSProtocol12) matchedProtocol = PAL_SslProtocol_Tls12; else if (protocol == kTLSProtocol11) matchedProtocol = PAL_SslProtocol_Tls11; else if (protocol == kTLSProtocol1) matchedProtocol = PAL_SslProtocol_Tls10; else if (protocol == kSSLProtocol3) matchedProtocol = PAL_SslProtocol_Ssl3; else if (protocol == kSSLProtocol2) matchedProtocol = PAL_SslProtocol_Ssl2; *pProtocol = matchedProtocol; } #pragma clang diagnostic pop return osStatus; } int32_t AppleCryptoNative_SslGetCipherSuite(SSLContextRef sslContext, uint16_t* pCipherSuiteOut) { if (pCipherSuiteOut == NULL) { return errSecParam; } SSLCipherSuite cipherSuite; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" OSStatus status = SSLGetNegotiatedCipher(sslContext, &cipherSuite); #pragma clang diagnostic pop *pCipherSuiteOut = (uint16_t)cipherSuite; return status; } int32_t AppleCryptoNative_SslSetEnabledCipherSuites(SSLContextRef sslContext, const uint32_t* cipherSuites, int32_t numCipherSuites) { // Max numCipherSuites is 2^16 (all possible cipher suites) assert(numCipherSuites < (1 << 16)); #if !defined(TARGET_ARM64) && !defined(TARGET_IOS) && !defined(TARGET_TVOS) if (sizeof(SSLCipherSuite) == sizeof(uint32_t)) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" // macOS & MacCatalyst x64 return SSLSetEnabledCiphers(sslContext, (const SSLCipherSuite *)cipherSuites, (size_t)numCipherSuites); #pragma clang diagnostic pop } else #endif { // MacCatalyst arm64, iOS, tvOS, watchOS SSLCipherSuite* cipherSuites16 = (SSLCipherSuite*)calloc((size_t)numCipherSuites, sizeof(SSLCipherSuite)); if (cipherSuites16 == NULL) { return errSSLInternal; } for (int i = 0; i < numCipherSuites; i++) { cipherSuites16[i] = (SSLCipherSuite)cipherSuites[i]; } #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" OSStatus status = SSLSetEnabledCiphers(sslContext, cipherSuites16, (size_t)numCipherSuites); #pragma clang diagnostic pop free(cipherSuites16); return status; } } // This API is present on macOS 10.5 and newer only static OSStatus (*SSLSetCertificateAuthoritiesPtr)(SSLContextRef context, CFArrayRef certificates, int32_t replaceExisting) = NULL; PALEXPORT int32_t AppleCryptoNative_SslSetCertificateAuthorities(SSLContextRef sslContext, CFArrayRef certificates, int32_t replaceExisting) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" // The underlying call handles NULL inputs, so just pass it through if (!SSLSetCertificateAuthoritiesPtr) { // not available. return 0; } return SSLSetCertificateAuthoritiesPtr(sslContext, certificates, replaceExisting); #pragma clang diagnostic pop } __attribute__((constructor)) static void InitializeAppleCryptoSslShim() { SSLSetCertificateAuthoritiesPtr = (OSStatus(*)(SSLContextRef, CFArrayRef, int32_t))dlsym(RTLD_DEFAULT, "SSLSetCertificateAuthorities"); SSLSetALPNProtocolsPtr = (OSStatus(*)(SSLContextRef, CFArrayRef))dlsym(RTLD_DEFAULT, "SSLSetALPNProtocols"); SSLCopyALPNProtocolsPtr = (OSStatus(*)(SSLContextRef, CFArrayRef*))dlsym(RTLD_DEFAULT, "SSLCopyALPNProtocols"); }
-1
dotnet/runtime
66,452
[mono] Stop setting time_date_stamp field in MonoImage
We never read that field in the runtime and it was causing unnecessary disk IO during startup (5ms on my iOS device). It was also never set on Windows already.
akoeplinger
2022-03-10T15:49:37Z
2022-03-10T21:47:58Z
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
d2826308964e4ee4496d6884e09811e1f709005e
[mono] Stop setting time_date_stamp field in MonoImage. We never read that field in the runtime and it was causing unnecessary disk IO during startup (5ms on my iOS device). It was also never set on Windows already.
./src/native/corehost/redirected_error_writer.h
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #ifndef _COREHOST_CLI_REDIRECTED_ERROR_WRITER_H_ #define _COREHOST_CLI_REDIRECTED_ERROR_WRITER_H_ #include <pal.h> void reset_redirected_error_writer(); void __cdecl redirected_error_writer(const pal::char_t* msg); pal::string_t get_redirected_error_string(); #endif /* _COREHOST_CLI_REDIRECTED_ERROR_WRITER_H_ */
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #ifndef _COREHOST_CLI_REDIRECTED_ERROR_WRITER_H_ #define _COREHOST_CLI_REDIRECTED_ERROR_WRITER_H_ #include <pal.h> void reset_redirected_error_writer(); void __cdecl redirected_error_writer(const pal::char_t* msg); pal::string_t get_redirected_error_string(); #endif /* _COREHOST_CLI_REDIRECTED_ERROR_WRITER_H_ */
-1
dotnet/runtime
66,452
[mono] Stop setting time_date_stamp field in MonoImage
We never read that field in the runtime and it was causing unnecessary disk IO during startup (5ms on my iOS device). It was also never set on Windows already.
akoeplinger
2022-03-10T15:49:37Z
2022-03-10T21:47:58Z
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
d2826308964e4ee4496d6884e09811e1f709005e
[mono] Stop setting time_date_stamp field in MonoImage. We never read that field in the runtime and it was causing unnecessary disk IO during startup (5ms on my iOS device). It was also never set on Windows already.
./src/coreclr/pal/src/libunwind/src/tilegx/Linit_remote.c
#define UNW_LOCAL_ONLY #include <libunwind.h> #if defined(UNW_LOCAL_ONLY) && !defined(UNW_REMOTE_ONLY) #include "Ginit_remote.c" #endif
#define UNW_LOCAL_ONLY #include <libunwind.h> #if defined(UNW_LOCAL_ONLY) && !defined(UNW_REMOTE_ONLY) #include "Ginit_remote.c" #endif
-1
dotnet/runtime
66,452
[mono] Stop setting time_date_stamp field in MonoImage
We never read that field in the runtime and it was causing unnecessary disk IO during startup (5ms on my iOS device). It was also never set on Windows already.
akoeplinger
2022-03-10T15:49:37Z
2022-03-10T21:47:58Z
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
d2826308964e4ee4496d6884e09811e1f709005e
[mono] Stop setting time_date_stamp field in MonoImage. We never read that field in the runtime and it was causing unnecessary disk IO during startup (5ms on my iOS device). It was also never set on Windows already.
./src/mono/mono/mini/arch-stubs.c
/** * \file */ #include "mini.h" /* Dummy versions of some arch specific functions to avoid ifdefs at call sites */ #ifndef MONO_ARCH_GSHAREDVT_SUPPORTED gboolean mono_arch_gsharedvt_sig_supported (MonoMethodSignature *sig) { return FALSE; } gpointer mono_arch_get_gsharedvt_call_info (MonoMemoryManager *mem_manager, gpointer addr, MonoMethodSignature *normal_sig, MonoMethodSignature *gsharedvt_sig, gboolean gsharedvt_in, gint32 vcall_offset, gboolean calli) { g_assert_not_reached (); return NULL; } gpointer mono_arch_get_gsharedvt_arg_trampoline (gpointer arg, gpointer addr) { g_assert_not_reached (); return NULL; } gpointer mono_arch_get_gsharedvt_trampoline (MonoTrampInfo **info, gboolean aot) { g_assert_not_reached (); return NULL; } #endif #ifndef MONO_ARCH_HAVE_DECOMPOSE_OPTS void mono_arch_decompose_opts (MonoCompile *cfg, MonoInst *ins) { } #endif #ifndef MONO_ARCH_HAVE_OPCODE_NEEDS_EMULATION gboolean mono_arch_opcode_needs_emulation (MonoCompile *cfg, int opcode) { return TRUE; } #endif #ifndef MONO_ARCH_HAVE_DECOMPOSE_LONG_OPTS void mono_arch_decompose_long_opts (MonoCompile *cfg, MonoInst *ins) { } #endif #ifndef MONO_ARCH_INTERPRETER_SUPPORTED gpointer mono_arch_get_interp_to_native_trampoline (MonoTrampInfo **info) { g_assert_not_reached (); return NULL; } gpointer mono_arch_get_native_to_interp_trampoline (MonoTrampInfo **info) { g_assert_not_reached (); return NULL; } void mono_arch_undo_ip_adjustment (MonoContext *context) { g_assert_not_reached (); } void mono_arch_do_ip_adjustment (MonoContext *context) { g_assert_not_reached (); } #endif #ifndef MONO_ARCH_HAVE_EXCEPTIONS_INIT void mono_arch_exceptions_init (void) { } #endif #if defined (DISABLE_JIT) && !defined (HOST_WASM) gpointer mono_arch_get_restore_context (MonoTrampInfo **info, gboolean aot) { g_assert_not_reached (); return NULL; } gpointer mono_arch_get_call_filter (MonoTrampInfo **info, gboolean aot) { g_assert_not_reached (); return NULL; } gpointer mono_arch_get_throw_exception (MonoTrampInfo **info, gboolean aot) { g_assert_not_reached (); return NULL; } gpointer mono_arch_get_rethrow_exception (MonoTrampInfo **info, gboolean aot) { g_assert_not_reached (); return NULL; } gpointer mono_arch_get_rethrow_preserve_exception (MonoTrampInfo **info, gboolean aot) { g_assert_not_reached (); return NULL; } gpointer mono_arch_get_throw_corlib_exception (MonoTrampInfo **info, gboolean aot) { g_assert_not_reached (); return NULL; } #endif /* DISABLE_JIT */
/** * \file */ #include "mini.h" /* Dummy versions of some arch specific functions to avoid ifdefs at call sites */ #ifndef MONO_ARCH_GSHAREDVT_SUPPORTED gboolean mono_arch_gsharedvt_sig_supported (MonoMethodSignature *sig) { return FALSE; } gpointer mono_arch_get_gsharedvt_call_info (MonoMemoryManager *mem_manager, gpointer addr, MonoMethodSignature *normal_sig, MonoMethodSignature *gsharedvt_sig, gboolean gsharedvt_in, gint32 vcall_offset, gboolean calli) { g_assert_not_reached (); return NULL; } gpointer mono_arch_get_gsharedvt_arg_trampoline (gpointer arg, gpointer addr) { g_assert_not_reached (); return NULL; } gpointer mono_arch_get_gsharedvt_trampoline (MonoTrampInfo **info, gboolean aot) { g_assert_not_reached (); return NULL; } #endif #ifndef MONO_ARCH_HAVE_DECOMPOSE_OPTS void mono_arch_decompose_opts (MonoCompile *cfg, MonoInst *ins) { } #endif #ifndef MONO_ARCH_HAVE_OPCODE_NEEDS_EMULATION gboolean mono_arch_opcode_needs_emulation (MonoCompile *cfg, int opcode) { return TRUE; } #endif #ifndef MONO_ARCH_HAVE_DECOMPOSE_LONG_OPTS void mono_arch_decompose_long_opts (MonoCompile *cfg, MonoInst *ins) { } #endif #ifndef MONO_ARCH_INTERPRETER_SUPPORTED gpointer mono_arch_get_interp_to_native_trampoline (MonoTrampInfo **info) { g_assert_not_reached (); return NULL; } gpointer mono_arch_get_native_to_interp_trampoline (MonoTrampInfo **info) { g_assert_not_reached (); return NULL; } void mono_arch_undo_ip_adjustment (MonoContext *context) { g_assert_not_reached (); } void mono_arch_do_ip_adjustment (MonoContext *context) { g_assert_not_reached (); } #endif #ifndef MONO_ARCH_HAVE_EXCEPTIONS_INIT void mono_arch_exceptions_init (void) { } #endif #if defined (DISABLE_JIT) && !defined (HOST_WASM) gpointer mono_arch_get_restore_context (MonoTrampInfo **info, gboolean aot) { g_assert_not_reached (); return NULL; } gpointer mono_arch_get_call_filter (MonoTrampInfo **info, gboolean aot) { g_assert_not_reached (); return NULL; } gpointer mono_arch_get_throw_exception (MonoTrampInfo **info, gboolean aot) { g_assert_not_reached (); return NULL; } gpointer mono_arch_get_rethrow_exception (MonoTrampInfo **info, gboolean aot) { g_assert_not_reached (); return NULL; } gpointer mono_arch_get_rethrow_preserve_exception (MonoTrampInfo **info, gboolean aot) { g_assert_not_reached (); return NULL; } gpointer mono_arch_get_throw_corlib_exception (MonoTrampInfo **info, gboolean aot) { g_assert_not_reached (); return NULL; } #endif /* DISABLE_JIT */
-1
dotnet/runtime
66,452
[mono] Stop setting time_date_stamp field in MonoImage
We never read that field in the runtime and it was causing unnecessary disk IO during startup (5ms on my iOS device). It was also never set on Windows already.
akoeplinger
2022-03-10T15:49:37Z
2022-03-10T21:47:58Z
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
d2826308964e4ee4496d6884e09811e1f709005e
[mono] Stop setting time_date_stamp field in MonoImage. We never read that field in the runtime and it was causing unnecessary disk IO during startup (5ms on my iOS device). It was also never set on Windows already.
./src/coreclr/inc/metamodelpub.h
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. //***************************************************************************** // MetaModelPub.h -- header file for Common Language Runtime metadata. // // //***************************************************************************** #ifndef _METAMODELPUB_H_ #define _METAMODELPUB_H_ #if _MSC_VER >= 1100 # pragma once #endif #include <cor.h> #include "contract.h" template<class T> inline T Align4(T p) { LIMITED_METHOD_CONTRACT; INT_PTR i = (INT_PTR)p; i = (i+(3)) & ~3; return (T)i; } typedef uint32_t RID; // check if a rid is valid or not #define InvalidRid(rid) ((rid) == 0) #ifndef METADATA_FIELDS_PROTECTION #define METADATA_FIELDS_PROTECTION public #endif //***************************************************************************** // Record definitions. Records have some combination of fixed size fields and // variable sized fields (actually, constant across a database, but variable // between databases). // // In this section we define record definitions which include the fixed size // fields and an enumeration of the variable sized fields. // // Naming is as follows: // Given some table "Xyz": // class XyzRec { public: // SOMETYPE m_SomeField; // // rest of the fixed fields. // enum { COL_Xyz_SomeOtherField, // // rest of the fields, enumerated. // COL_Xyz_COUNT }; // }; // // The important features are the class name (XyzRec), the enumerations // (COL_Xyz_FieldName), and the enumeration count (COL_Xyz_COUNT). // // THESE NAMING CONVENTIONS ARE CARVED IN STONE! DON'T TRY TO BE CREATIVE! // //***************************************************************************** // Have the compiler generate two byte alignment. Be careful to manually lay // out the fields for proper alignment. The alignment for variable-sized // fields will be computed at save time. #include <pshpack2.h> // Non-sparse tables. class ModuleRec { METADATA_FIELDS_PROTECTION: USHORT m_Generation; // ENC generation. public: enum { COL_Generation, COL_Name, COL_Mvid, COL_EncId, COL_EncBaseId, COL_COUNT, COL_KEY }; USHORT GetGeneration() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_Generation); } void SetGeneration(USHORT Generation) { LIMITED_METHOD_CONTRACT; m_Generation = VAL16(Generation); } }; class TypeRefRec { public: enum { COL_ResolutionScope, // mdModuleRef or mdAssemblyRef. COL_Name, COL_Namespace, COL_COUNT, COL_KEY }; }; class TypeDefRec { METADATA_FIELDS_PROTECTION: ULONG m_Flags; // Flags for this TypeDef public: enum { COL_Flags, COL_Name, // offset into string pool. COL_Namespace, COL_Extends, // coded token to typedef/typeref. COL_FieldList, // rid of first field. COL_MethodList, // rid of first method. COL_COUNT, COL_KEY }; ULONG GetFlags() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL32(&m_Flags); } void SetFlags(ULONG Flags) { LIMITED_METHOD_CONTRACT; m_Flags = VAL32(Flags); } void AddFlags(ULONG Flags) { LIMITED_METHOD_CONTRACT; m_Flags |= VAL32(Flags); } void RemoveFlags(ULONG Flags) { LIMITED_METHOD_CONTRACT; m_Flags &= ~VAL32(Flags); } }; class FieldPtrRec { public: enum { COL_Field, COL_COUNT, COL_KEY }; }; class FieldRec { METADATA_FIELDS_PROTECTION: USHORT m_Flags; // Flags for the field. public: enum { COL_Flags, COL_Name, COL_Signature, COL_COUNT, COL_KEY }; USHORT GetFlags() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_Flags); } void SetFlags(ULONG Flags) { LIMITED_METHOD_CONTRACT; m_Flags = (USHORT)VAL16(Flags); } void AddFlags(ULONG Flags) { LIMITED_METHOD_CONTRACT; m_Flags |= (USHORT)VAL16(Flags); } void RemoveFlags(ULONG Flags) { LIMITED_METHOD_CONTRACT; m_Flags &= (USHORT)~VAL16(Flags); } }; class MethodPtrRec { public: enum { COL_Method, COL_COUNT, COL_KEY }; }; class MethodRec { METADATA_FIELDS_PROTECTION: ULONG m_RVA; // RVA of the Method. USHORT m_ImplFlags; // Descr flags of the Method. USHORT m_Flags; // Flags for the Method. public: enum { COL_RVA, COL_ImplFlags, COL_Flags, COL_Name, COL_Signature, COL_ParamList, // Rid of first param. COL_COUNT, COL_KEY }; void Copy(MethodRec *pFrom) { LIMITED_METHOD_CONTRACT; m_RVA = pFrom->m_RVA; m_ImplFlags = pFrom->m_ImplFlags; m_Flags = pFrom->m_Flags; } ULONG GetRVA() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL32(&m_RVA); } void SetRVA(ULONG RVA) { LIMITED_METHOD_CONTRACT; m_RVA = VAL32(RVA); } USHORT GetImplFlags() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_ImplFlags); } void SetImplFlags(USHORT ImplFlags) { LIMITED_METHOD_CONTRACT; m_ImplFlags = VAL16(ImplFlags); } void AddImplFlags(USHORT ImplFlags) { LIMITED_METHOD_CONTRACT; m_ImplFlags |= VAL16(ImplFlags); } void RemoveImplFlags(USHORT ImplFlags) { LIMITED_METHOD_CONTRACT; m_ImplFlags &= ~VAL16(ImplFlags); } USHORT GetFlags() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_Flags); } void SetFlags(ULONG Flags) { LIMITED_METHOD_CONTRACT; m_Flags = (USHORT)VAL16(Flags); } void AddFlags(ULONG Flags) { LIMITED_METHOD_CONTRACT; m_Flags |= (USHORT)VAL16(Flags); } void RemoveFlags(ULONG Flags) { LIMITED_METHOD_CONTRACT; m_Flags &= (USHORT)~VAL16(Flags); } }; class ParamPtrRec { public: enum { COL_Param, COL_COUNT, COL_KEY }; }; class ParamRec { METADATA_FIELDS_PROTECTION: USHORT m_Flags; // Flags for this Param. USHORT m_Sequence; // Sequence # of param. 0 - return value. public: enum { COL_Flags, COL_Sequence, COL_Name, // Name of the param. COL_COUNT, COL_KEY }; void Copy(ParamRec *pFrom) { LIMITED_METHOD_CONTRACT; m_Flags = pFrom->m_Flags; m_Sequence = pFrom->m_Sequence; } USHORT GetFlags() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_Flags); } void SetFlags(ULONG Flags) { LIMITED_METHOD_CONTRACT; m_Flags = (USHORT)VAL16(Flags); } void AddFlags(ULONG Flags) { LIMITED_METHOD_CONTRACT; m_Flags |= (USHORT)VAL16(Flags); } void RemoveFlags(ULONG Flags) { LIMITED_METHOD_CONTRACT; m_Flags &= (USHORT)~VAL16(Flags); } USHORT GetSequence() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_Sequence); } void SetSequence(USHORT Sequence) { LIMITED_METHOD_CONTRACT; m_Sequence = VAL16(Sequence); } }; class InterfaceImplRec { public: enum { COL_Class, // Rid of class' TypeDef. COL_Interface, // Coded rid of implemented interface. COL_COUNT, COL_KEY = COL_Class }; }; class MemberRefRec { public: enum { COL_Class, // Rid of TypeDef. COL_Name, COL_Signature, COL_COUNT, COL_KEY }; }; class StandAloneSigRec { public: enum { COL_Signature, COL_COUNT, COL_KEY }; }; // Sparse tables. These contain modifiers for tables above. class ConstantRec { METADATA_FIELDS_PROTECTION: BYTE m_Type; // Type of the constant. BYTE m_PAD1; public: enum { COL_Type, COL_Parent, // Coded rid of object (param, field). COL_Value, // Index into blob pool. COL_COUNT, COL_KEY = COL_Parent }; BYTE GetType() { LIMITED_METHOD_CONTRACT; return m_Type; } void SetType(BYTE Type) { LIMITED_METHOD_CONTRACT; m_Type = Type; } }; class CustomAttributeRec { public: enum { COL_Parent, // Coded rid of any object. COL_Type, // TypeDef or TypeRef. COL_Value, // Blob. COL_COUNT, COL_KEY = COL_Parent }; }; class FieldMarshalRec { public: enum { COL_Parent, // Coded rid of field or param. COL_NativeType, COL_COUNT, COL_KEY = COL_Parent }; }; class DeclSecurityRec { METADATA_FIELDS_PROTECTION: USHORT m_Action; public: enum { COL_Action, COL_Parent, COL_PermissionSet, COL_COUNT, COL_KEY = COL_Parent }; void Copy(DeclSecurityRec *pFrom) { LIMITED_METHOD_CONTRACT; m_Action = pFrom->m_Action; } USHORT GetAction() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_Action); } void SetAction(USHORT Action) { LIMITED_METHOD_CONTRACT; m_Action = VAL16(Action); } }; class ClassLayoutRec { METADATA_FIELDS_PROTECTION: USHORT m_PackingSize; ULONG m_ClassSize; public: enum { COL_PackingSize, COL_ClassSize, COL_Parent, // Rid of TypeDef. COL_COUNT, COL_KEY = COL_Parent }; void Copy(ClassLayoutRec *pFrom) { LIMITED_METHOD_CONTRACT; m_PackingSize = pFrom->m_PackingSize; m_ClassSize = pFrom->m_ClassSize; } USHORT GetPackingSize() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_PackingSize); } void SetPackingSize(USHORT PackingSize) { LIMITED_METHOD_CONTRACT; m_PackingSize = VAL16(PackingSize); } ULONG GetClassSize() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL32(&m_ClassSize); } void SetClassSize(ULONG ClassSize) { LIMITED_METHOD_CONTRACT; m_ClassSize = VAL32(ClassSize); } }; class FieldLayoutRec { METADATA_FIELDS_PROTECTION: ULONG m_OffSet; public: enum { COL_OffSet, COL_Field, COL_COUNT, COL_KEY = COL_Field }; void Copy(FieldLayoutRec *pFrom) { LIMITED_METHOD_CONTRACT; m_OffSet = pFrom->m_OffSet; } ULONG GetOffSet() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL32(&m_OffSet); } void SetOffSet(ULONG Offset) { LIMITED_METHOD_CONTRACT; m_OffSet = VAL32(Offset); } }; class EventMapRec { public: enum { COL_Parent, COL_EventList, // rid of first event. COL_COUNT, COL_KEY }; }; class EventPtrRec { public: enum { COL_Event, COL_COUNT, COL_KEY }; }; class EventRec { METADATA_FIELDS_PROTECTION: USHORT m_EventFlags; public: enum { COL_EventFlags, COL_Name, COL_EventType, COL_COUNT, COL_KEY }; USHORT GetEventFlags() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_EventFlags); } void SetEventFlags(USHORT EventFlags) { LIMITED_METHOD_CONTRACT; m_EventFlags = VAL16(EventFlags); } void AddEventFlags(USHORT EventFlags) { LIMITED_METHOD_CONTRACT; m_EventFlags |= VAL16(EventFlags); } }; class PropertyMapRec { public: enum { COL_Parent, COL_PropertyList, // rid of first property. COL_COUNT, COL_KEY }; }; class PropertyPtrRec { public: enum { COL_Property, COL_COUNT, COL_KEY }; }; class PropertyRec { METADATA_FIELDS_PROTECTION: USHORT m_PropFlags; public: enum { COL_PropFlags, COL_Name, COL_Type, COL_COUNT, COL_KEY }; USHORT GetPropFlags() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_PropFlags); } void SetPropFlags(USHORT PropFlags) { LIMITED_METHOD_CONTRACT; m_PropFlags = VAL16(PropFlags); } void AddPropFlags(USHORT PropFlags) { LIMITED_METHOD_CONTRACT; m_PropFlags |= VAL16(PropFlags); } }; class MethodSemanticsRec { METADATA_FIELDS_PROTECTION: USHORT m_Semantic; public: enum { COL_Semantic, COL_Method, COL_Association, COL_COUNT, COL_KEY = COL_Association }; USHORT GetSemantic() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_Semantic); } void SetSemantic(USHORT Semantic) { LIMITED_METHOD_CONTRACT; m_Semantic = VAL16(Semantic); } }; class MethodImplRec { public: enum { COL_Class, // TypeDef where the MethodBody lives. COL_MethodBody, // MethodDef or MemberRef. COL_MethodDeclaration, // MethodDef or MemberRef. COL_COUNT, COL_KEY = COL_Class }; }; class ModuleRefRec { public: enum { COL_Name, COL_COUNT, COL_KEY }; }; class TypeSpecRec { public: enum { COL_Signature, COL_COUNT, COL_KEY }; }; class ImplMapRec { METADATA_FIELDS_PROTECTION: USHORT m_MappingFlags; public: enum { COL_MappingFlags, COL_MemberForwarded, // mdField or mdMethod. COL_ImportName, COL_ImportScope, // mdModuleRef. COL_COUNT, COL_KEY = COL_MemberForwarded }; USHORT GetMappingFlags() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_MappingFlags); } void SetMappingFlags(USHORT MappingFlags) { LIMITED_METHOD_CONTRACT; m_MappingFlags = VAL16(MappingFlags); } }; class FieldRVARec { METADATA_FIELDS_PROTECTION: ULONG m_RVA; public: enum{ COL_RVA, COL_Field, COL_COUNT, COL_KEY = COL_Field }; void Copy(FieldRVARec *pFrom) { LIMITED_METHOD_CONTRACT; m_RVA = pFrom->m_RVA; } ULONG GetRVA() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL32(&m_RVA); } void SetRVA(ULONG RVA) { LIMITED_METHOD_CONTRACT; m_RVA = VAL32(RVA); } }; class ENCLogRec { METADATA_FIELDS_PROTECTION: ULONG m_Token; // Token, or like a token, but with (ixTbl|0x80) instead of token type. ULONG m_FuncCode; // Function code describing the nature of ENC change. public: enum { COL_Token, COL_FuncCode, COL_COUNT, COL_KEY }; ULONG GetToken() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL32(&m_Token); } void SetToken(ULONG Token) { LIMITED_METHOD_CONTRACT; m_Token = VAL32(Token); } ULONG GetFuncCode() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL32(&m_FuncCode); } void SetFuncCode(ULONG FuncCode) { LIMITED_METHOD_CONTRACT; m_FuncCode = VAL32(FuncCode); } }; class ENCMapRec { METADATA_FIELDS_PROTECTION: ULONG m_Token; // Token, or like a token, but with (ixTbl|0x80) instead of token type. public: enum { COL_Token, COL_COUNT, COL_KEY }; ULONG GetToken() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL32(&m_Token); } void SetToken(ULONG Token) { LIMITED_METHOD_CONTRACT; m_Token = VAL32(Token); } }; // Assembly tables. class AssemblyRec { METADATA_FIELDS_PROTECTION: ULONG m_HashAlgId; USHORT m_MajorVersion; USHORT m_MinorVersion; USHORT m_BuildNumber; USHORT m_RevisionNumber; ULONG m_Flags; public: enum { COL_HashAlgId, COL_MajorVersion, COL_MinorVersion, COL_BuildNumber, COL_RevisionNumber, COL_Flags, COL_PublicKey, // Public key identifying the publisher COL_Name, COL_Locale, COL_COUNT, COL_KEY }; void Copy(AssemblyRec *pFrom) { LIMITED_METHOD_CONTRACT; m_HashAlgId = pFrom->m_HashAlgId; m_MajorVersion = pFrom->m_MajorVersion; m_MinorVersion = pFrom->m_MinorVersion; m_BuildNumber = pFrom->m_BuildNumber; m_RevisionNumber = pFrom->m_RevisionNumber; m_Flags = pFrom->m_Flags; } ULONG GetHashAlgId() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL32(&m_HashAlgId); } void SetHashAlgId (ULONG HashAlgId) { LIMITED_METHOD_CONTRACT; m_HashAlgId = VAL32(HashAlgId); } USHORT GetMajorVersion() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_MajorVersion); } void SetMajorVersion (USHORT MajorVersion) { LIMITED_METHOD_CONTRACT; m_MajorVersion = VAL16(MajorVersion); } USHORT GetMinorVersion() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_MinorVersion); } void SetMinorVersion (USHORT MinorVersion) { LIMITED_METHOD_CONTRACT; m_MinorVersion = VAL16(MinorVersion); } USHORT GetBuildNumber() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_BuildNumber); } void SetBuildNumber (USHORT BuildNumber) { LIMITED_METHOD_CONTRACT; m_BuildNumber = VAL16(BuildNumber); } USHORT GetRevisionNumber() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_RevisionNumber); } void SetRevisionNumber (USHORT RevisionNumber) { LIMITED_METHOD_CONTRACT; m_RevisionNumber = VAL16(RevisionNumber); } ULONG GetFlags() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL32(&m_Flags); } void SetFlags (ULONG Flags) { LIMITED_METHOD_CONTRACT; m_Flags = VAL32(Flags); } }; class AssemblyProcessorRec { METADATA_FIELDS_PROTECTION: ULONG m_Processor; public: enum { COL_Processor, COL_COUNT, COL_KEY }; ULONG GetProcessor() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL32(&m_Processor); } void SetProcessor(ULONG Processor) { LIMITED_METHOD_CONTRACT; m_Processor = VAL32(Processor); } }; class AssemblyOSRec { METADATA_FIELDS_PROTECTION: ULONG m_OSPlatformId; ULONG m_OSMajorVersion; ULONG m_OSMinorVersion; public: enum { COL_OSPlatformId, COL_OSMajorVersion, COL_OSMinorVersion, COL_COUNT, COL_KEY }; ULONG GetOSPlatformId() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL32(&m_OSPlatformId); } void SetOSPlatformId(ULONG OSPlatformId) { LIMITED_METHOD_CONTRACT; m_OSPlatformId = VAL32(OSPlatformId); } ULONG GetOSMajorVersion() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL32(&m_OSMajorVersion); } void SetOSMajorVersion(ULONG OSMajorVersion) { LIMITED_METHOD_CONTRACT; m_OSMajorVersion = VAL32(OSMajorVersion); } ULONG GetOSMinorVersion() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL32(&m_OSMinorVersion); } void SetOSMinorVersion(ULONG OSMinorVersion) { LIMITED_METHOD_CONTRACT; m_OSMinorVersion = VAL32(OSMinorVersion); } }; class AssemblyRefRec { METADATA_FIELDS_PROTECTION: USHORT m_MajorVersion; USHORT m_MinorVersion; USHORT m_BuildNumber; USHORT m_RevisionNumber; ULONG m_Flags; public: enum { COL_MajorVersion, COL_MinorVersion, COL_BuildNumber, COL_RevisionNumber, COL_Flags, COL_PublicKeyOrToken, // The public key or token identifying the publisher of the Assembly. COL_Name, COL_Locale, COL_HashValue, COL_COUNT, COL_KEY }; void Copy(AssemblyRefRec *pFrom) { LIMITED_METHOD_CONTRACT; m_MajorVersion = pFrom->m_MajorVersion; m_MinorVersion = pFrom->m_MinorVersion; m_BuildNumber = pFrom->m_BuildNumber; m_RevisionNumber = pFrom->m_RevisionNumber; m_Flags = pFrom->m_Flags; } USHORT GetMajorVersion() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_MajorVersion); } void SetMajorVersion(USHORT MajorVersion) { LIMITED_METHOD_CONTRACT; m_MajorVersion = VAL16(MajorVersion); } USHORT GetMinorVersion() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_MinorVersion); } void SetMinorVersion(USHORT MinorVersion) { LIMITED_METHOD_CONTRACT; m_MinorVersion = VAL16(MinorVersion); } USHORT GetBuildNumber() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_BuildNumber); } void SetBuildNumber(USHORT BuildNumber) { LIMITED_METHOD_CONTRACT; m_BuildNumber = VAL16(BuildNumber); } USHORT GetRevisionNumber() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_RevisionNumber); } void SetRevisionNumber(USHORT RevisionNumber) { LIMITED_METHOD_CONTRACT; m_RevisionNumber = RevisionNumber; } ULONG GetFlags() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL32(&m_Flags); } void SetFlags(ULONG Flags) { LIMITED_METHOD_CONTRACT; m_Flags = VAL32(Flags); } }; class AssemblyRefProcessorRec { METADATA_FIELDS_PROTECTION: ULONG m_Processor; public: enum { COL_Processor, COL_AssemblyRef, // mdtAssemblyRef COL_COUNT, COL_KEY }; ULONG GetProcessor() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL32(&m_Processor); } void SetProcessor(ULONG Processor) { LIMITED_METHOD_CONTRACT; m_Processor = VAL32(Processor); } }; class AssemblyRefOSRec { METADATA_FIELDS_PROTECTION: ULONG m_OSPlatformId; ULONG m_OSMajorVersion; ULONG m_OSMinorVersion; public: enum { COL_OSPlatformId, COL_OSMajorVersion, COL_OSMinorVersion, COL_AssemblyRef, // mdtAssemblyRef. COL_COUNT, COL_KEY }; ULONG GetOSPlatformId() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL32(&m_OSPlatformId); } void SetOSPlatformId(ULONG OSPlatformId) { LIMITED_METHOD_CONTRACT; m_OSPlatformId = VAL32(OSPlatformId); } ULONG GetOSMajorVersion() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL32(&m_OSMajorVersion); } void SetOSMajorVersion(ULONG OSMajorVersion) { LIMITED_METHOD_CONTRACT; m_OSMajorVersion = VAL32(OSMajorVersion); } ULONG GetOSMinorVersion() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL32(&m_OSMinorVersion); } void SetOSMinorVersion(ULONG OSMinorVersion) { LIMITED_METHOD_CONTRACT; m_OSMinorVersion = VAL32(OSMinorVersion); } }; class FileRec { METADATA_FIELDS_PROTECTION: ULONG m_Flags; public: enum { COL_Flags, COL_Name, COL_HashValue, COL_COUNT, COL_KEY }; void Copy(FileRec *pFrom) { LIMITED_METHOD_CONTRACT; m_Flags = pFrom->m_Flags; } ULONG GetFlags() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL32(&m_Flags); } void SetFlags(ULONG Flags) { LIMITED_METHOD_CONTRACT; m_Flags = VAL32(Flags); } }; class ExportedTypeRec { METADATA_FIELDS_PROTECTION: ULONG m_Flags; ULONG m_TypeDefId; public: enum { COL_Flags, COL_TypeDefId, COL_TypeName, COL_TypeNamespace, COL_Implementation, // mdFile or mdAssemblyRef. COL_COUNT, COL_KEY }; void Copy(ExportedTypeRec *pFrom) { LIMITED_METHOD_CONTRACT; m_Flags = pFrom->m_Flags; m_TypeDefId = pFrom->m_TypeDefId; } ULONG GetFlags() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL32(&m_Flags); } void SetFlags(ULONG Flags) { LIMITED_METHOD_CONTRACT; m_Flags = VAL32(Flags); } ULONG GetTypeDefId() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL32(&m_TypeDefId); } void SetTypeDefId(ULONG TypeDefId) { LIMITED_METHOD_CONTRACT; m_TypeDefId = VAL32(TypeDefId); } }; class ManifestResourceRec { METADATA_FIELDS_PROTECTION: ULONG m_Offset; ULONG m_Flags; public: enum { COL_Offset, COL_Flags, COL_Name, COL_Implementation, // mdFile or mdAssemblyRef. COL_COUNT, COL_KEY }; void Copy(ManifestResourceRec *pFrom) { LIMITED_METHOD_CONTRACT; m_Flags = pFrom->m_Flags; m_Offset = pFrom->m_Offset; } ULONG GetOffset() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL32(&m_Offset); } void SetOffset(ULONG Offset) { LIMITED_METHOD_CONTRACT; m_Offset = VAL32(Offset); } ULONG GetFlags() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL32(&m_Flags); } void SetFlags(ULONG Flags) { LIMITED_METHOD_CONTRACT; m_Flags = VAL32(Flags); } }; // End Assembly Tables. class NestedClassRec { public: enum { COL_NestedClass, COL_EnclosingClass, COL_COUNT, COL_KEY = COL_NestedClass }; }; // Generics class GenericParamRec { METADATA_FIELDS_PROTECTION: USHORT m_Number; // index; zero = first var USHORT m_Flags; // index; zero = first var public: enum { COL_Number, // index; zero = first var COL_Flags, // flags, for future use COL_Owner, // typeDef/methodDef COL_Name, // Purely descriptive, not used for binding purposes COL_COUNT, COL_KEY = COL_Owner }; USHORT GetNumber() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_Number); } void SetNumber(USHORT Number) { LIMITED_METHOD_CONTRACT; m_Number = VAL16(Number); } USHORT GetFlags() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_Flags); } void SetFlags(USHORT Flags) { LIMITED_METHOD_CONTRACT; m_Flags = VAL16(Flags); } }; // @todo: this definition is for reading the old (and wrong) GenericParamRec from a // Beta1 assembly. class GenericParamV1_1Rec { METADATA_FIELDS_PROTECTION: USHORT m_Number; // index; zero = first var USHORT m_Flags; // index; zero = first var public: enum { COL_Number, // index; zero = first var COL_Flags, // flags, for future use COL_Owner, // typeDef/methodDef COL_Name, // Purely descriptive, not used for binding purposes COL_Kind, // typeDef/Ref/Spec, reserved for future use COL_COUNT, COL_KEY = COL_Owner }; USHORT GetNumber() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_Number); } void SetNumber(USHORT Number) { LIMITED_METHOD_CONTRACT; m_Number = VAL16(Number); } USHORT GetFlags() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_Flags); } void SetFlags(USHORT Flags) { LIMITED_METHOD_CONTRACT; m_Flags = VAL16(Flags); } }; class MethodSpecRec { public: enum { COL_Method, // methodDef/memberRef COL_Instantiation, // signature COL_COUNT, COL_KEY }; }; class GenericParamConstraintRec { public: enum { COL_Owner, // GenericParam COL_Constraint, // typeDef/Ref/Spec COL_COUNT, COL_KEY = COL_Owner }; }; #ifdef FEATURE_METADATA_EMIT_PORTABLE_PDB /* Portable PDB tables */ // -- Dummy records to fill the gap to 0x30 class DummyRec { public: enum { COL_COUNT, COL_KEY }; }; class Dummy1Rec : public DummyRec {}; class Dummy2Rec : public DummyRec {}; class Dummy3Rec : public DummyRec {}; class DocumentRec { public: enum { COL_Name, COL_HashAlgorithm, COL_Hash, COL_Language, COL_COUNT, COL_KEY }; }; class MethodDebugInformationRec { public: enum { COL_Document, COL_SequencePoints, COL_COUNT, COL_KEY }; }; class LocalScopeRec { METADATA_FIELDS_PROTECTION: // [IMPORTANT]: Assigning values directly can override other columns, use PutCol instead ULONG m_StartOffset; // [IMPORTANT]: Assigning values directly can override other columns, use PutCol instead ULONG m_Length; public: enum { COL_Method, COL_ImportScope, COL_VariableList, COL_ConstantList, COL_StartOffset, COL_Length, COL_COUNT, COL_KEY }; }; class LocalVariableRec { METADATA_FIELDS_PROTECTION: USHORT m_Attributes; USHORT m_Index; public: enum { COL_Attributes, COL_Index, COL_Name, COL_COUNT, COL_KEY }; USHORT GetAttributes() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_Attributes); } void SetAttributes(USHORT attributes) { LIMITED_METHOD_CONTRACT; m_Attributes = VAL16(attributes); } USHORT GetIndex() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_Index); } void SetIndex(USHORT index) { LIMITED_METHOD_CONTRACT; m_Index = VAL16(index); } }; class LocalConstantRec { public: enum { COL_Name, COL_Signature, COL_COUNT, COL_KEY }; }; class ImportScopeRec { public: enum { COL_Parent, COL_Imports, COL_COUNT, COL_KEY }; }; // TODO: // class StateMachineMethodRec // class CustomDebugInformationRec #endif // FEATURE_METADATA_EMIT_PORTABLE_PDB #include <poppack.h> // List of MiniMd tables. #define MiniMdTables() \ MiniMdTable(Module) \ MiniMdTable(TypeRef) \ MiniMdTable(TypeDef) \ MiniMdTable(FieldPtr) \ MiniMdTable(Field) \ MiniMdTable(MethodPtr) \ MiniMdTable(Method) \ MiniMdTable(ParamPtr) \ MiniMdTable(Param) \ MiniMdTable(InterfaceImpl) \ MiniMdTable(MemberRef) \ MiniMdTable(Constant) \ MiniMdTable(CustomAttribute)\ MiniMdTable(FieldMarshal) \ MiniMdTable(DeclSecurity) \ MiniMdTable(ClassLayout) \ MiniMdTable(FieldLayout) \ MiniMdTable(StandAloneSig) \ MiniMdTable(EventMap) \ MiniMdTable(EventPtr) \ MiniMdTable(Event) \ MiniMdTable(PropertyMap) \ MiniMdTable(PropertyPtr) \ MiniMdTable(Property) \ MiniMdTable(MethodSemantics)\ MiniMdTable(MethodImpl) \ MiniMdTable(ModuleRef) \ MiniMdTable(TypeSpec) \ MiniMdTable(ImplMap) \ MiniMdTable(FieldRVA) \ MiniMdTable(ENCLog) \ MiniMdTable(ENCMap) \ MiniMdTable(Assembly) \ MiniMdTable(AssemblyProcessor) \ MiniMdTable(AssemblyOS) \ MiniMdTable(AssemblyRef) \ MiniMdTable(AssemblyRefProcessor) \ MiniMdTable(AssemblyRefOS) \ MiniMdTable(File) \ MiniMdTable(ExportedType) \ MiniMdTable(ManifestResource) \ MiniMdTable(NestedClass) \ MiniMdTable(GenericParam) \ MiniMdTable(MethodSpec) \ MiniMdTable(GenericParamConstraint) #ifdef FEATURE_METADATA_EMIT_PORTABLE_PDB #define PortablePdbMiniMdTables() \ /* Dummy tables to fill the gap to 0x30 */ \ MiniMdTable(Dummy1) /* 0x2D */ \ MiniMdTable(Dummy2) /* 0x2E */ \ MiniMdTable(Dummy3) /* 0x2F */ \ /* Actual portable PDB tables */ \ MiniMdTable(Document) /* 0x30 */ \ MiniMdTable(MethodDebugInformation) /* 0x31 */ \ MiniMdTable(LocalScope) /* 0x32 */ \ MiniMdTable(LocalVariable) /* 0x33 */ \ MiniMdTable(LocalConstant) /* 0x34 */ \ MiniMdTable(ImportScope) /* 0x35 */ \ // TODO: // MiniMdTable(StateMachineMethod) /* 0x36 */ // MiniMdTable(CustomDebugInformation) /* 0x37 */ #endif // FEATURE_METADATA_EMIT_PORTABLE_PDB #undef MiniMdTable #define MiniMdTable(x) TBL_##x, enum { MiniMdTables() #ifdef FEATURE_METADATA_EMIT_PORTABLE_PDB PortablePdbMiniMdTables() #endif TBL_COUNT, // Highest table. TBL_COUNT_V1 = TBL_NestedClass + 1, // Highest table in v1.0 database #ifndef FEATURE_METADATA_EMIT_PORTABLE_PDB TBL_COUNT_V2 = TBL_GenericParamConstraint + 1 // Highest in v2.0 database #else TBL_COUNT_V2 = TBL_ImportScope + 1 // Highest in portable PDB database #endif }; #undef MiniMdTable // List of MiniMd coded token types. #define MiniMdCodedTokens() \ MiniMdCodedToken(TypeDefOrRef) \ MiniMdCodedToken(HasConstant) \ MiniMdCodedToken(HasCustomAttribute) \ MiniMdCodedToken(HasFieldMarshal) \ MiniMdCodedToken(HasDeclSecurity) \ MiniMdCodedToken(MemberRefParent) \ MiniMdCodedToken(HasSemantic) \ MiniMdCodedToken(MethodDefOrRef) \ MiniMdCodedToken(MemberForwarded) \ MiniMdCodedToken(Implementation) \ MiniMdCodedToken(CustomAttributeType) \ MiniMdCodedToken(ResolutionScope) \ MiniMdCodedToken(TypeOrMethodDef) \ #undef MiniMdCodedToken #define MiniMdCodedToken(x) CDTKN_##x, enum { MiniMdCodedTokens() CDTKN_COUNT }; #undef MiniMdCodedToken //***************************************************************************** // Meta-meta data. Constant across all MiniMds. //***************************************************************************** #ifndef _META_DATA_META_CONSTANTS_DEFINED #define _META_DATA_META_CONSTANTS_DEFINED const unsigned int iRidMax = 63; const unsigned int iCodedToken = 64; // base of coded tokens. const unsigned int iCodedTokenMax = 95; const unsigned int iSHORT = 96; // fixed types. const unsigned int iUSHORT = 97; const unsigned int iLONG = 98; const unsigned int iULONG = 99; const unsigned int iBYTE = 100; const unsigned int iSTRING = 101; // pool types. const unsigned int iGUID = 102; const unsigned int iBLOB = 103; inline int IsRidType(ULONG ix) {LIMITED_METHOD_CONTRACT; return ix <= iRidMax; } inline int IsCodedTokenType(ULONG ix) {LIMITED_METHOD_CONTRACT; return (ix >= iCodedToken) && (ix <= iCodedTokenMax); } inline int IsRidOrToken(ULONG ix) {LIMITED_METHOD_CONTRACT; return ix <= iCodedTokenMax; } inline int IsHeapType(ULONG ix) {LIMITED_METHOD_CONTRACT; return ix >= iSTRING; } inline int IsFixedType(ULONG ix) {LIMITED_METHOD_CONTRACT; return (ix < iSTRING) && (ix > iCodedTokenMax); } #endif enum MDPools { MDPoolStrings, // Id for the string pool. MDPoolGuids, // ...the GUID pool. MDPoolBlobs, // ...the blob pool. MDPoolUSBlobs, // ...the user string pool. MDPoolCount, // Count of pools, for array sizing. }; // enum MDPools struct CCodedTokenDef { ULONG m_cTokens; // Count of tokens. const mdToken *m_pTokens; // Array of tokens. const char *m_pName; // Name of the coded-token type. }; struct CMiniColDef { BYTE m_Type; // Type of the column. BYTE m_oColumn; // Offset of the column. BYTE m_cbColumn; // Size of the column. }; struct CMiniTableDef { CMiniColDef *m_pColDefs; // Array of field defs. BYTE m_cCols; // Count of columns in the table. BYTE m_iKey; // Column which is the key, if any. USHORT m_cbRec; // Size of the records. }; struct CMiniTableDefEx { CMiniTableDef m_Def; // Table definition. const char * const *m_pColNames; // Array of column names. const char *m_pName; // Name of the table. }; #endif // _METAMODELPUB_H_ // eof ------------------------------------------------------------------------
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. //***************************************************************************** // MetaModelPub.h -- header file for Common Language Runtime metadata. // // //***************************************************************************** #ifndef _METAMODELPUB_H_ #define _METAMODELPUB_H_ #if _MSC_VER >= 1100 # pragma once #endif #include <cor.h> #include "contract.h" template<class T> inline T Align4(T p) { LIMITED_METHOD_CONTRACT; INT_PTR i = (INT_PTR)p; i = (i+(3)) & ~3; return (T)i; } typedef uint32_t RID; // check if a rid is valid or not #define InvalidRid(rid) ((rid) == 0) #ifndef METADATA_FIELDS_PROTECTION #define METADATA_FIELDS_PROTECTION public #endif //***************************************************************************** // Record definitions. Records have some combination of fixed size fields and // variable sized fields (actually, constant across a database, but variable // between databases). // // In this section we define record definitions which include the fixed size // fields and an enumeration of the variable sized fields. // // Naming is as follows: // Given some table "Xyz": // class XyzRec { public: // SOMETYPE m_SomeField; // // rest of the fixed fields. // enum { COL_Xyz_SomeOtherField, // // rest of the fields, enumerated. // COL_Xyz_COUNT }; // }; // // The important features are the class name (XyzRec), the enumerations // (COL_Xyz_FieldName), and the enumeration count (COL_Xyz_COUNT). // // THESE NAMING CONVENTIONS ARE CARVED IN STONE! DON'T TRY TO BE CREATIVE! // //***************************************************************************** // Have the compiler generate two byte alignment. Be careful to manually lay // out the fields for proper alignment. The alignment for variable-sized // fields will be computed at save time. #include <pshpack2.h> // Non-sparse tables. class ModuleRec { METADATA_FIELDS_PROTECTION: USHORT m_Generation; // ENC generation. public: enum { COL_Generation, COL_Name, COL_Mvid, COL_EncId, COL_EncBaseId, COL_COUNT, COL_KEY }; USHORT GetGeneration() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_Generation); } void SetGeneration(USHORT Generation) { LIMITED_METHOD_CONTRACT; m_Generation = VAL16(Generation); } }; class TypeRefRec { public: enum { COL_ResolutionScope, // mdModuleRef or mdAssemblyRef. COL_Name, COL_Namespace, COL_COUNT, COL_KEY }; }; class TypeDefRec { METADATA_FIELDS_PROTECTION: ULONG m_Flags; // Flags for this TypeDef public: enum { COL_Flags, COL_Name, // offset into string pool. COL_Namespace, COL_Extends, // coded token to typedef/typeref. COL_FieldList, // rid of first field. COL_MethodList, // rid of first method. COL_COUNT, COL_KEY }; ULONG GetFlags() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL32(&m_Flags); } void SetFlags(ULONG Flags) { LIMITED_METHOD_CONTRACT; m_Flags = VAL32(Flags); } void AddFlags(ULONG Flags) { LIMITED_METHOD_CONTRACT; m_Flags |= VAL32(Flags); } void RemoveFlags(ULONG Flags) { LIMITED_METHOD_CONTRACT; m_Flags &= ~VAL32(Flags); } }; class FieldPtrRec { public: enum { COL_Field, COL_COUNT, COL_KEY }; }; class FieldRec { METADATA_FIELDS_PROTECTION: USHORT m_Flags; // Flags for the field. public: enum { COL_Flags, COL_Name, COL_Signature, COL_COUNT, COL_KEY }; USHORT GetFlags() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_Flags); } void SetFlags(ULONG Flags) { LIMITED_METHOD_CONTRACT; m_Flags = (USHORT)VAL16(Flags); } void AddFlags(ULONG Flags) { LIMITED_METHOD_CONTRACT; m_Flags |= (USHORT)VAL16(Flags); } void RemoveFlags(ULONG Flags) { LIMITED_METHOD_CONTRACT; m_Flags &= (USHORT)~VAL16(Flags); } }; class MethodPtrRec { public: enum { COL_Method, COL_COUNT, COL_KEY }; }; class MethodRec { METADATA_FIELDS_PROTECTION: ULONG m_RVA; // RVA of the Method. USHORT m_ImplFlags; // Descr flags of the Method. USHORT m_Flags; // Flags for the Method. public: enum { COL_RVA, COL_ImplFlags, COL_Flags, COL_Name, COL_Signature, COL_ParamList, // Rid of first param. COL_COUNT, COL_KEY }; void Copy(MethodRec *pFrom) { LIMITED_METHOD_CONTRACT; m_RVA = pFrom->m_RVA; m_ImplFlags = pFrom->m_ImplFlags; m_Flags = pFrom->m_Flags; } ULONG GetRVA() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL32(&m_RVA); } void SetRVA(ULONG RVA) { LIMITED_METHOD_CONTRACT; m_RVA = VAL32(RVA); } USHORT GetImplFlags() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_ImplFlags); } void SetImplFlags(USHORT ImplFlags) { LIMITED_METHOD_CONTRACT; m_ImplFlags = VAL16(ImplFlags); } void AddImplFlags(USHORT ImplFlags) { LIMITED_METHOD_CONTRACT; m_ImplFlags |= VAL16(ImplFlags); } void RemoveImplFlags(USHORT ImplFlags) { LIMITED_METHOD_CONTRACT; m_ImplFlags &= ~VAL16(ImplFlags); } USHORT GetFlags() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_Flags); } void SetFlags(ULONG Flags) { LIMITED_METHOD_CONTRACT; m_Flags = (USHORT)VAL16(Flags); } void AddFlags(ULONG Flags) { LIMITED_METHOD_CONTRACT; m_Flags |= (USHORT)VAL16(Flags); } void RemoveFlags(ULONG Flags) { LIMITED_METHOD_CONTRACT; m_Flags &= (USHORT)~VAL16(Flags); } }; class ParamPtrRec { public: enum { COL_Param, COL_COUNT, COL_KEY }; }; class ParamRec { METADATA_FIELDS_PROTECTION: USHORT m_Flags; // Flags for this Param. USHORT m_Sequence; // Sequence # of param. 0 - return value. public: enum { COL_Flags, COL_Sequence, COL_Name, // Name of the param. COL_COUNT, COL_KEY }; void Copy(ParamRec *pFrom) { LIMITED_METHOD_CONTRACT; m_Flags = pFrom->m_Flags; m_Sequence = pFrom->m_Sequence; } USHORT GetFlags() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_Flags); } void SetFlags(ULONG Flags) { LIMITED_METHOD_CONTRACT; m_Flags = (USHORT)VAL16(Flags); } void AddFlags(ULONG Flags) { LIMITED_METHOD_CONTRACT; m_Flags |= (USHORT)VAL16(Flags); } void RemoveFlags(ULONG Flags) { LIMITED_METHOD_CONTRACT; m_Flags &= (USHORT)~VAL16(Flags); } USHORT GetSequence() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_Sequence); } void SetSequence(USHORT Sequence) { LIMITED_METHOD_CONTRACT; m_Sequence = VAL16(Sequence); } }; class InterfaceImplRec { public: enum { COL_Class, // Rid of class' TypeDef. COL_Interface, // Coded rid of implemented interface. COL_COUNT, COL_KEY = COL_Class }; }; class MemberRefRec { public: enum { COL_Class, // Rid of TypeDef. COL_Name, COL_Signature, COL_COUNT, COL_KEY }; }; class StandAloneSigRec { public: enum { COL_Signature, COL_COUNT, COL_KEY }; }; // Sparse tables. These contain modifiers for tables above. class ConstantRec { METADATA_FIELDS_PROTECTION: BYTE m_Type; // Type of the constant. BYTE m_PAD1; public: enum { COL_Type, COL_Parent, // Coded rid of object (param, field). COL_Value, // Index into blob pool. COL_COUNT, COL_KEY = COL_Parent }; BYTE GetType() { LIMITED_METHOD_CONTRACT; return m_Type; } void SetType(BYTE Type) { LIMITED_METHOD_CONTRACT; m_Type = Type; } }; class CustomAttributeRec { public: enum { COL_Parent, // Coded rid of any object. COL_Type, // TypeDef or TypeRef. COL_Value, // Blob. COL_COUNT, COL_KEY = COL_Parent }; }; class FieldMarshalRec { public: enum { COL_Parent, // Coded rid of field or param. COL_NativeType, COL_COUNT, COL_KEY = COL_Parent }; }; class DeclSecurityRec { METADATA_FIELDS_PROTECTION: USHORT m_Action; public: enum { COL_Action, COL_Parent, COL_PermissionSet, COL_COUNT, COL_KEY = COL_Parent }; void Copy(DeclSecurityRec *pFrom) { LIMITED_METHOD_CONTRACT; m_Action = pFrom->m_Action; } USHORT GetAction() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_Action); } void SetAction(USHORT Action) { LIMITED_METHOD_CONTRACT; m_Action = VAL16(Action); } }; class ClassLayoutRec { METADATA_FIELDS_PROTECTION: USHORT m_PackingSize; ULONG m_ClassSize; public: enum { COL_PackingSize, COL_ClassSize, COL_Parent, // Rid of TypeDef. COL_COUNT, COL_KEY = COL_Parent }; void Copy(ClassLayoutRec *pFrom) { LIMITED_METHOD_CONTRACT; m_PackingSize = pFrom->m_PackingSize; m_ClassSize = pFrom->m_ClassSize; } USHORT GetPackingSize() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_PackingSize); } void SetPackingSize(USHORT PackingSize) { LIMITED_METHOD_CONTRACT; m_PackingSize = VAL16(PackingSize); } ULONG GetClassSize() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL32(&m_ClassSize); } void SetClassSize(ULONG ClassSize) { LIMITED_METHOD_CONTRACT; m_ClassSize = VAL32(ClassSize); } }; class FieldLayoutRec { METADATA_FIELDS_PROTECTION: ULONG m_OffSet; public: enum { COL_OffSet, COL_Field, COL_COUNT, COL_KEY = COL_Field }; void Copy(FieldLayoutRec *pFrom) { LIMITED_METHOD_CONTRACT; m_OffSet = pFrom->m_OffSet; } ULONG GetOffSet() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL32(&m_OffSet); } void SetOffSet(ULONG Offset) { LIMITED_METHOD_CONTRACT; m_OffSet = VAL32(Offset); } }; class EventMapRec { public: enum { COL_Parent, COL_EventList, // rid of first event. COL_COUNT, COL_KEY }; }; class EventPtrRec { public: enum { COL_Event, COL_COUNT, COL_KEY }; }; class EventRec { METADATA_FIELDS_PROTECTION: USHORT m_EventFlags; public: enum { COL_EventFlags, COL_Name, COL_EventType, COL_COUNT, COL_KEY }; USHORT GetEventFlags() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_EventFlags); } void SetEventFlags(USHORT EventFlags) { LIMITED_METHOD_CONTRACT; m_EventFlags = VAL16(EventFlags); } void AddEventFlags(USHORT EventFlags) { LIMITED_METHOD_CONTRACT; m_EventFlags |= VAL16(EventFlags); } }; class PropertyMapRec { public: enum { COL_Parent, COL_PropertyList, // rid of first property. COL_COUNT, COL_KEY }; }; class PropertyPtrRec { public: enum { COL_Property, COL_COUNT, COL_KEY }; }; class PropertyRec { METADATA_FIELDS_PROTECTION: USHORT m_PropFlags; public: enum { COL_PropFlags, COL_Name, COL_Type, COL_COUNT, COL_KEY }; USHORT GetPropFlags() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_PropFlags); } void SetPropFlags(USHORT PropFlags) { LIMITED_METHOD_CONTRACT; m_PropFlags = VAL16(PropFlags); } void AddPropFlags(USHORT PropFlags) { LIMITED_METHOD_CONTRACT; m_PropFlags |= VAL16(PropFlags); } }; class MethodSemanticsRec { METADATA_FIELDS_PROTECTION: USHORT m_Semantic; public: enum { COL_Semantic, COL_Method, COL_Association, COL_COUNT, COL_KEY = COL_Association }; USHORT GetSemantic() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_Semantic); } void SetSemantic(USHORT Semantic) { LIMITED_METHOD_CONTRACT; m_Semantic = VAL16(Semantic); } }; class MethodImplRec { public: enum { COL_Class, // TypeDef where the MethodBody lives. COL_MethodBody, // MethodDef or MemberRef. COL_MethodDeclaration, // MethodDef or MemberRef. COL_COUNT, COL_KEY = COL_Class }; }; class ModuleRefRec { public: enum { COL_Name, COL_COUNT, COL_KEY }; }; class TypeSpecRec { public: enum { COL_Signature, COL_COUNT, COL_KEY }; }; class ImplMapRec { METADATA_FIELDS_PROTECTION: USHORT m_MappingFlags; public: enum { COL_MappingFlags, COL_MemberForwarded, // mdField or mdMethod. COL_ImportName, COL_ImportScope, // mdModuleRef. COL_COUNT, COL_KEY = COL_MemberForwarded }; USHORT GetMappingFlags() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_MappingFlags); } void SetMappingFlags(USHORT MappingFlags) { LIMITED_METHOD_CONTRACT; m_MappingFlags = VAL16(MappingFlags); } }; class FieldRVARec { METADATA_FIELDS_PROTECTION: ULONG m_RVA; public: enum{ COL_RVA, COL_Field, COL_COUNT, COL_KEY = COL_Field }; void Copy(FieldRVARec *pFrom) { LIMITED_METHOD_CONTRACT; m_RVA = pFrom->m_RVA; } ULONG GetRVA() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL32(&m_RVA); } void SetRVA(ULONG RVA) { LIMITED_METHOD_CONTRACT; m_RVA = VAL32(RVA); } }; class ENCLogRec { METADATA_FIELDS_PROTECTION: ULONG m_Token; // Token, or like a token, but with (ixTbl|0x80) instead of token type. ULONG m_FuncCode; // Function code describing the nature of ENC change. public: enum { COL_Token, COL_FuncCode, COL_COUNT, COL_KEY }; ULONG GetToken() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL32(&m_Token); } void SetToken(ULONG Token) { LIMITED_METHOD_CONTRACT; m_Token = VAL32(Token); } ULONG GetFuncCode() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL32(&m_FuncCode); } void SetFuncCode(ULONG FuncCode) { LIMITED_METHOD_CONTRACT; m_FuncCode = VAL32(FuncCode); } }; class ENCMapRec { METADATA_FIELDS_PROTECTION: ULONG m_Token; // Token, or like a token, but with (ixTbl|0x80) instead of token type. public: enum { COL_Token, COL_COUNT, COL_KEY }; ULONG GetToken() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL32(&m_Token); } void SetToken(ULONG Token) { LIMITED_METHOD_CONTRACT; m_Token = VAL32(Token); } }; // Assembly tables. class AssemblyRec { METADATA_FIELDS_PROTECTION: ULONG m_HashAlgId; USHORT m_MajorVersion; USHORT m_MinorVersion; USHORT m_BuildNumber; USHORT m_RevisionNumber; ULONG m_Flags; public: enum { COL_HashAlgId, COL_MajorVersion, COL_MinorVersion, COL_BuildNumber, COL_RevisionNumber, COL_Flags, COL_PublicKey, // Public key identifying the publisher COL_Name, COL_Locale, COL_COUNT, COL_KEY }; void Copy(AssemblyRec *pFrom) { LIMITED_METHOD_CONTRACT; m_HashAlgId = pFrom->m_HashAlgId; m_MajorVersion = pFrom->m_MajorVersion; m_MinorVersion = pFrom->m_MinorVersion; m_BuildNumber = pFrom->m_BuildNumber; m_RevisionNumber = pFrom->m_RevisionNumber; m_Flags = pFrom->m_Flags; } ULONG GetHashAlgId() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL32(&m_HashAlgId); } void SetHashAlgId (ULONG HashAlgId) { LIMITED_METHOD_CONTRACT; m_HashAlgId = VAL32(HashAlgId); } USHORT GetMajorVersion() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_MajorVersion); } void SetMajorVersion (USHORT MajorVersion) { LIMITED_METHOD_CONTRACT; m_MajorVersion = VAL16(MajorVersion); } USHORT GetMinorVersion() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_MinorVersion); } void SetMinorVersion (USHORT MinorVersion) { LIMITED_METHOD_CONTRACT; m_MinorVersion = VAL16(MinorVersion); } USHORT GetBuildNumber() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_BuildNumber); } void SetBuildNumber (USHORT BuildNumber) { LIMITED_METHOD_CONTRACT; m_BuildNumber = VAL16(BuildNumber); } USHORT GetRevisionNumber() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_RevisionNumber); } void SetRevisionNumber (USHORT RevisionNumber) { LIMITED_METHOD_CONTRACT; m_RevisionNumber = VAL16(RevisionNumber); } ULONG GetFlags() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL32(&m_Flags); } void SetFlags (ULONG Flags) { LIMITED_METHOD_CONTRACT; m_Flags = VAL32(Flags); } }; class AssemblyProcessorRec { METADATA_FIELDS_PROTECTION: ULONG m_Processor; public: enum { COL_Processor, COL_COUNT, COL_KEY }; ULONG GetProcessor() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL32(&m_Processor); } void SetProcessor(ULONG Processor) { LIMITED_METHOD_CONTRACT; m_Processor = VAL32(Processor); } }; class AssemblyOSRec { METADATA_FIELDS_PROTECTION: ULONG m_OSPlatformId; ULONG m_OSMajorVersion; ULONG m_OSMinorVersion; public: enum { COL_OSPlatformId, COL_OSMajorVersion, COL_OSMinorVersion, COL_COUNT, COL_KEY }; ULONG GetOSPlatformId() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL32(&m_OSPlatformId); } void SetOSPlatformId(ULONG OSPlatformId) { LIMITED_METHOD_CONTRACT; m_OSPlatformId = VAL32(OSPlatformId); } ULONG GetOSMajorVersion() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL32(&m_OSMajorVersion); } void SetOSMajorVersion(ULONG OSMajorVersion) { LIMITED_METHOD_CONTRACT; m_OSMajorVersion = VAL32(OSMajorVersion); } ULONG GetOSMinorVersion() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL32(&m_OSMinorVersion); } void SetOSMinorVersion(ULONG OSMinorVersion) { LIMITED_METHOD_CONTRACT; m_OSMinorVersion = VAL32(OSMinorVersion); } }; class AssemblyRefRec { METADATA_FIELDS_PROTECTION: USHORT m_MajorVersion; USHORT m_MinorVersion; USHORT m_BuildNumber; USHORT m_RevisionNumber; ULONG m_Flags; public: enum { COL_MajorVersion, COL_MinorVersion, COL_BuildNumber, COL_RevisionNumber, COL_Flags, COL_PublicKeyOrToken, // The public key or token identifying the publisher of the Assembly. COL_Name, COL_Locale, COL_HashValue, COL_COUNT, COL_KEY }; void Copy(AssemblyRefRec *pFrom) { LIMITED_METHOD_CONTRACT; m_MajorVersion = pFrom->m_MajorVersion; m_MinorVersion = pFrom->m_MinorVersion; m_BuildNumber = pFrom->m_BuildNumber; m_RevisionNumber = pFrom->m_RevisionNumber; m_Flags = pFrom->m_Flags; } USHORT GetMajorVersion() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_MajorVersion); } void SetMajorVersion(USHORT MajorVersion) { LIMITED_METHOD_CONTRACT; m_MajorVersion = VAL16(MajorVersion); } USHORT GetMinorVersion() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_MinorVersion); } void SetMinorVersion(USHORT MinorVersion) { LIMITED_METHOD_CONTRACT; m_MinorVersion = VAL16(MinorVersion); } USHORT GetBuildNumber() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_BuildNumber); } void SetBuildNumber(USHORT BuildNumber) { LIMITED_METHOD_CONTRACT; m_BuildNumber = VAL16(BuildNumber); } USHORT GetRevisionNumber() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_RevisionNumber); } void SetRevisionNumber(USHORT RevisionNumber) { LIMITED_METHOD_CONTRACT; m_RevisionNumber = RevisionNumber; } ULONG GetFlags() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL32(&m_Flags); } void SetFlags(ULONG Flags) { LIMITED_METHOD_CONTRACT; m_Flags = VAL32(Flags); } }; class AssemblyRefProcessorRec { METADATA_FIELDS_PROTECTION: ULONG m_Processor; public: enum { COL_Processor, COL_AssemblyRef, // mdtAssemblyRef COL_COUNT, COL_KEY }; ULONG GetProcessor() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL32(&m_Processor); } void SetProcessor(ULONG Processor) { LIMITED_METHOD_CONTRACT; m_Processor = VAL32(Processor); } }; class AssemblyRefOSRec { METADATA_FIELDS_PROTECTION: ULONG m_OSPlatformId; ULONG m_OSMajorVersion; ULONG m_OSMinorVersion; public: enum { COL_OSPlatformId, COL_OSMajorVersion, COL_OSMinorVersion, COL_AssemblyRef, // mdtAssemblyRef. COL_COUNT, COL_KEY }; ULONG GetOSPlatformId() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL32(&m_OSPlatformId); } void SetOSPlatformId(ULONG OSPlatformId) { LIMITED_METHOD_CONTRACT; m_OSPlatformId = VAL32(OSPlatformId); } ULONG GetOSMajorVersion() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL32(&m_OSMajorVersion); } void SetOSMajorVersion(ULONG OSMajorVersion) { LIMITED_METHOD_CONTRACT; m_OSMajorVersion = VAL32(OSMajorVersion); } ULONG GetOSMinorVersion() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL32(&m_OSMinorVersion); } void SetOSMinorVersion(ULONG OSMinorVersion) { LIMITED_METHOD_CONTRACT; m_OSMinorVersion = VAL32(OSMinorVersion); } }; class FileRec { METADATA_FIELDS_PROTECTION: ULONG m_Flags; public: enum { COL_Flags, COL_Name, COL_HashValue, COL_COUNT, COL_KEY }; void Copy(FileRec *pFrom) { LIMITED_METHOD_CONTRACT; m_Flags = pFrom->m_Flags; } ULONG GetFlags() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL32(&m_Flags); } void SetFlags(ULONG Flags) { LIMITED_METHOD_CONTRACT; m_Flags = VAL32(Flags); } }; class ExportedTypeRec { METADATA_FIELDS_PROTECTION: ULONG m_Flags; ULONG m_TypeDefId; public: enum { COL_Flags, COL_TypeDefId, COL_TypeName, COL_TypeNamespace, COL_Implementation, // mdFile or mdAssemblyRef. COL_COUNT, COL_KEY }; void Copy(ExportedTypeRec *pFrom) { LIMITED_METHOD_CONTRACT; m_Flags = pFrom->m_Flags; m_TypeDefId = pFrom->m_TypeDefId; } ULONG GetFlags() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL32(&m_Flags); } void SetFlags(ULONG Flags) { LIMITED_METHOD_CONTRACT; m_Flags = VAL32(Flags); } ULONG GetTypeDefId() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL32(&m_TypeDefId); } void SetTypeDefId(ULONG TypeDefId) { LIMITED_METHOD_CONTRACT; m_TypeDefId = VAL32(TypeDefId); } }; class ManifestResourceRec { METADATA_FIELDS_PROTECTION: ULONG m_Offset; ULONG m_Flags; public: enum { COL_Offset, COL_Flags, COL_Name, COL_Implementation, // mdFile or mdAssemblyRef. COL_COUNT, COL_KEY }; void Copy(ManifestResourceRec *pFrom) { LIMITED_METHOD_CONTRACT; m_Flags = pFrom->m_Flags; m_Offset = pFrom->m_Offset; } ULONG GetOffset() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL32(&m_Offset); } void SetOffset(ULONG Offset) { LIMITED_METHOD_CONTRACT; m_Offset = VAL32(Offset); } ULONG GetFlags() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL32(&m_Flags); } void SetFlags(ULONG Flags) { LIMITED_METHOD_CONTRACT; m_Flags = VAL32(Flags); } }; // End Assembly Tables. class NestedClassRec { public: enum { COL_NestedClass, COL_EnclosingClass, COL_COUNT, COL_KEY = COL_NestedClass }; }; // Generics class GenericParamRec { METADATA_FIELDS_PROTECTION: USHORT m_Number; // index; zero = first var USHORT m_Flags; // index; zero = first var public: enum { COL_Number, // index; zero = first var COL_Flags, // flags, for future use COL_Owner, // typeDef/methodDef COL_Name, // Purely descriptive, not used for binding purposes COL_COUNT, COL_KEY = COL_Owner }; USHORT GetNumber() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_Number); } void SetNumber(USHORT Number) { LIMITED_METHOD_CONTRACT; m_Number = VAL16(Number); } USHORT GetFlags() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_Flags); } void SetFlags(USHORT Flags) { LIMITED_METHOD_CONTRACT; m_Flags = VAL16(Flags); } }; // @todo: this definition is for reading the old (and wrong) GenericParamRec from a // Beta1 assembly. class GenericParamV1_1Rec { METADATA_FIELDS_PROTECTION: USHORT m_Number; // index; zero = first var USHORT m_Flags; // index; zero = first var public: enum { COL_Number, // index; zero = first var COL_Flags, // flags, for future use COL_Owner, // typeDef/methodDef COL_Name, // Purely descriptive, not used for binding purposes COL_Kind, // typeDef/Ref/Spec, reserved for future use COL_COUNT, COL_KEY = COL_Owner }; USHORT GetNumber() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_Number); } void SetNumber(USHORT Number) { LIMITED_METHOD_CONTRACT; m_Number = VAL16(Number); } USHORT GetFlags() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_Flags); } void SetFlags(USHORT Flags) { LIMITED_METHOD_CONTRACT; m_Flags = VAL16(Flags); } }; class MethodSpecRec { public: enum { COL_Method, // methodDef/memberRef COL_Instantiation, // signature COL_COUNT, COL_KEY }; }; class GenericParamConstraintRec { public: enum { COL_Owner, // GenericParam COL_Constraint, // typeDef/Ref/Spec COL_COUNT, COL_KEY = COL_Owner }; }; #ifdef FEATURE_METADATA_EMIT_PORTABLE_PDB /* Portable PDB tables */ // -- Dummy records to fill the gap to 0x30 class DummyRec { public: enum { COL_COUNT, COL_KEY }; }; class Dummy1Rec : public DummyRec {}; class Dummy2Rec : public DummyRec {}; class Dummy3Rec : public DummyRec {}; class DocumentRec { public: enum { COL_Name, COL_HashAlgorithm, COL_Hash, COL_Language, COL_COUNT, COL_KEY }; }; class MethodDebugInformationRec { public: enum { COL_Document, COL_SequencePoints, COL_COUNT, COL_KEY }; }; class LocalScopeRec { METADATA_FIELDS_PROTECTION: // [IMPORTANT]: Assigning values directly can override other columns, use PutCol instead ULONG m_StartOffset; // [IMPORTANT]: Assigning values directly can override other columns, use PutCol instead ULONG m_Length; public: enum { COL_Method, COL_ImportScope, COL_VariableList, COL_ConstantList, COL_StartOffset, COL_Length, COL_COUNT, COL_KEY }; }; class LocalVariableRec { METADATA_FIELDS_PROTECTION: USHORT m_Attributes; USHORT m_Index; public: enum { COL_Attributes, COL_Index, COL_Name, COL_COUNT, COL_KEY }; USHORT GetAttributes() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_Attributes); } void SetAttributes(USHORT attributes) { LIMITED_METHOD_CONTRACT; m_Attributes = VAL16(attributes); } USHORT GetIndex() { LIMITED_METHOD_CONTRACT; return GET_UNALIGNED_VAL16(&m_Index); } void SetIndex(USHORT index) { LIMITED_METHOD_CONTRACT; m_Index = VAL16(index); } }; class LocalConstantRec { public: enum { COL_Name, COL_Signature, COL_COUNT, COL_KEY }; }; class ImportScopeRec { public: enum { COL_Parent, COL_Imports, COL_COUNT, COL_KEY }; }; // TODO: // class StateMachineMethodRec // class CustomDebugInformationRec #endif // FEATURE_METADATA_EMIT_PORTABLE_PDB #include <poppack.h> // List of MiniMd tables. #define MiniMdTables() \ MiniMdTable(Module) \ MiniMdTable(TypeRef) \ MiniMdTable(TypeDef) \ MiniMdTable(FieldPtr) \ MiniMdTable(Field) \ MiniMdTable(MethodPtr) \ MiniMdTable(Method) \ MiniMdTable(ParamPtr) \ MiniMdTable(Param) \ MiniMdTable(InterfaceImpl) \ MiniMdTable(MemberRef) \ MiniMdTable(Constant) \ MiniMdTable(CustomAttribute)\ MiniMdTable(FieldMarshal) \ MiniMdTable(DeclSecurity) \ MiniMdTable(ClassLayout) \ MiniMdTable(FieldLayout) \ MiniMdTable(StandAloneSig) \ MiniMdTable(EventMap) \ MiniMdTable(EventPtr) \ MiniMdTable(Event) \ MiniMdTable(PropertyMap) \ MiniMdTable(PropertyPtr) \ MiniMdTable(Property) \ MiniMdTable(MethodSemantics)\ MiniMdTable(MethodImpl) \ MiniMdTable(ModuleRef) \ MiniMdTable(TypeSpec) \ MiniMdTable(ImplMap) \ MiniMdTable(FieldRVA) \ MiniMdTable(ENCLog) \ MiniMdTable(ENCMap) \ MiniMdTable(Assembly) \ MiniMdTable(AssemblyProcessor) \ MiniMdTable(AssemblyOS) \ MiniMdTable(AssemblyRef) \ MiniMdTable(AssemblyRefProcessor) \ MiniMdTable(AssemblyRefOS) \ MiniMdTable(File) \ MiniMdTable(ExportedType) \ MiniMdTable(ManifestResource) \ MiniMdTable(NestedClass) \ MiniMdTable(GenericParam) \ MiniMdTable(MethodSpec) \ MiniMdTable(GenericParamConstraint) #ifdef FEATURE_METADATA_EMIT_PORTABLE_PDB #define PortablePdbMiniMdTables() \ /* Dummy tables to fill the gap to 0x30 */ \ MiniMdTable(Dummy1) /* 0x2D */ \ MiniMdTable(Dummy2) /* 0x2E */ \ MiniMdTable(Dummy3) /* 0x2F */ \ /* Actual portable PDB tables */ \ MiniMdTable(Document) /* 0x30 */ \ MiniMdTable(MethodDebugInformation) /* 0x31 */ \ MiniMdTable(LocalScope) /* 0x32 */ \ MiniMdTable(LocalVariable) /* 0x33 */ \ MiniMdTable(LocalConstant) /* 0x34 */ \ MiniMdTable(ImportScope) /* 0x35 */ \ // TODO: // MiniMdTable(StateMachineMethod) /* 0x36 */ // MiniMdTable(CustomDebugInformation) /* 0x37 */ #endif // FEATURE_METADATA_EMIT_PORTABLE_PDB #undef MiniMdTable #define MiniMdTable(x) TBL_##x, enum { MiniMdTables() #ifdef FEATURE_METADATA_EMIT_PORTABLE_PDB PortablePdbMiniMdTables() #endif TBL_COUNT, // Highest table. TBL_COUNT_V1 = TBL_NestedClass + 1, // Highest table in v1.0 database #ifndef FEATURE_METADATA_EMIT_PORTABLE_PDB TBL_COUNT_V2 = TBL_GenericParamConstraint + 1 // Highest in v2.0 database #else TBL_COUNT_V2 = TBL_ImportScope + 1 // Highest in portable PDB database #endif }; #undef MiniMdTable // List of MiniMd coded token types. #define MiniMdCodedTokens() \ MiniMdCodedToken(TypeDefOrRef) \ MiniMdCodedToken(HasConstant) \ MiniMdCodedToken(HasCustomAttribute) \ MiniMdCodedToken(HasFieldMarshal) \ MiniMdCodedToken(HasDeclSecurity) \ MiniMdCodedToken(MemberRefParent) \ MiniMdCodedToken(HasSemantic) \ MiniMdCodedToken(MethodDefOrRef) \ MiniMdCodedToken(MemberForwarded) \ MiniMdCodedToken(Implementation) \ MiniMdCodedToken(CustomAttributeType) \ MiniMdCodedToken(ResolutionScope) \ MiniMdCodedToken(TypeOrMethodDef) \ #undef MiniMdCodedToken #define MiniMdCodedToken(x) CDTKN_##x, enum { MiniMdCodedTokens() CDTKN_COUNT }; #undef MiniMdCodedToken //***************************************************************************** // Meta-meta data. Constant across all MiniMds. //***************************************************************************** #ifndef _META_DATA_META_CONSTANTS_DEFINED #define _META_DATA_META_CONSTANTS_DEFINED const unsigned int iRidMax = 63; const unsigned int iCodedToken = 64; // base of coded tokens. const unsigned int iCodedTokenMax = 95; const unsigned int iSHORT = 96; // fixed types. const unsigned int iUSHORT = 97; const unsigned int iLONG = 98; const unsigned int iULONG = 99; const unsigned int iBYTE = 100; const unsigned int iSTRING = 101; // pool types. const unsigned int iGUID = 102; const unsigned int iBLOB = 103; inline int IsRidType(ULONG ix) {LIMITED_METHOD_CONTRACT; return ix <= iRidMax; } inline int IsCodedTokenType(ULONG ix) {LIMITED_METHOD_CONTRACT; return (ix >= iCodedToken) && (ix <= iCodedTokenMax); } inline int IsRidOrToken(ULONG ix) {LIMITED_METHOD_CONTRACT; return ix <= iCodedTokenMax; } inline int IsHeapType(ULONG ix) {LIMITED_METHOD_CONTRACT; return ix >= iSTRING; } inline int IsFixedType(ULONG ix) {LIMITED_METHOD_CONTRACT; return (ix < iSTRING) && (ix > iCodedTokenMax); } #endif enum MDPools { MDPoolStrings, // Id for the string pool. MDPoolGuids, // ...the GUID pool. MDPoolBlobs, // ...the blob pool. MDPoolUSBlobs, // ...the user string pool. MDPoolCount, // Count of pools, for array sizing. }; // enum MDPools struct CCodedTokenDef { ULONG m_cTokens; // Count of tokens. const mdToken *m_pTokens; // Array of tokens. const char *m_pName; // Name of the coded-token type. }; struct CMiniColDef { BYTE m_Type; // Type of the column. BYTE m_oColumn; // Offset of the column. BYTE m_cbColumn; // Size of the column. }; struct CMiniTableDef { CMiniColDef *m_pColDefs; // Array of field defs. BYTE m_cCols; // Count of columns in the table. BYTE m_iKey; // Column which is the key, if any. USHORT m_cbRec; // Size of the records. }; struct CMiniTableDefEx { CMiniTableDef m_Def; // Table definition. const char * const *m_pColNames; // Array of column names. const char *m_pName; // Name of the table. }; #endif // _METAMODELPUB_H_ // eof ------------------------------------------------------------------------
-1
dotnet/runtime
66,452
[mono] Stop setting time_date_stamp field in MonoImage
We never read that field in the runtime and it was causing unnecessary disk IO during startup (5ms on my iOS device). It was also never set on Windows already.
akoeplinger
2022-03-10T15:49:37Z
2022-03-10T21:47:58Z
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
d2826308964e4ee4496d6884e09811e1f709005e
[mono] Stop setting time_date_stamp field in MonoImage. We never read that field in the runtime and it was causing unnecessary disk IO during startup (5ms on my iOS device). It was also never set on Windows already.
./src/coreclr/md/debug_metadata.h
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // File: Debug_MetaData.h // // // This file defines special macros for debugging MetaData (even in special retail builds). // The level of debugging is set by these (input) macros: // * code:#_DEBUG_METADATA // * code:#_DEBUG_MDSCHEMA // // // #_DEBUG_METADATA // _DEBUG_METADATA ... Enables debugging information in MetaData implementation. It's useful for debugging // retail builds in MetaData (when using CHK build is too slow). // Note: Enabled by default if _DEBUG is defined (see code:#DefaultSetting_DEBUG_METADATA), can be // enabled externally/explicitly also in retail builds (without _DEBUG defined). // // Defines macros (see code:#Macros_DEBUG_METADATA): // * code:#INDEBUG_MD // * code:#COMMA_INDEBUG_MD // * code:#INDEBUG_MD_COMMA // // #_DEBUG_MDSCHEMA // _DEBUG_MDSCHEMA ... Enables additional debugging of MetaData schema. // Note: Allowed to be enabled only if _DEBUG is defined (see code:#Check_DEBUG_MDSCHEMA). // // Defines macros (see code:#Macros_DEBUG_MDSCHEMA): // * code:#_ASSERTE_MDSCHEMA // // ====================================================================================== #pragma once // Include for CLRConfig class used in Debug_ReportError #include <utilcode.h> // -------------------------------------------------------------------------------------- //#DefaultSetting_DEBUG_METADATA // // Enable _DEBUG_METADATA by default if _DEBUG is defined (code:#_DEBUG_METADATA). // #ifdef _DEBUG #define _DEBUG_METADATA #endif //_DEBUG // -------------------------------------------------------------------------------------- //#Macros_DEBUG_METADATA // // Define macros for MetaData implementation debugging (see code:#_DEBUG_METADATA). // #ifdef _DEBUG_METADATA //#INDEBUG_MD #define INDEBUG_MD(expr) expr //#COMMA_INDEBUG_MD #define COMMA_INDEBUG_MD(expr) , expr //#INDEBUG_MD_COMMA #define INDEBUG_MD_COMMA(expr) expr, #define Debug_ReportError(strMessage) \ do { \ if (CLRConfig::GetConfigValue(CLRConfig::INTERNAL_AssertOnBadImageFormat)) \ { _ASSERTE_MSG(FALSE, (strMessage)); } \ } while(0) #define Debug_ReportInternalError(strMessage) _ASSERTE_MSG(FALSE, (strMessage)) #else //!_DEBUG_METADATA #define INDEBUG_MD(expr) #define COMMA_INDEBUG_MD(expr) #define INDEBUG_MD_COMMA(expr) #define Debug_ReportError(strMessage) #define Debug_ReportInternalError(strMessage) _ASSERTE(!(strMessage)) #endif //!_DEBUG_METADATA // -------------------------------------------------------------------------------------- //#Check_DEBUG_MDSCHEMA // // Check that _DEBUG_MDSCHEMA is defined only if _DEBUG is defined (see code:#_DEBUG_MDSCHEMA). // #ifdef _DEBUG_MDSCHEMA #ifndef _DEBUG #error _DEBUG_MDSCHEMA is defined while _DEBUG is not defined. #endif //!_DEBUG #endif //_DEBUG_MDSCHEMA // -------------------------------------------------------------------------------------- //#Macros_DEBUG_MDSCHEMA // // Define macros for MetaData schema debugging (see code:#_DEBUG_MDSCHEMA). // #ifdef _DEBUG_MDSCHEMA //#_ASSERTE_MDSCHEMA // This assert is useful only to catch errors in schema (tables and columns) definitions. It is useful e.g. // for verifying consistency between table record classes (e.g. code:MethodDefRecord) and columns' // offsets/sizes as defined in code:ColumnDefinition. #define _ASSERTE_MDSCHEMA(expr) _ASSERTE(expr) #else //!_DEBUG_MDSCHEMA #define _ASSERTE_MDSCHEMA(expr) #endif //!_DEBUG_MDSCHEMA
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // File: Debug_MetaData.h // // // This file defines special macros for debugging MetaData (even in special retail builds). // The level of debugging is set by these (input) macros: // * code:#_DEBUG_METADATA // * code:#_DEBUG_MDSCHEMA // // // #_DEBUG_METADATA // _DEBUG_METADATA ... Enables debugging information in MetaData implementation. It's useful for debugging // retail builds in MetaData (when using CHK build is too slow). // Note: Enabled by default if _DEBUG is defined (see code:#DefaultSetting_DEBUG_METADATA), can be // enabled externally/explicitly also in retail builds (without _DEBUG defined). // // Defines macros (see code:#Macros_DEBUG_METADATA): // * code:#INDEBUG_MD // * code:#COMMA_INDEBUG_MD // * code:#INDEBUG_MD_COMMA // // #_DEBUG_MDSCHEMA // _DEBUG_MDSCHEMA ... Enables additional debugging of MetaData schema. // Note: Allowed to be enabled only if _DEBUG is defined (see code:#Check_DEBUG_MDSCHEMA). // // Defines macros (see code:#Macros_DEBUG_MDSCHEMA): // * code:#_ASSERTE_MDSCHEMA // // ====================================================================================== #pragma once // Include for CLRConfig class used in Debug_ReportError #include <utilcode.h> // -------------------------------------------------------------------------------------- //#DefaultSetting_DEBUG_METADATA // // Enable _DEBUG_METADATA by default if _DEBUG is defined (code:#_DEBUG_METADATA). // #ifdef _DEBUG #define _DEBUG_METADATA #endif //_DEBUG // -------------------------------------------------------------------------------------- //#Macros_DEBUG_METADATA // // Define macros for MetaData implementation debugging (see code:#_DEBUG_METADATA). // #ifdef _DEBUG_METADATA //#INDEBUG_MD #define INDEBUG_MD(expr) expr //#COMMA_INDEBUG_MD #define COMMA_INDEBUG_MD(expr) , expr //#INDEBUG_MD_COMMA #define INDEBUG_MD_COMMA(expr) expr, #define Debug_ReportError(strMessage) \ do { \ if (CLRConfig::GetConfigValue(CLRConfig::INTERNAL_AssertOnBadImageFormat)) \ { _ASSERTE_MSG(FALSE, (strMessage)); } \ } while(0) #define Debug_ReportInternalError(strMessage) _ASSERTE_MSG(FALSE, (strMessage)) #else //!_DEBUG_METADATA #define INDEBUG_MD(expr) #define COMMA_INDEBUG_MD(expr) #define INDEBUG_MD_COMMA(expr) #define Debug_ReportError(strMessage) #define Debug_ReportInternalError(strMessage) _ASSERTE(!(strMessage)) #endif //!_DEBUG_METADATA // -------------------------------------------------------------------------------------- //#Check_DEBUG_MDSCHEMA // // Check that _DEBUG_MDSCHEMA is defined only if _DEBUG is defined (see code:#_DEBUG_MDSCHEMA). // #ifdef _DEBUG_MDSCHEMA #ifndef _DEBUG #error _DEBUG_MDSCHEMA is defined while _DEBUG is not defined. #endif //!_DEBUG #endif //_DEBUG_MDSCHEMA // -------------------------------------------------------------------------------------- //#Macros_DEBUG_MDSCHEMA // // Define macros for MetaData schema debugging (see code:#_DEBUG_MDSCHEMA). // #ifdef _DEBUG_MDSCHEMA //#_ASSERTE_MDSCHEMA // This assert is useful only to catch errors in schema (tables and columns) definitions. It is useful e.g. // for verifying consistency between table record classes (e.g. code:MethodDefRecord) and columns' // offsets/sizes as defined in code:ColumnDefinition. #define _ASSERTE_MDSCHEMA(expr) _ASSERTE(expr) #else //!_DEBUG_MDSCHEMA #define _ASSERTE_MDSCHEMA(expr) #endif //!_DEBUG_MDSCHEMA
-1
dotnet/runtime
66,452
[mono] Stop setting time_date_stamp field in MonoImage
We never read that field in the runtime and it was causing unnecessary disk IO during startup (5ms on my iOS device). It was also never set on Windows already.
akoeplinger
2022-03-10T15:49:37Z
2022-03-10T21:47:58Z
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
d2826308964e4ee4496d6884e09811e1f709005e
[mono] Stop setting time_date_stamp field in MonoImage. We never read that field in the runtime and it was causing unnecessary disk IO during startup (5ms on my iOS device). It was also never set on Windows already.
./src/native/libs/System.Native/pal_interfaceaddresses.c
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include "pal_config.h" #include "pal_interfaceaddresses.h" #include "pal_maphardwaretype.h" #include "pal_utilities.h" #include "pal_safecrt.h" #include "pal_networking.h" #include <stdlib.h> #include <sys/types.h> #include <assert.h> #if HAVE_IFADDRS || HAVE_GETIFADDRS #include <ifaddrs.h> #endif #if !HAVE_GETIFADDRS && TARGET_ANDROID #include <dlfcn.h> #include <pthread.h> #endif #include <net/if.h> #include <netinet/in.h> #include <string.h> #include <sys/socket.h> #if HAVE_SYS_SYSCTL_H #include <sys/sysctl.h> #endif #if HAVE_SYS_IOCTL_H #include <sys/ioctl.h> #endif #if HAVE_ETHTOOL_H #include <linux/ethtool.h> #include <linux/sockios.h> #include <arpa/inet.h> #endif #if HAVE_NET_IFMEDIA_H #include <net/if_media.h> #elif HAVE_IOS_NET_IFMEDIA_H #include "ios/net/if_media.h" #endif #if defined(AF_PACKET) #include <sys/ioctl.h> #if HAVE_NETPACKET_PACKET_H #include <netpacket/packet.h> #else #include <linux/if_packet.h> #endif #elif defined(AF_LINK) #include <net/if_dl.h> #include <net/if_types.h> #else #error System must have AF_PACKET or AF_LINK. #endif #if HAVE_RT_MSGHDR #if HAVE_IOS_NET_ROUTE_H #include "ios/net/route.h" #else #include <net/route.h> #endif #endif // Convert mask to prefix length e.g. 255.255.255.0 -> 24 // mask parameter is pointer to buffer where address starts and length is // buffer length e.g. 4 for IPv4 and 16 for IPv6. // Code bellow counts consecutive number of 1 bits. static inline uint8_t mask2prefix(uint8_t* mask, int length) { uint8_t len = 0; uint8_t* end = mask + length; if (mask == NULL) { // If we did not get valid mask, assume host address. return (uint8_t)length * 8; } // Get whole bytes while ((mask < end) && (*mask == 0xff)) { len += 8; mask++; } // Get last incomplete byte if (mask < end) { while (*mask) { len++; *mask <<= 1; } } if (len == 0 && length == 4) { len = 32; } return len; } #if !HAVE_IFADDRS && TARGET_ANDROID // This structure is exactly the same as struct ifaddrs defined in ifaddrs.h but since the header // might not be available (e.g., in bionics used in Android before API 24) we need to mirror it here // so that we can dynamically load the getifaddrs function and use it. struct ifaddrs { struct ifaddrs *ifa_next; char *ifa_name; unsigned int ifa_flags; struct sockaddr *ifa_addr; struct sockaddr *ifa_netmask; union { struct sockaddr *ifu_broadaddr; struct sockaddr *ifu_dstaddr; } ifa_ifu; void *ifa_data; }; #endif #if !HAVE_GETIFADDRS && TARGET_ANDROID // Try to load the getifaddrs and freeifaddrs functions manually. // This workaround is necessary on Android prior to API 24 and it can be removed once // we drop support for earlier Android versions. static int (*getifaddrs)(struct ifaddrs**) = NULL; static void (*freeifaddrs)(struct ifaddrs*) = NULL; static void try_loading_getifaddrs() { void *libc = dlopen("libc.so", RTLD_NOW); if (libc) { getifaddrs = (int (*)(struct ifaddrs**)) dlsym(libc, "getifaddrs"); freeifaddrs = (void (*)(struct ifaddrs*)) dlsym(libc, "freeifaddrs"); } } static bool ensure_getifaddrs_is_loaded() { static pthread_once_t getifaddrs_is_loaded = PTHREAD_ONCE_INIT; pthread_once(&getifaddrs_is_loaded, try_loading_getifaddrs); return getifaddrs != NULL && freeifaddrs != NULL; } #endif int32_t SystemNative_EnumerateInterfaceAddresses(void* context, IPv4AddressFound onIpv4Found, IPv6AddressFound onIpv6Found, LinkLayerAddressFound onLinkLayerFound) { #if !HAVE_GETIFADDRS && TARGET_ANDROID // Workaround for Android API < 24 if (!ensure_getifaddrs_is_loaded()) { errno = ENOTSUP; return -1; } #endif #if HAVE_GETIFADDRS || TARGET_ANDROID struct ifaddrs* headAddr; if (getifaddrs(&headAddr) == -1) { return -1; } for (struct ifaddrs* current = headAddr; current != NULL; current = current->ifa_next) { if (current->ifa_addr == NULL) { continue; } uint32_t interfaceIndex = if_nametoindex(current->ifa_name); // ifa_name may be an aliased interface name. // Use if_indextoname to map back to the true device name. char actualName[IF_NAMESIZE]; char* result = if_indextoname(interfaceIndex, actualName); if (result == NULL) { freeifaddrs(headAddr); return -1; } assert(result == actualName); int family = current->ifa_addr->sa_family; if (family == AF_INET) { if (onIpv4Found != NULL) { // IP Address IpAddressInfo iai; memset(&iai, 0, sizeof(IpAddressInfo)); iai.InterfaceIndex = interfaceIndex; iai.NumAddressBytes = NUM_BYTES_IN_IPV4_ADDRESS; struct sockaddr_in* sain = (struct sockaddr_in*)current->ifa_addr; memcpy_s(iai.AddressBytes, sizeof_member(IpAddressInfo, AddressBytes), &sain->sin_addr.s_addr, sizeof(sain->sin_addr.s_addr)); struct sockaddr_in* mask_sain = (struct sockaddr_in*)current->ifa_netmask; // ifa_netmask can be NULL according to documentation, probably P2P interfaces. iai.PrefixLength = mask_sain != NULL ? mask2prefix((uint8_t*)&mask_sain->sin_addr.s_addr, NUM_BYTES_IN_IPV4_ADDRESS) : NUM_BYTES_IN_IPV4_ADDRESS * 8; onIpv4Found(context, actualName, &iai); } } else if (family == AF_INET6) { if (onIpv6Found != NULL) { IpAddressInfo iai; memset(&iai, 0, sizeof(IpAddressInfo)); iai.InterfaceIndex = interfaceIndex; iai.NumAddressBytes = NUM_BYTES_IN_IPV6_ADDRESS; struct sockaddr_in6* sain6 = (struct sockaddr_in6*)current->ifa_addr; memcpy_s(iai.AddressBytes, sizeof_member(IpAddressInfo, AddressBytes), sain6->sin6_addr.s6_addr, sizeof(sain6->sin6_addr.s6_addr)); uint32_t scopeId = sain6->sin6_scope_id; struct sockaddr_in6* mask_sain6 = (struct sockaddr_in6*)current->ifa_netmask; iai.PrefixLength = mask_sain6 != NULL ? mask2prefix((uint8_t*)&mask_sain6->sin6_addr.s6_addr, NUM_BYTES_IN_IPV6_ADDRESS) : NUM_BYTES_IN_IPV6_ADDRESS * 8; onIpv6Found(context, actualName, &iai, &scopeId); } } #if defined(AF_PACKET) else if (family == AF_PACKET) { if (onLinkLayerFound != NULL) { struct sockaddr_ll* sall = (struct sockaddr_ll*)current->ifa_addr; if (sall->sll_halen > sizeof(sall->sll_addr)) { // sockaddr_ll->sll_addr has a maximum capacity of 8 bytes (unsigned char sll_addr[8]) // so if we get a address length greater than that, we truncate it to 8 bytes. // This is following the kernel docs where they always treat physical addresses with a maximum of 8 bytes. // However in WSL we hit an issue where sll_halen was 16 bytes so the memcpy_s below would fail because it was greater. sall->sll_halen = sizeof(sall->sll_addr); } LinkLayerAddressInfo lla; memset(&lla, 0, sizeof(LinkLayerAddressInfo)); lla.InterfaceIndex = interfaceIndex; lla.NumAddressBytes = sall->sll_halen; lla.HardwareType = MapHardwareType(sall->sll_hatype); memcpy_s(&lla.AddressBytes, sizeof_member(LinkLayerAddressInfo, AddressBytes), &sall->sll_addr, sall->sll_halen); onLinkLayerFound(context, current->ifa_name, &lla); } } #elif defined(AF_LINK) else if (family == AF_LINK) { if (onLinkLayerFound != NULL) { struct sockaddr_dl* sadl = (struct sockaddr_dl*)current->ifa_addr; LinkLayerAddressInfo lla; memset(&lla, 0, sizeof(LinkLayerAddressInfo)); lla.InterfaceIndex = interfaceIndex; lla.NumAddressBytes = sadl->sdl_alen; lla.HardwareType = MapHardwareType(sadl->sdl_type); #if HAVE_NET_IFMEDIA_H || HAVE_IOS_NET_IFMEDIA_H if (lla.HardwareType == NetworkInterfaceType_Ethernet) { // WI-FI and Ethernet have same address type so we can try to distinguish more int fd = socket(AF_INET, SOCK_DGRAM, 0); if (fd >= 0) { struct ifmediareq ifmr; memset(&ifmr, 0, sizeof(ifmr)); strncpy(ifmr.ifm_name, actualName, sizeof(ifmr.ifm_name)); if ((ioctl(fd, SIOCGIFMEDIA, (caddr_t)&ifmr) == 0) && (IFM_TYPE(ifmr.ifm_current) == IFM_IEEE80211)) { lla.HardwareType = NetworkInterfaceType_Wireless80211; } close(fd); } } #endif memcpy_s(&lla.AddressBytes, sizeof_member(LinkLayerAddressInfo, AddressBytes), (uint8_t*)LLADDR(sadl), sadl->sdl_alen); onLinkLayerFound(context, current->ifa_name, &lla); } } #endif } freeifaddrs(headAddr); return 0; #else // Not supported. Also, prevent a compiler error because parameters are unused (void)context; (void)onIpv4Found; (void)onIpv6Found; (void)onLinkLayerFound; errno = ENOTSUP; return -1; #endif } int32_t SystemNative_GetNetworkInterfaces(int32_t * interfaceCount, NetworkInterfaceInfo **interfaceList, int32_t * addressCount, IpAddressInfo **addressList ) { #if !HAVE_GETIFADDRS && TARGET_ANDROID // Workaround for Android API < 24 if (!ensure_getifaddrs_is_loaded()) { errno = ENOTSUP; return -1; } #endif #if HAVE_GETIFADDRS || TARGET_ANDROID struct ifaddrs* head; // Pointer to block allocated by getifaddrs(). struct ifaddrs* ifaddrsEntry; IpAddressInfo *ai; int count = 0; // Count of entries returned by getifaddrs(). int ip4count = 0; // Total number of IPv4 addresses. int ip6count = 0; // Total number of IPv6 addresses. int ifcount = 0; // Total number of unique network interface. int index; int socketfd = -1; NetworkInterfaceInfo *nii; if (getifaddrs(&head) == -1) { assert(errno != 0); return -1; } ifaddrsEntry = head; while (ifaddrsEntry != NULL) { count ++; if (ifaddrsEntry->ifa_addr != NULL && ifaddrsEntry->ifa_addr->sa_family == AF_INET) { ip4count++; } else if (ifaddrsEntry->ifa_addr != NULL && ifaddrsEntry->ifa_addr->sa_family == AF_INET6) { ip6count++; } ifaddrsEntry = ifaddrsEntry->ifa_next; } // Allocate estimated space. It can be little bit more than we need. // To save allocation need for separate free() we will allocate one memory chunk // where we first write out NetworkInterfaceInfo entries immediately followed by // IpAddressInfo list. void * memoryBlock = calloc((size_t)count, sizeof(NetworkInterfaceInfo)); if (memoryBlock == NULL) { errno = ENOMEM; return -1; } // Reset head pointers again. ifaddrsEntry = head; *interfaceList = nii = (NetworkInterfaceInfo*)memoryBlock; // address of first IpAddressInfo after all NetworkInterfaceInfo entries. *addressList = ai = (IpAddressInfo*)(nii + (count - ip4count - ip6count)); while (ifaddrsEntry != NULL) { //current = NULL; nii = NULL; uint ifindex = if_nametoindex(ifaddrsEntry->ifa_name); for (index = 0; index < (int)ifcount; index ++) { if (((NetworkInterfaceInfo*)memoryBlock)[index].InterfaceIndex == ifindex) { nii = &((NetworkInterfaceInfo*)memoryBlock)[index]; break; } } if (nii == NULL) { // We git new interface. nii = &((NetworkInterfaceInfo*)memoryBlock)[ifcount++]; memcpy(nii->Name, ifaddrsEntry->ifa_name, sizeof(nii->Name)); nii->InterfaceIndex = if_nametoindex(ifaddrsEntry->ifa_name); nii->Speed = -1; nii->HardwareType = NetworkInterfaceType_Unknown; // Get operational state and multicast support. if ((ifaddrsEntry->ifa_flags & (IFF_MULTICAST|IFF_ALLMULTI)) != 0) { nii->SupportsMulticast = 1; } // OperationalState returns whether the interface can transmit data packets. // The administrator must have enabled the interface (IFF_UP), and the cable must be plugged in (IFF_RUNNING). nii->OperationalState = ((ifaddrsEntry->ifa_flags & (IFF_UP|IFF_RUNNING)) == (IFF_UP|IFF_RUNNING)) ? OperationalStatus_Up : OperationalStatus_Down; } if (ifaddrsEntry->ifa_addr == NULL) { // Interface with no addresses. Not even link layer. (like PPP or tunnel) ifaddrsEntry = ifaddrsEntry->ifa_next; continue; } else if (ifaddrsEntry->ifa_addr->sa_family == AF_INET) { ai->InterfaceIndex = ifindex; ai->NumAddressBytes = NUM_BYTES_IN_IPV4_ADDRESS; memcpy(ai->AddressBytes, &((struct sockaddr_in*)ifaddrsEntry->ifa_addr)->sin_addr, NUM_BYTES_IN_IPV4_ADDRESS); ai->PrefixLength = mask2prefix((uint8_t*)&((struct sockaddr_in*)ifaddrsEntry->ifa_netmask)->sin_addr, NUM_BYTES_IN_IPV4_ADDRESS); ai++; } else if (ifaddrsEntry->ifa_addr->sa_family == AF_INET6) { ai->InterfaceIndex = ifindex; ai->NumAddressBytes = NUM_BYTES_IN_IPV6_ADDRESS; memcpy(ai->AddressBytes, &((struct sockaddr_in6*)ifaddrsEntry->ifa_addr)->sin6_addr, NUM_BYTES_IN_IPV6_ADDRESS); ai->PrefixLength = mask2prefix((uint8_t*)&(((struct sockaddr_in6*)ifaddrsEntry->ifa_netmask)->sin6_addr), NUM_BYTES_IN_IPV6_ADDRESS); ai++; } #if defined(AF_LINK) else if (ifaddrsEntry->ifa_addr->sa_family == AF_LINK) { struct sockaddr_dl* sadl = (struct sockaddr_dl*)ifaddrsEntry->ifa_addr; nii->HardwareType = MapHardwareType(sadl->sdl_type); nii->NumAddressBytes = sadl->sdl_alen; memcpy_s(&nii->AddressBytes, sizeof_member(NetworkInterfaceInfo, AddressBytes), (uint8_t*)LLADDR(sadl), sadl->sdl_alen); } #endif #if defined(AF_PACKET) else if (ifaddrsEntry->ifa_addr->sa_family == AF_PACKET) { struct sockaddr_ll* sall = (struct sockaddr_ll*)ifaddrsEntry->ifa_addr; if (sall->sll_halen > sizeof(sall->sll_addr)) { // sockaddr_ll->sll_addr has a maximum capacity of 8 bytes (unsigned char sll_addr[8]) // so if we get a address length greater than that, we truncate it to 8 bytes. // This is following the kernel docs where they always treat physical addresses with a maximum of 8 bytes. // However in WSL we hit an issue where sll_halen was 16 bytes so the memcpy_s below would fail because it was greater. sall->sll_halen = sizeof(sall->sll_addr); } nii->HardwareType = MapHardwareType(sall->sll_hatype); nii->NumAddressBytes = sall->sll_halen; memcpy_s(&nii->AddressBytes, sizeof_member(NetworkInterfaceInfo, AddressBytes), &sall->sll_addr, sall->sll_halen); struct ifreq ifr; strncpy(ifr.ifr_name, nii->Name, sizeof(ifr.ifr_name)); ifr.ifr_name[sizeof(ifr.ifr_name) - 1] = '\0'; if (socketfd == -1) { socketfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP); } if (socketfd > -1) { if (ioctl(socketfd, SIOCGIFMTU, &ifr) == 0) { nii->Mtu = ifr.ifr_mtu; } #if HAVE_ETHTOOL_H // Do not even try to get speed on certain interface types. if (nii->HardwareType != NetworkInterfaceType_Unknown && nii->HardwareType != NetworkInterfaceType_Tunnel && nii->HardwareType != NetworkInterfaceType_Loopback) { struct ethtool_cmd ecmd; ecmd.cmd = ETHTOOL_GLINK; ifr.ifr_data = (char *) &ecmd; if (ioctl(socketfd, SIOCETHTOOL, &ifr) == 0) { if (!ecmd.supported) { // Mark Interface as down if we succeeded getting link status and it is down. nii->OperationalState = OperationalStatus_Down; } // Try to get link speed if link is up. // Use older ETHTOOL_GSET instead of ETHTOOL_GLINKSETTINGS to support RH6 ecmd.cmd = ETHTOOL_GSET; if (ioctl(socketfd, SIOCETHTOOL, &ifr) == 0) { #ifdef TARGET_ANDROID nii->Speed = (int64_t)ecmd.speed; #else nii->Speed = (int64_t)ethtool_cmd_speed(&ecmd); #endif if (nii->Speed > 0) { // If we did not get -1 nii->Speed *= 1000000; // convert from mbits } } } } #endif } } #endif ifaddrsEntry = ifaddrsEntry->ifa_next; } *interfaceCount = ifcount; *addressCount = ip4count + ip6count; // Cleanup. freeifaddrs(head); if (socketfd != -1) { close(socketfd); } return 0; #else // Not supported. Also, prevent a compiler error because parameters are unused (void)interfaceCount; (void)interfaceList; (void)addressCount; (void)addressList; errno = ENOTSUP; return -1; #endif } #if HAVE_RT_MSGHDR && defined(CTL_NET) int32_t SystemNative_EnumerateGatewayAddressesForInterface(void* context, uint32_t interfaceIndex, GatewayAddressFound onGatewayFound) { static struct in6_addr anyaddr = IN6ADDR_ANY_INIT; int routeDumpName[] = {CTL_NET, AF_ROUTE, 0, 0, NET_RT_DUMP, 0}; size_t byteCount; if (sysctl(routeDumpName, 6, NULL, &byteCount, NULL, 0) != 0) { return -1; } uint8_t* buffer = malloc(byteCount); if (buffer == NULL) { errno = ENOMEM; return -1; } while (sysctl(routeDumpName, 6, buffer, &byteCount, NULL, 0) != 0) { if (errno != ENOMEM) { return -1; } // If buffer is not big enough double size to avoid calling sysctl again // as byteCount only gets estimated size when passed buffer is NULL. // This only happens if routing table grows between first and second call. size_t tmpEstimatedSize; if (!multiply_s(byteCount, (size_t)2, &tmpEstimatedSize)) { errno = ENOMEM; return -1; } byteCount = tmpEstimatedSize; free(buffer); buffer = malloc(byteCount); if (buffer == NULL) { errno = ENOMEM; return -1; } } struct rt_msghdr* hdr; for (size_t i = 0; i < byteCount; i += hdr->rtm_msglen) { hdr = (struct rt_msghdr*)&buffer[i]; int flags = hdr->rtm_flags; int isGateway = flags & RTF_GATEWAY; int gatewayPresent = hdr->rtm_addrs & RTA_GATEWAY; if (isGateway && gatewayPresent && ((int)interfaceIndex == -1 || interfaceIndex == hdr->rtm_index)) { IpAddressInfo iai; struct sockaddr_storage* sock = (struct sockaddr_storage*)(hdr + 1); memset(&iai, 0, sizeof(IpAddressInfo)); iai.InterfaceIndex = hdr->rtm_index; if (sock->ss_family == AF_INET) { iai.NumAddressBytes = NUM_BYTES_IN_IPV4_ADDRESS; struct sockaddr_in* sain = (struct sockaddr_in*)sock; if (sain->sin_addr.s_addr != 0) { // filter out normal routes. continue; } sain = sain + 1; // Skip over the first sockaddr, the destination address. The second is the gateway. memcpy_s(iai.AddressBytes, sizeof_member(IpAddressInfo, AddressBytes), &sain->sin_addr.s_addr, sizeof(sain->sin_addr.s_addr)); } else if (sock->ss_family == AF_INET6) { struct sockaddr_in6* sain6 = (struct sockaddr_in6*)sock; iai.NumAddressBytes = NUM_BYTES_IN_IPV6_ADDRESS; if (memcmp(&anyaddr, &sain6->sin6_addr, sizeof(sain6->sin6_addr)) != 0) { // filter out normal routes. continue; } sain6 = sain6 + 1; // Skip over the first sockaddr, the destination address. The second is the gateway. if ((sain6->sin6_addr.__u6_addr.__u6_addr16[0] & htons(0xfe80)) == htons(0xfe80)) { // clear embedded if index. sain6->sin6_addr.__u6_addr.__u6_addr16[1] = 0; } memcpy_s(iai.AddressBytes, sizeof_member(IpAddressInfo, AddressBytes), &sain6->sin6_addr, sizeof(sain6->sin6_addr)); } else { // Ignore other address families. continue; } onGatewayFound(context, &iai); } } free(buffer); return 0; } #else int32_t SystemNative_EnumerateGatewayAddressesForInterface(void* context, uint32_t interfaceIndex, GatewayAddressFound onGatewayFound) { (void)context; (void)interfaceIndex; (void)onGatewayFound; errno = ENOTSUP; return -1; } #endif // HAVE_RT_MSGHDR
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include "pal_config.h" #include "pal_interfaceaddresses.h" #include "pal_maphardwaretype.h" #include "pal_utilities.h" #include "pal_safecrt.h" #include "pal_networking.h" #include <stdlib.h> #include <sys/types.h> #include <assert.h> #if HAVE_IFADDRS || HAVE_GETIFADDRS #include <ifaddrs.h> #endif #if !HAVE_GETIFADDRS && TARGET_ANDROID #include <dlfcn.h> #include <pthread.h> #endif #include <net/if.h> #include <netinet/in.h> #include <string.h> #include <sys/socket.h> #if HAVE_SYS_SYSCTL_H #include <sys/sysctl.h> #endif #if HAVE_SYS_IOCTL_H #include <sys/ioctl.h> #endif #if HAVE_ETHTOOL_H #include <linux/ethtool.h> #include <linux/sockios.h> #include <arpa/inet.h> #endif #if HAVE_NET_IFMEDIA_H #include <net/if_media.h> #elif HAVE_IOS_NET_IFMEDIA_H #include "ios/net/if_media.h" #endif #if defined(AF_PACKET) #include <sys/ioctl.h> #if HAVE_NETPACKET_PACKET_H #include <netpacket/packet.h> #else #include <linux/if_packet.h> #endif #elif defined(AF_LINK) #include <net/if_dl.h> #include <net/if_types.h> #else #error System must have AF_PACKET or AF_LINK. #endif #if HAVE_RT_MSGHDR #if HAVE_IOS_NET_ROUTE_H #include "ios/net/route.h" #else #include <net/route.h> #endif #endif // Convert mask to prefix length e.g. 255.255.255.0 -> 24 // mask parameter is pointer to buffer where address starts and length is // buffer length e.g. 4 for IPv4 and 16 for IPv6. // Code bellow counts consecutive number of 1 bits. static inline uint8_t mask2prefix(uint8_t* mask, int length) { uint8_t len = 0; uint8_t* end = mask + length; if (mask == NULL) { // If we did not get valid mask, assume host address. return (uint8_t)length * 8; } // Get whole bytes while ((mask < end) && (*mask == 0xff)) { len += 8; mask++; } // Get last incomplete byte if (mask < end) { while (*mask) { len++; *mask <<= 1; } } if (len == 0 && length == 4) { len = 32; } return len; } #if !HAVE_IFADDRS && TARGET_ANDROID // This structure is exactly the same as struct ifaddrs defined in ifaddrs.h but since the header // might not be available (e.g., in bionics used in Android before API 24) we need to mirror it here // so that we can dynamically load the getifaddrs function and use it. struct ifaddrs { struct ifaddrs *ifa_next; char *ifa_name; unsigned int ifa_flags; struct sockaddr *ifa_addr; struct sockaddr *ifa_netmask; union { struct sockaddr *ifu_broadaddr; struct sockaddr *ifu_dstaddr; } ifa_ifu; void *ifa_data; }; #endif #if !HAVE_GETIFADDRS && TARGET_ANDROID // Try to load the getifaddrs and freeifaddrs functions manually. // This workaround is necessary on Android prior to API 24 and it can be removed once // we drop support for earlier Android versions. static int (*getifaddrs)(struct ifaddrs**) = NULL; static void (*freeifaddrs)(struct ifaddrs*) = NULL; static void try_loading_getifaddrs() { void *libc = dlopen("libc.so", RTLD_NOW); if (libc) { getifaddrs = (int (*)(struct ifaddrs**)) dlsym(libc, "getifaddrs"); freeifaddrs = (void (*)(struct ifaddrs*)) dlsym(libc, "freeifaddrs"); } } static bool ensure_getifaddrs_is_loaded() { static pthread_once_t getifaddrs_is_loaded = PTHREAD_ONCE_INIT; pthread_once(&getifaddrs_is_loaded, try_loading_getifaddrs); return getifaddrs != NULL && freeifaddrs != NULL; } #endif int32_t SystemNative_EnumerateInterfaceAddresses(void* context, IPv4AddressFound onIpv4Found, IPv6AddressFound onIpv6Found, LinkLayerAddressFound onLinkLayerFound) { #if !HAVE_GETIFADDRS && TARGET_ANDROID // Workaround for Android API < 24 if (!ensure_getifaddrs_is_loaded()) { errno = ENOTSUP; return -1; } #endif #if HAVE_GETIFADDRS || TARGET_ANDROID struct ifaddrs* headAddr; if (getifaddrs(&headAddr) == -1) { return -1; } for (struct ifaddrs* current = headAddr; current != NULL; current = current->ifa_next) { if (current->ifa_addr == NULL) { continue; } uint32_t interfaceIndex = if_nametoindex(current->ifa_name); // ifa_name may be an aliased interface name. // Use if_indextoname to map back to the true device name. char actualName[IF_NAMESIZE]; char* result = if_indextoname(interfaceIndex, actualName); if (result == NULL) { freeifaddrs(headAddr); return -1; } assert(result == actualName); int family = current->ifa_addr->sa_family; if (family == AF_INET) { if (onIpv4Found != NULL) { // IP Address IpAddressInfo iai; memset(&iai, 0, sizeof(IpAddressInfo)); iai.InterfaceIndex = interfaceIndex; iai.NumAddressBytes = NUM_BYTES_IN_IPV4_ADDRESS; struct sockaddr_in* sain = (struct sockaddr_in*)current->ifa_addr; memcpy_s(iai.AddressBytes, sizeof_member(IpAddressInfo, AddressBytes), &sain->sin_addr.s_addr, sizeof(sain->sin_addr.s_addr)); struct sockaddr_in* mask_sain = (struct sockaddr_in*)current->ifa_netmask; // ifa_netmask can be NULL according to documentation, probably P2P interfaces. iai.PrefixLength = mask_sain != NULL ? mask2prefix((uint8_t*)&mask_sain->sin_addr.s_addr, NUM_BYTES_IN_IPV4_ADDRESS) : NUM_BYTES_IN_IPV4_ADDRESS * 8; onIpv4Found(context, actualName, &iai); } } else if (family == AF_INET6) { if (onIpv6Found != NULL) { IpAddressInfo iai; memset(&iai, 0, sizeof(IpAddressInfo)); iai.InterfaceIndex = interfaceIndex; iai.NumAddressBytes = NUM_BYTES_IN_IPV6_ADDRESS; struct sockaddr_in6* sain6 = (struct sockaddr_in6*)current->ifa_addr; memcpy_s(iai.AddressBytes, sizeof_member(IpAddressInfo, AddressBytes), sain6->sin6_addr.s6_addr, sizeof(sain6->sin6_addr.s6_addr)); uint32_t scopeId = sain6->sin6_scope_id; struct sockaddr_in6* mask_sain6 = (struct sockaddr_in6*)current->ifa_netmask; iai.PrefixLength = mask_sain6 != NULL ? mask2prefix((uint8_t*)&mask_sain6->sin6_addr.s6_addr, NUM_BYTES_IN_IPV6_ADDRESS) : NUM_BYTES_IN_IPV6_ADDRESS * 8; onIpv6Found(context, actualName, &iai, &scopeId); } } #if defined(AF_PACKET) else if (family == AF_PACKET) { if (onLinkLayerFound != NULL) { struct sockaddr_ll* sall = (struct sockaddr_ll*)current->ifa_addr; if (sall->sll_halen > sizeof(sall->sll_addr)) { // sockaddr_ll->sll_addr has a maximum capacity of 8 bytes (unsigned char sll_addr[8]) // so if we get a address length greater than that, we truncate it to 8 bytes. // This is following the kernel docs where they always treat physical addresses with a maximum of 8 bytes. // However in WSL we hit an issue where sll_halen was 16 bytes so the memcpy_s below would fail because it was greater. sall->sll_halen = sizeof(sall->sll_addr); } LinkLayerAddressInfo lla; memset(&lla, 0, sizeof(LinkLayerAddressInfo)); lla.InterfaceIndex = interfaceIndex; lla.NumAddressBytes = sall->sll_halen; lla.HardwareType = MapHardwareType(sall->sll_hatype); memcpy_s(&lla.AddressBytes, sizeof_member(LinkLayerAddressInfo, AddressBytes), &sall->sll_addr, sall->sll_halen); onLinkLayerFound(context, current->ifa_name, &lla); } } #elif defined(AF_LINK) else if (family == AF_LINK) { if (onLinkLayerFound != NULL) { struct sockaddr_dl* sadl = (struct sockaddr_dl*)current->ifa_addr; LinkLayerAddressInfo lla; memset(&lla, 0, sizeof(LinkLayerAddressInfo)); lla.InterfaceIndex = interfaceIndex; lla.NumAddressBytes = sadl->sdl_alen; lla.HardwareType = MapHardwareType(sadl->sdl_type); #if HAVE_NET_IFMEDIA_H || HAVE_IOS_NET_IFMEDIA_H if (lla.HardwareType == NetworkInterfaceType_Ethernet) { // WI-FI and Ethernet have same address type so we can try to distinguish more int fd = socket(AF_INET, SOCK_DGRAM, 0); if (fd >= 0) { struct ifmediareq ifmr; memset(&ifmr, 0, sizeof(ifmr)); strncpy(ifmr.ifm_name, actualName, sizeof(ifmr.ifm_name)); if ((ioctl(fd, SIOCGIFMEDIA, (caddr_t)&ifmr) == 0) && (IFM_TYPE(ifmr.ifm_current) == IFM_IEEE80211)) { lla.HardwareType = NetworkInterfaceType_Wireless80211; } close(fd); } } #endif memcpy_s(&lla.AddressBytes, sizeof_member(LinkLayerAddressInfo, AddressBytes), (uint8_t*)LLADDR(sadl), sadl->sdl_alen); onLinkLayerFound(context, current->ifa_name, &lla); } } #endif } freeifaddrs(headAddr); return 0; #else // Not supported. Also, prevent a compiler error because parameters are unused (void)context; (void)onIpv4Found; (void)onIpv6Found; (void)onLinkLayerFound; errno = ENOTSUP; return -1; #endif } int32_t SystemNative_GetNetworkInterfaces(int32_t * interfaceCount, NetworkInterfaceInfo **interfaceList, int32_t * addressCount, IpAddressInfo **addressList ) { #if !HAVE_GETIFADDRS && TARGET_ANDROID // Workaround for Android API < 24 if (!ensure_getifaddrs_is_loaded()) { errno = ENOTSUP; return -1; } #endif #if HAVE_GETIFADDRS || TARGET_ANDROID struct ifaddrs* head; // Pointer to block allocated by getifaddrs(). struct ifaddrs* ifaddrsEntry; IpAddressInfo *ai; int count = 0; // Count of entries returned by getifaddrs(). int ip4count = 0; // Total number of IPv4 addresses. int ip6count = 0; // Total number of IPv6 addresses. int ifcount = 0; // Total number of unique network interface. int index; int socketfd = -1; NetworkInterfaceInfo *nii; if (getifaddrs(&head) == -1) { assert(errno != 0); return -1; } ifaddrsEntry = head; while (ifaddrsEntry != NULL) { count ++; if (ifaddrsEntry->ifa_addr != NULL && ifaddrsEntry->ifa_addr->sa_family == AF_INET) { ip4count++; } else if (ifaddrsEntry->ifa_addr != NULL && ifaddrsEntry->ifa_addr->sa_family == AF_INET6) { ip6count++; } ifaddrsEntry = ifaddrsEntry->ifa_next; } // Allocate estimated space. It can be little bit more than we need. // To save allocation need for separate free() we will allocate one memory chunk // where we first write out NetworkInterfaceInfo entries immediately followed by // IpAddressInfo list. void * memoryBlock = calloc((size_t)count, sizeof(NetworkInterfaceInfo)); if (memoryBlock == NULL) { errno = ENOMEM; return -1; } // Reset head pointers again. ifaddrsEntry = head; *interfaceList = nii = (NetworkInterfaceInfo*)memoryBlock; // address of first IpAddressInfo after all NetworkInterfaceInfo entries. *addressList = ai = (IpAddressInfo*)(nii + (count - ip4count - ip6count)); while (ifaddrsEntry != NULL) { //current = NULL; nii = NULL; uint ifindex = if_nametoindex(ifaddrsEntry->ifa_name); for (index = 0; index < (int)ifcount; index ++) { if (((NetworkInterfaceInfo*)memoryBlock)[index].InterfaceIndex == ifindex) { nii = &((NetworkInterfaceInfo*)memoryBlock)[index]; break; } } if (nii == NULL) { // We git new interface. nii = &((NetworkInterfaceInfo*)memoryBlock)[ifcount++]; memcpy(nii->Name, ifaddrsEntry->ifa_name, sizeof(nii->Name)); nii->InterfaceIndex = if_nametoindex(ifaddrsEntry->ifa_name); nii->Speed = -1; nii->HardwareType = NetworkInterfaceType_Unknown; // Get operational state and multicast support. if ((ifaddrsEntry->ifa_flags & (IFF_MULTICAST|IFF_ALLMULTI)) != 0) { nii->SupportsMulticast = 1; } // OperationalState returns whether the interface can transmit data packets. // The administrator must have enabled the interface (IFF_UP), and the cable must be plugged in (IFF_RUNNING). nii->OperationalState = ((ifaddrsEntry->ifa_flags & (IFF_UP|IFF_RUNNING)) == (IFF_UP|IFF_RUNNING)) ? OperationalStatus_Up : OperationalStatus_Down; } if (ifaddrsEntry->ifa_addr == NULL) { // Interface with no addresses. Not even link layer. (like PPP or tunnel) ifaddrsEntry = ifaddrsEntry->ifa_next; continue; } else if (ifaddrsEntry->ifa_addr->sa_family == AF_INET) { ai->InterfaceIndex = ifindex; ai->NumAddressBytes = NUM_BYTES_IN_IPV4_ADDRESS; memcpy(ai->AddressBytes, &((struct sockaddr_in*)ifaddrsEntry->ifa_addr)->sin_addr, NUM_BYTES_IN_IPV4_ADDRESS); ai->PrefixLength = mask2prefix((uint8_t*)&((struct sockaddr_in*)ifaddrsEntry->ifa_netmask)->sin_addr, NUM_BYTES_IN_IPV4_ADDRESS); ai++; } else if (ifaddrsEntry->ifa_addr->sa_family == AF_INET6) { ai->InterfaceIndex = ifindex; ai->NumAddressBytes = NUM_BYTES_IN_IPV6_ADDRESS; memcpy(ai->AddressBytes, &((struct sockaddr_in6*)ifaddrsEntry->ifa_addr)->sin6_addr, NUM_BYTES_IN_IPV6_ADDRESS); ai->PrefixLength = mask2prefix((uint8_t*)&(((struct sockaddr_in6*)ifaddrsEntry->ifa_netmask)->sin6_addr), NUM_BYTES_IN_IPV6_ADDRESS); ai++; } #if defined(AF_LINK) else if (ifaddrsEntry->ifa_addr->sa_family == AF_LINK) { struct sockaddr_dl* sadl = (struct sockaddr_dl*)ifaddrsEntry->ifa_addr; nii->HardwareType = MapHardwareType(sadl->sdl_type); nii->NumAddressBytes = sadl->sdl_alen; memcpy_s(&nii->AddressBytes, sizeof_member(NetworkInterfaceInfo, AddressBytes), (uint8_t*)LLADDR(sadl), sadl->sdl_alen); } #endif #if defined(AF_PACKET) else if (ifaddrsEntry->ifa_addr->sa_family == AF_PACKET) { struct sockaddr_ll* sall = (struct sockaddr_ll*)ifaddrsEntry->ifa_addr; if (sall->sll_halen > sizeof(sall->sll_addr)) { // sockaddr_ll->sll_addr has a maximum capacity of 8 bytes (unsigned char sll_addr[8]) // so if we get a address length greater than that, we truncate it to 8 bytes. // This is following the kernel docs where they always treat physical addresses with a maximum of 8 bytes. // However in WSL we hit an issue where sll_halen was 16 bytes so the memcpy_s below would fail because it was greater. sall->sll_halen = sizeof(sall->sll_addr); } nii->HardwareType = MapHardwareType(sall->sll_hatype); nii->NumAddressBytes = sall->sll_halen; memcpy_s(&nii->AddressBytes, sizeof_member(NetworkInterfaceInfo, AddressBytes), &sall->sll_addr, sall->sll_halen); struct ifreq ifr; strncpy(ifr.ifr_name, nii->Name, sizeof(ifr.ifr_name)); ifr.ifr_name[sizeof(ifr.ifr_name) - 1] = '\0'; if (socketfd == -1) { socketfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP); } if (socketfd > -1) { if (ioctl(socketfd, SIOCGIFMTU, &ifr) == 0) { nii->Mtu = ifr.ifr_mtu; } #if HAVE_ETHTOOL_H // Do not even try to get speed on certain interface types. if (nii->HardwareType != NetworkInterfaceType_Unknown && nii->HardwareType != NetworkInterfaceType_Tunnel && nii->HardwareType != NetworkInterfaceType_Loopback) { struct ethtool_cmd ecmd; ecmd.cmd = ETHTOOL_GLINK; ifr.ifr_data = (char *) &ecmd; if (ioctl(socketfd, SIOCETHTOOL, &ifr) == 0) { if (!ecmd.supported) { // Mark Interface as down if we succeeded getting link status and it is down. nii->OperationalState = OperationalStatus_Down; } // Try to get link speed if link is up. // Use older ETHTOOL_GSET instead of ETHTOOL_GLINKSETTINGS to support RH6 ecmd.cmd = ETHTOOL_GSET; if (ioctl(socketfd, SIOCETHTOOL, &ifr) == 0) { #ifdef TARGET_ANDROID nii->Speed = (int64_t)ecmd.speed; #else nii->Speed = (int64_t)ethtool_cmd_speed(&ecmd); #endif if (nii->Speed > 0) { // If we did not get -1 nii->Speed *= 1000000; // convert from mbits } } } } #endif } } #endif ifaddrsEntry = ifaddrsEntry->ifa_next; } *interfaceCount = ifcount; *addressCount = ip4count + ip6count; // Cleanup. freeifaddrs(head); if (socketfd != -1) { close(socketfd); } return 0; #else // Not supported. Also, prevent a compiler error because parameters are unused (void)interfaceCount; (void)interfaceList; (void)addressCount; (void)addressList; errno = ENOTSUP; return -1; #endif } #if HAVE_RT_MSGHDR && defined(CTL_NET) int32_t SystemNative_EnumerateGatewayAddressesForInterface(void* context, uint32_t interfaceIndex, GatewayAddressFound onGatewayFound) { static struct in6_addr anyaddr = IN6ADDR_ANY_INIT; int routeDumpName[] = {CTL_NET, AF_ROUTE, 0, 0, NET_RT_DUMP, 0}; size_t byteCount; if (sysctl(routeDumpName, 6, NULL, &byteCount, NULL, 0) != 0) { return -1; } uint8_t* buffer = malloc(byteCount); if (buffer == NULL) { errno = ENOMEM; return -1; } while (sysctl(routeDumpName, 6, buffer, &byteCount, NULL, 0) != 0) { if (errno != ENOMEM) { return -1; } // If buffer is not big enough double size to avoid calling sysctl again // as byteCount only gets estimated size when passed buffer is NULL. // This only happens if routing table grows between first and second call. size_t tmpEstimatedSize; if (!multiply_s(byteCount, (size_t)2, &tmpEstimatedSize)) { errno = ENOMEM; return -1; } byteCount = tmpEstimatedSize; free(buffer); buffer = malloc(byteCount); if (buffer == NULL) { errno = ENOMEM; return -1; } } struct rt_msghdr* hdr; for (size_t i = 0; i < byteCount; i += hdr->rtm_msglen) { hdr = (struct rt_msghdr*)&buffer[i]; int flags = hdr->rtm_flags; int isGateway = flags & RTF_GATEWAY; int gatewayPresent = hdr->rtm_addrs & RTA_GATEWAY; if (isGateway && gatewayPresent && ((int)interfaceIndex == -1 || interfaceIndex == hdr->rtm_index)) { IpAddressInfo iai; struct sockaddr_storage* sock = (struct sockaddr_storage*)(hdr + 1); memset(&iai, 0, sizeof(IpAddressInfo)); iai.InterfaceIndex = hdr->rtm_index; if (sock->ss_family == AF_INET) { iai.NumAddressBytes = NUM_BYTES_IN_IPV4_ADDRESS; struct sockaddr_in* sain = (struct sockaddr_in*)sock; if (sain->sin_addr.s_addr != 0) { // filter out normal routes. continue; } sain = sain + 1; // Skip over the first sockaddr, the destination address. The second is the gateway. memcpy_s(iai.AddressBytes, sizeof_member(IpAddressInfo, AddressBytes), &sain->sin_addr.s_addr, sizeof(sain->sin_addr.s_addr)); } else if (sock->ss_family == AF_INET6) { struct sockaddr_in6* sain6 = (struct sockaddr_in6*)sock; iai.NumAddressBytes = NUM_BYTES_IN_IPV6_ADDRESS; if (memcmp(&anyaddr, &sain6->sin6_addr, sizeof(sain6->sin6_addr)) != 0) { // filter out normal routes. continue; } sain6 = sain6 + 1; // Skip over the first sockaddr, the destination address. The second is the gateway. if ((sain6->sin6_addr.__u6_addr.__u6_addr16[0] & htons(0xfe80)) == htons(0xfe80)) { // clear embedded if index. sain6->sin6_addr.__u6_addr.__u6_addr16[1] = 0; } memcpy_s(iai.AddressBytes, sizeof_member(IpAddressInfo, AddressBytes), &sain6->sin6_addr, sizeof(sain6->sin6_addr)); } else { // Ignore other address families. continue; } onGatewayFound(context, &iai); } } free(buffer); return 0; } #else int32_t SystemNative_EnumerateGatewayAddressesForInterface(void* context, uint32_t interfaceIndex, GatewayAddressFound onGatewayFound) { (void)context; (void)interfaceIndex; (void)onGatewayFound; errno = ENOTSUP; return -1; } #endif // HAVE_RT_MSGHDR
-1
dotnet/runtime
66,452
[mono] Stop setting time_date_stamp field in MonoImage
We never read that field in the runtime and it was causing unnecessary disk IO during startup (5ms on my iOS device). It was also never set on Windows already.
akoeplinger
2022-03-10T15:49:37Z
2022-03-10T21:47:58Z
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
d2826308964e4ee4496d6884e09811e1f709005e
[mono] Stop setting time_date_stamp field in MonoImage. We never read that field in the runtime and it was causing unnecessary disk IO during startup (5ms on my iOS device). It was also never set on Windows already.
./src/coreclr/vm/debuginfostore.h
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // DebugInfoStore #ifndef __DebugInfoStore_H_ #define __DebugInfoStore_H_ // Debugging information is described in CorInfo.h #include "corinfo.h" #include "nibblestream.h" //----------------------------------------------------------------------------- // Information to request Debug info. //----------------------------------------------------------------------------- class DebugInfoRequest { public: #ifdef _DEBUG // Must initialize via an Init*() function, not just a ctor. // In debug, ctor sets fields to values that will cause asserts if not initialized. DebugInfoRequest() { SUPPORTS_DAC; m_pMD = NULL; m_addrStart = NULL; } #endif // Eventually we may have many ways to initialize a request. // Init given a method desc and starting address for a native code blob. void InitFromStartingAddr(MethodDesc * pDesc, PCODE addrCode); MethodDesc * GetMD() const { LIMITED_METHOD_DAC_CONTRACT; return m_pMD; } PCODE GetStartAddress() const { LIMITED_METHOD_DAC_CONTRACT; return m_addrStart; } protected: MethodDesc * m_pMD; PCODE m_addrStart; }; //----------------------------------------------------------------------------- // A Debug-Info Store abstracts the storage of debugging information //----------------------------------------------------------------------------- // We pass the IDS an allocator which it uses to hand the data back. // pData is data the allocator may use for 'new'. // Eg, perhaps we have multiple heaps (eg, loader-heaps per appdomain). typedef BYTE* (*FP_IDS_NEW)(void * pData, size_t cBytes); //----------------------------------------------------------------------------- // Utility routines used for compression // Note that the compression is just an implementation detail of the stores, // and so these are just utility routines exposed to the stores. //----------------------------------------------------------------------------- class CompressDebugInfo { public: // Compress incoming data and write it to the provided NibbleWriter. static void CompressBoundaries( IN ULONG32 cMap, IN ICorDebugInfo::OffsetMapping *pMap, IN OUT NibbleWriter * pWriter ); static void CompressVars( IN ULONG32 cVars, IN ICorDebugInfo::NativeVarInfo *vars, IN OUT NibbleWriter * pBuffer ); // Stores the result into SBuffer (used by NGen), or in LoaderHeap (used by JIT) static PTR_BYTE CompressBoundariesAndVars( IN ICorDebugInfo::OffsetMapping * pOffsetMapping, IN ULONG iOffsetMapping, IN ICorDebugInfo::NativeVarInfo * pNativeVarInfo, IN ULONG iNativeVarInfo, IN PatchpointInfo * patchpointInfo, IN OUT SBuffer * pDebugInfoBuffer, IN LoaderHeap * pLoaderHeap ); public: // Uncompress data supplied by Compress functions. static void RestoreBoundariesAndVars( IN FP_IDS_NEW fpNew, IN void * pNewData, IN PTR_BYTE pDebugInfo, OUT ULONG32 * pcMap, // number of entries in ppMap OUT ICorDebugInfo::OffsetMapping **ppMap, // pointer to newly allocated array OUT ULONG32 *pcVars, OUT ICorDebugInfo::NativeVarInfo **ppVars, BOOL hasFlagByte ); #ifdef FEATURE_ON_STACK_REPLACEMENT static PatchpointInfo * RestorePatchpointInfo( IN PTR_BYTE pDebugInfo ); #endif #ifdef DACCESS_COMPILE static void EnumMemoryRegions(CLRDataEnumMemoryFlags flags, PTR_BYTE pDebugInfo, BOOL hasFlagByte); #endif }; //----------------------------------------------------------------------------- // Debug-Info-manager. This is like a process-wide store. // There should be only 1 instance of this and it's process-wide. // It will delegate to sub-stores as needed //----------------------------------------------------------------------------- class DebugInfoManager { public: static BOOL GetBoundariesAndVars( const DebugInfoRequest & request, IN FP_IDS_NEW fpNew, IN void * pNewData, OUT ULONG32 * pcMap, OUT ICorDebugInfo::OffsetMapping ** ppMap, OUT ULONG32 * pcVars, OUT ICorDebugInfo::NativeVarInfo ** ppVars); #ifdef DACCESS_COMPILE static void EnumMemoryRegionsForMethodDebugInfo(CLRDataEnumMemoryFlags flags, MethodDesc * pMD); #endif }; #endif // __DebugInfoStore_H_
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // DebugInfoStore #ifndef __DebugInfoStore_H_ #define __DebugInfoStore_H_ // Debugging information is described in CorInfo.h #include "corinfo.h" #include "nibblestream.h" //----------------------------------------------------------------------------- // Information to request Debug info. //----------------------------------------------------------------------------- class DebugInfoRequest { public: #ifdef _DEBUG // Must initialize via an Init*() function, not just a ctor. // In debug, ctor sets fields to values that will cause asserts if not initialized. DebugInfoRequest() { SUPPORTS_DAC; m_pMD = NULL; m_addrStart = NULL; } #endif // Eventually we may have many ways to initialize a request. // Init given a method desc and starting address for a native code blob. void InitFromStartingAddr(MethodDesc * pDesc, PCODE addrCode); MethodDesc * GetMD() const { LIMITED_METHOD_DAC_CONTRACT; return m_pMD; } PCODE GetStartAddress() const { LIMITED_METHOD_DAC_CONTRACT; return m_addrStart; } protected: MethodDesc * m_pMD; PCODE m_addrStart; }; //----------------------------------------------------------------------------- // A Debug-Info Store abstracts the storage of debugging information //----------------------------------------------------------------------------- // We pass the IDS an allocator which it uses to hand the data back. // pData is data the allocator may use for 'new'. // Eg, perhaps we have multiple heaps (eg, loader-heaps per appdomain). typedef BYTE* (*FP_IDS_NEW)(void * pData, size_t cBytes); //----------------------------------------------------------------------------- // Utility routines used for compression // Note that the compression is just an implementation detail of the stores, // and so these are just utility routines exposed to the stores. //----------------------------------------------------------------------------- class CompressDebugInfo { public: // Compress incoming data and write it to the provided NibbleWriter. static void CompressBoundaries( IN ULONG32 cMap, IN ICorDebugInfo::OffsetMapping *pMap, IN OUT NibbleWriter * pWriter ); static void CompressVars( IN ULONG32 cVars, IN ICorDebugInfo::NativeVarInfo *vars, IN OUT NibbleWriter * pBuffer ); // Stores the result into SBuffer (used by NGen), or in LoaderHeap (used by JIT) static PTR_BYTE CompressBoundariesAndVars( IN ICorDebugInfo::OffsetMapping * pOffsetMapping, IN ULONG iOffsetMapping, IN ICorDebugInfo::NativeVarInfo * pNativeVarInfo, IN ULONG iNativeVarInfo, IN PatchpointInfo * patchpointInfo, IN OUT SBuffer * pDebugInfoBuffer, IN LoaderHeap * pLoaderHeap ); public: // Uncompress data supplied by Compress functions. static void RestoreBoundariesAndVars( IN FP_IDS_NEW fpNew, IN void * pNewData, IN PTR_BYTE pDebugInfo, OUT ULONG32 * pcMap, // number of entries in ppMap OUT ICorDebugInfo::OffsetMapping **ppMap, // pointer to newly allocated array OUT ULONG32 *pcVars, OUT ICorDebugInfo::NativeVarInfo **ppVars, BOOL hasFlagByte ); #ifdef FEATURE_ON_STACK_REPLACEMENT static PatchpointInfo * RestorePatchpointInfo( IN PTR_BYTE pDebugInfo ); #endif #ifdef DACCESS_COMPILE static void EnumMemoryRegions(CLRDataEnumMemoryFlags flags, PTR_BYTE pDebugInfo, BOOL hasFlagByte); #endif }; //----------------------------------------------------------------------------- // Debug-Info-manager. This is like a process-wide store. // There should be only 1 instance of this and it's process-wide. // It will delegate to sub-stores as needed //----------------------------------------------------------------------------- class DebugInfoManager { public: static BOOL GetBoundariesAndVars( const DebugInfoRequest & request, IN FP_IDS_NEW fpNew, IN void * pNewData, OUT ULONG32 * pcMap, OUT ICorDebugInfo::OffsetMapping ** ppMap, OUT ULONG32 * pcVars, OUT ICorDebugInfo::NativeVarInfo ** ppVars); #ifdef DACCESS_COMPILE static void EnumMemoryRegionsForMethodDebugInfo(CLRDataEnumMemoryFlags flags, MethodDesc * pMD); #endif }; #endif // __DebugInfoStore_H_
-1
dotnet/runtime
66,452
[mono] Stop setting time_date_stamp field in MonoImage
We never read that field in the runtime and it was causing unnecessary disk IO during startup (5ms on my iOS device). It was also never set on Windows already.
akoeplinger
2022-03-10T15:49:37Z
2022-03-10T21:47:58Z
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
d2826308964e4ee4496d6884e09811e1f709005e
[mono] Stop setting time_date_stamp field in MonoImage. We never read that field in the runtime and it was causing unnecessary disk IO during startup (5ms on my iOS device). It was also never set on Windows already.
./src/coreclr/pal/src/include/pal/unicodedata.h
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #ifndef _PAL_UNICODEDATA_H_ #define _PAL_UNICODEDATA_H_ #include "pal/palinternal.h" #ifdef __cplusplus extern "C" { #endif // __cplusplus #define UPPER_CASE 1 #define LOWER_CASE 2 typedef struct { WCHAR nUnicodeValue; WORD nFlag; WCHAR nOpposingCase; } UnicodeDataRec; extern CONST UnicodeDataRec UnicodeData[]; extern CONST UINT UNICODE_DATA_SIZE; #ifdef __cplusplus } #endif // __cplusplus #endif /* _UNICODE_DATA_H_ */
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #ifndef _PAL_UNICODEDATA_H_ #define _PAL_UNICODEDATA_H_ #include "pal/palinternal.h" #ifdef __cplusplus extern "C" { #endif // __cplusplus #define UPPER_CASE 1 #define LOWER_CASE 2 typedef struct { WCHAR nUnicodeValue; WORD nFlag; WCHAR nOpposingCase; } UnicodeDataRec; extern CONST UnicodeDataRec UnicodeData[]; extern CONST UINT UNICODE_DATA_SIZE; #ifdef __cplusplus } #endif // __cplusplus #endif /* _UNICODE_DATA_H_ */
-1
dotnet/runtime
66,452
[mono] Stop setting time_date_stamp field in MonoImage
We never read that field in the runtime and it was causing unnecessary disk IO during startup (5ms on my iOS device). It was also never set on Windows already.
akoeplinger
2022-03-10T15:49:37Z
2022-03-10T21:47:58Z
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
d2826308964e4ee4496d6884e09811e1f709005e
[mono] Stop setting time_date_stamp field in MonoImage. We never read that field in the runtime and it was causing unnecessary disk IO during startup (5ms on my iOS device). It was also never set on Windows already.
./src/coreclr/debug/inc/runtimeinfo.h
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #pragma once // The first byte of the index is the count of bytes typedef unsigned char SYMBOL_INDEX; #define RUNTIME_INFO_SIGNATURE "DotNetRuntimeInfo" // Make sure that if you update this structure // - You do so in a in a way that it is backwards compatible. For example, only tail append to this. // - Rev the version. // - Update the logic in ClrDataAccess::EnumMemCLRMainModuleInfo to ensure all needed state is in the dump. typedef struct _RuntimeInfo { const char Signature[18]; int Version; const SYMBOL_INDEX RuntimeModuleIndex[24]; const SYMBOL_INDEX DacModuleIndex[24]; const SYMBOL_INDEX DbiModuleIndex[24]; } RuntimeInfo; extern RuntimeInfo DotNetRuntimeInfo;
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #pragma once // The first byte of the index is the count of bytes typedef unsigned char SYMBOL_INDEX; #define RUNTIME_INFO_SIGNATURE "DotNetRuntimeInfo" // Make sure that if you update this structure // - You do so in a in a way that it is backwards compatible. For example, only tail append to this. // - Rev the version. // - Update the logic in ClrDataAccess::EnumMemCLRMainModuleInfo to ensure all needed state is in the dump. typedef struct _RuntimeInfo { const char Signature[18]; int Version; const SYMBOL_INDEX RuntimeModuleIndex[24]; const SYMBOL_INDEX DacModuleIndex[24]; const SYMBOL_INDEX DbiModuleIndex[24]; } RuntimeInfo; extern RuntimeInfo DotNetRuntimeInfo;
-1
dotnet/runtime
66,452
[mono] Stop setting time_date_stamp field in MonoImage
We never read that field in the runtime and it was causing unnecessary disk IO during startup (5ms on my iOS device). It was also never set on Windows already.
akoeplinger
2022-03-10T15:49:37Z
2022-03-10T21:47:58Z
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
d2826308964e4ee4496d6884e09811e1f709005e
[mono] Stop setting time_date_stamp field in MonoImage. We never read that field in the runtime and it was causing unnecessary disk IO during startup (5ms on my iOS device). It was also never set on Windows already.
./src/mono/mono/mini/mini-x86-gsharedvt.c
/** * \file * gsharedvt support code for x86 * * Authors: * Zoltan Varga <[email protected]> * * Copyright 2013 Xamarin, Inc (http://www.xamarin.com) * Licensed under the MIT license. See LICENSE file in the project root for full license information. */ #include "mini.h" #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED /* * GSHAREDVT */ gboolean mono_arch_gsharedvt_sig_supported (MonoMethodSignature *sig) { /* if (sig->ret && is_variable_size (sig->ret)) return FALSE; */ return TRUE; } /* * mono_arch_get_gsharedvt_call_info: * * Compute calling convention information for marshalling a call between NORMAL_SIG and GSHAREDVT_SIG. * If GSHAREDVT_IN is TRUE, then the caller calls using the signature NORMAL_SIG but the call is received by * a method with signature GSHAREDVT_SIG, otherwise its the other way around. */ gpointer mono_arch_get_gsharedvt_call_info (MonoMemoryManager *mem_manager, gpointer addr, MonoMethodSignature *normal_sig, MonoMethodSignature *gsharedvt_sig, gboolean gsharedvt_in, gint32 vcall_offset, gboolean calli) { GSharedVtCallInfo *info; CallInfo *caller_cinfo, *callee_cinfo; MonoMethodSignature *caller_sig, *callee_sig; int i, j; gboolean var_ret = FALSE; CallInfo *cinfo, *gcinfo; MonoMethodSignature *sig, *gsig; GPtrArray *map; if (gsharedvt_in) { caller_sig = normal_sig; callee_sig = gsharedvt_sig; caller_cinfo = mono_arch_get_call_info (NULL, caller_sig); callee_cinfo = mono_arch_get_call_info (NULL, callee_sig); } else { callee_sig = normal_sig; callee_cinfo = mono_arch_get_call_info (NULL, callee_sig); caller_sig = gsharedvt_sig; caller_cinfo = mono_arch_get_call_info (NULL, caller_sig); } /* * If GSHAREDVT_IN is true, this means we are transitioning from normal to gsharedvt code. The caller uses the * normal call signature, while the callee uses the gsharedvt signature. * If GSHAREDVT_IN is false, its the other way around. */ /* sig/cinfo describes the normal call, while gsig/gcinfo describes the gsharedvt call */ if (gsharedvt_in) { sig = caller_sig; gsig = callee_sig; cinfo = caller_cinfo; gcinfo = callee_cinfo; } else { sig = callee_sig; gsig = caller_sig; cinfo = callee_cinfo; gcinfo = caller_cinfo; } if (gcinfo->vtype_retaddr && gsig->ret && mini_is_gsharedvt_type (gsig->ret)) { /* * The return type is gsharedvt */ var_ret = TRUE; } /* * The stack looks like this: * <arguments> * <ret addr> * <saved ebp> * <call area> * We have to map the stack slots in <arguments> to the stack slots in <call area>. */ map = g_ptr_array_new (); if (cinfo->vtype_retaddr) { /* * Map ret arg. * This handles the case when the method returns a normal vtype, and when it returns a type arg, and its instantiated * with a vtype. */ g_ptr_array_add (map, GUINT_TO_POINTER (caller_cinfo->vret_arg_offset / sizeof (target_mgreg_t))); g_ptr_array_add (map, GUINT_TO_POINTER (callee_cinfo->vret_arg_offset / sizeof (target_mgreg_t))); } for (i = 0; i < cinfo->nargs; ++i) { ArgInfo *ainfo = &caller_cinfo->args [i]; ArgInfo *ainfo2 = &callee_cinfo->args [i]; int nslots; switch (ainfo->storage) { case ArgGSharedVt: if (ainfo2->storage == ArgOnStack) { nslots = callee_cinfo->args [i].nslots; if (!nslots) nslots = 1; g_ptr_array_add (map, GUINT_TO_POINTER ((ainfo->offset / sizeof (target_mgreg_t)) + (1 << 16) + (nslots << 18))); g_ptr_array_add (map, GUINT_TO_POINTER ((ainfo2->offset / sizeof (target_mgreg_t)))); } else { g_ptr_array_add (map, GUINT_TO_POINTER ((ainfo->offset / sizeof (target_mgreg_t)))); g_ptr_array_add (map, GUINT_TO_POINTER ((ainfo2->offset / sizeof (target_mgreg_t)))); } break; default: if (ainfo2->storage == ArgOnStack) { nslots = cinfo->args [i].nslots; if (!nslots) nslots = 1; for (j = 0; j < nslots; ++j) { g_ptr_array_add (map, GUINT_TO_POINTER ((ainfo->offset / sizeof (target_mgreg_t)) + j)); g_ptr_array_add (map, GUINT_TO_POINTER ((ainfo2->offset / sizeof (target_mgreg_t)) + j)); } } else { g_assert (ainfo2->storage == ArgGSharedVt); g_ptr_array_add (map, GUINT_TO_POINTER ((ainfo->offset / sizeof (target_mgreg_t)) + (2 << 16))); g_ptr_array_add (map, GUINT_TO_POINTER ((ainfo2->offset / sizeof (target_mgreg_t)))); } break; } } info = mono_mem_manager_alloc0 (mem_manager, sizeof (GSharedVtCallInfo) + (map->len * sizeof (int))); info->addr = addr; info->stack_usage = callee_cinfo->stack_usage; info->ret_marshal = GSHAREDVT_RET_NONE; info->gsharedvt_in = gsharedvt_in ? 1 : 0; info->vret_slot = -1; info->calli = calli ? 1 : 0; if (var_ret) info->vret_arg_slot = gcinfo->vret_arg_offset / sizeof (target_mgreg_t); else info->vret_arg_slot = -1; info->vcall_offset = vcall_offset; info->map_count = map->len / 2; for (i = 0; i < map->len; ++i) info->map [i] = GPOINTER_TO_UINT (g_ptr_array_index (map, i)); g_ptr_array_free (map, TRUE); /* Compute return value marshalling */ if (var_ret) { switch (cinfo->ret.storage) { case ArgInIReg: if (gsharedvt_in && !m_type_is_byref (sig->ret) && sig->ret->type == MONO_TYPE_I1) info->ret_marshal = GSHAREDVT_RET_I1; else if (gsharedvt_in && !m_type_is_byref (sig->ret) && (sig->ret->type == MONO_TYPE_U1 || sig->ret->type == MONO_TYPE_BOOLEAN)) info->ret_marshal = GSHAREDVT_RET_U1; else if (gsharedvt_in && !m_type_is_byref (sig->ret) && sig->ret->type == MONO_TYPE_I2) info->ret_marshal = GSHAREDVT_RET_I2; else if (gsharedvt_in && !m_type_is_byref (sig->ret) && (sig->ret->type == MONO_TYPE_U2 || sig->ret->type == MONO_TYPE_CHAR)) info->ret_marshal = GSHAREDVT_RET_U2; else if (cinfo->ret.is_pair) info->ret_marshal = GSHAREDVT_RET_IREGS; else info->ret_marshal = GSHAREDVT_RET_IREG; break; case ArgOnDoubleFpStack: info->ret_marshal = GSHAREDVT_RET_DOUBLE_FPSTACK; break; case ArgOnFloatFpStack: info->ret_marshal = GSHAREDVT_RET_FLOAT_FPSTACK; break; case ArgOnStack: /* The caller passes in a vtype ret arg as well */ g_assert (gcinfo->vtype_retaddr); /* Just have to pop the arg, as done by normal methods in their epilog */ info->ret_marshal = GSHAREDVT_RET_STACK_POP; break; default: g_assert_not_reached (); } } else if (gsharedvt_in && cinfo->vtype_retaddr) { info->ret_marshal = GSHAREDVT_RET_STACK_POP; } if (gsharedvt_in && var_ret && !caller_cinfo->vtype_retaddr) { /* Allocate stack space for the return value */ info->vret_slot = info->stack_usage / sizeof (target_mgreg_t); // FIXME: info->stack_usage += sizeof (target_mgreg_t) * 3; } info->stack_usage = ALIGN_TO (info->stack_usage, MONO_ARCH_FRAME_ALIGNMENT); g_free (caller_cinfo); g_free (callee_cinfo); return info; } #endif
/** * \file * gsharedvt support code for x86 * * Authors: * Zoltan Varga <[email protected]> * * Copyright 2013 Xamarin, Inc (http://www.xamarin.com) * Licensed under the MIT license. See LICENSE file in the project root for full license information. */ #include "mini.h" #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED /* * GSHAREDVT */ gboolean mono_arch_gsharedvt_sig_supported (MonoMethodSignature *sig) { /* if (sig->ret && is_variable_size (sig->ret)) return FALSE; */ return TRUE; } /* * mono_arch_get_gsharedvt_call_info: * * Compute calling convention information for marshalling a call between NORMAL_SIG and GSHAREDVT_SIG. * If GSHAREDVT_IN is TRUE, then the caller calls using the signature NORMAL_SIG but the call is received by * a method with signature GSHAREDVT_SIG, otherwise its the other way around. */ gpointer mono_arch_get_gsharedvt_call_info (MonoMemoryManager *mem_manager, gpointer addr, MonoMethodSignature *normal_sig, MonoMethodSignature *gsharedvt_sig, gboolean gsharedvt_in, gint32 vcall_offset, gboolean calli) { GSharedVtCallInfo *info; CallInfo *caller_cinfo, *callee_cinfo; MonoMethodSignature *caller_sig, *callee_sig; int i, j; gboolean var_ret = FALSE; CallInfo *cinfo, *gcinfo; MonoMethodSignature *sig, *gsig; GPtrArray *map; if (gsharedvt_in) { caller_sig = normal_sig; callee_sig = gsharedvt_sig; caller_cinfo = mono_arch_get_call_info (NULL, caller_sig); callee_cinfo = mono_arch_get_call_info (NULL, callee_sig); } else { callee_sig = normal_sig; callee_cinfo = mono_arch_get_call_info (NULL, callee_sig); caller_sig = gsharedvt_sig; caller_cinfo = mono_arch_get_call_info (NULL, caller_sig); } /* * If GSHAREDVT_IN is true, this means we are transitioning from normal to gsharedvt code. The caller uses the * normal call signature, while the callee uses the gsharedvt signature. * If GSHAREDVT_IN is false, its the other way around. */ /* sig/cinfo describes the normal call, while gsig/gcinfo describes the gsharedvt call */ if (gsharedvt_in) { sig = caller_sig; gsig = callee_sig; cinfo = caller_cinfo; gcinfo = callee_cinfo; } else { sig = callee_sig; gsig = caller_sig; cinfo = callee_cinfo; gcinfo = caller_cinfo; } if (gcinfo->vtype_retaddr && gsig->ret && mini_is_gsharedvt_type (gsig->ret)) { /* * The return type is gsharedvt */ var_ret = TRUE; } /* * The stack looks like this: * <arguments> * <ret addr> * <saved ebp> * <call area> * We have to map the stack slots in <arguments> to the stack slots in <call area>. */ map = g_ptr_array_new (); if (cinfo->vtype_retaddr) { /* * Map ret arg. * This handles the case when the method returns a normal vtype, and when it returns a type arg, and its instantiated * with a vtype. */ g_ptr_array_add (map, GUINT_TO_POINTER (caller_cinfo->vret_arg_offset / sizeof (target_mgreg_t))); g_ptr_array_add (map, GUINT_TO_POINTER (callee_cinfo->vret_arg_offset / sizeof (target_mgreg_t))); } for (i = 0; i < cinfo->nargs; ++i) { ArgInfo *ainfo = &caller_cinfo->args [i]; ArgInfo *ainfo2 = &callee_cinfo->args [i]; int nslots; switch (ainfo->storage) { case ArgGSharedVt: if (ainfo2->storage == ArgOnStack) { nslots = callee_cinfo->args [i].nslots; if (!nslots) nslots = 1; g_ptr_array_add (map, GUINT_TO_POINTER ((ainfo->offset / sizeof (target_mgreg_t)) + (1 << 16) + (nslots << 18))); g_ptr_array_add (map, GUINT_TO_POINTER ((ainfo2->offset / sizeof (target_mgreg_t)))); } else { g_ptr_array_add (map, GUINT_TO_POINTER ((ainfo->offset / sizeof (target_mgreg_t)))); g_ptr_array_add (map, GUINT_TO_POINTER ((ainfo2->offset / sizeof (target_mgreg_t)))); } break; default: if (ainfo2->storage == ArgOnStack) { nslots = cinfo->args [i].nslots; if (!nslots) nslots = 1; for (j = 0; j < nslots; ++j) { g_ptr_array_add (map, GUINT_TO_POINTER ((ainfo->offset / sizeof (target_mgreg_t)) + j)); g_ptr_array_add (map, GUINT_TO_POINTER ((ainfo2->offset / sizeof (target_mgreg_t)) + j)); } } else { g_assert (ainfo2->storage == ArgGSharedVt); g_ptr_array_add (map, GUINT_TO_POINTER ((ainfo->offset / sizeof (target_mgreg_t)) + (2 << 16))); g_ptr_array_add (map, GUINT_TO_POINTER ((ainfo2->offset / sizeof (target_mgreg_t)))); } break; } } info = mono_mem_manager_alloc0 (mem_manager, sizeof (GSharedVtCallInfo) + (map->len * sizeof (int))); info->addr = addr; info->stack_usage = callee_cinfo->stack_usage; info->ret_marshal = GSHAREDVT_RET_NONE; info->gsharedvt_in = gsharedvt_in ? 1 : 0; info->vret_slot = -1; info->calli = calli ? 1 : 0; if (var_ret) info->vret_arg_slot = gcinfo->vret_arg_offset / sizeof (target_mgreg_t); else info->vret_arg_slot = -1; info->vcall_offset = vcall_offset; info->map_count = map->len / 2; for (i = 0; i < map->len; ++i) info->map [i] = GPOINTER_TO_UINT (g_ptr_array_index (map, i)); g_ptr_array_free (map, TRUE); /* Compute return value marshalling */ if (var_ret) { switch (cinfo->ret.storage) { case ArgInIReg: if (gsharedvt_in && !m_type_is_byref (sig->ret) && sig->ret->type == MONO_TYPE_I1) info->ret_marshal = GSHAREDVT_RET_I1; else if (gsharedvt_in && !m_type_is_byref (sig->ret) && (sig->ret->type == MONO_TYPE_U1 || sig->ret->type == MONO_TYPE_BOOLEAN)) info->ret_marshal = GSHAREDVT_RET_U1; else if (gsharedvt_in && !m_type_is_byref (sig->ret) && sig->ret->type == MONO_TYPE_I2) info->ret_marshal = GSHAREDVT_RET_I2; else if (gsharedvt_in && !m_type_is_byref (sig->ret) && (sig->ret->type == MONO_TYPE_U2 || sig->ret->type == MONO_TYPE_CHAR)) info->ret_marshal = GSHAREDVT_RET_U2; else if (cinfo->ret.is_pair) info->ret_marshal = GSHAREDVT_RET_IREGS; else info->ret_marshal = GSHAREDVT_RET_IREG; break; case ArgOnDoubleFpStack: info->ret_marshal = GSHAREDVT_RET_DOUBLE_FPSTACK; break; case ArgOnFloatFpStack: info->ret_marshal = GSHAREDVT_RET_FLOAT_FPSTACK; break; case ArgOnStack: /* The caller passes in a vtype ret arg as well */ g_assert (gcinfo->vtype_retaddr); /* Just have to pop the arg, as done by normal methods in their epilog */ info->ret_marshal = GSHAREDVT_RET_STACK_POP; break; default: g_assert_not_reached (); } } else if (gsharedvt_in && cinfo->vtype_retaddr) { info->ret_marshal = GSHAREDVT_RET_STACK_POP; } if (gsharedvt_in && var_ret && !caller_cinfo->vtype_retaddr) { /* Allocate stack space for the return value */ info->vret_slot = info->stack_usage / sizeof (target_mgreg_t); // FIXME: info->stack_usage += sizeof (target_mgreg_t) * 3; } info->stack_usage = ALIGN_TO (info->stack_usage, MONO_ARCH_FRAME_ALIGNMENT); g_free (caller_cinfo); g_free (callee_cinfo); return info; } #endif
-1
dotnet/runtime
66,452
[mono] Stop setting time_date_stamp field in MonoImage
We never read that field in the runtime and it was causing unnecessary disk IO during startup (5ms on my iOS device). It was also never set on Windows already.
akoeplinger
2022-03-10T15:49:37Z
2022-03-10T21:47:58Z
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
d2826308964e4ee4496d6884e09811e1f709005e
[mono] Stop setting time_date_stamp field in MonoImage. We never read that field in the runtime and it was causing unnecessary disk IO during startup (5ms on my iOS device). It was also never set on Windows already.
./src/native/external/brotli/enc/backward_references_hq.h
/* Copyright 2013 Google Inc. All Rights Reserved. Distributed under MIT license. See file LICENSE for detail or copy at https://opensource.org/licenses/MIT */ /* Function to find backward reference copies. */ #ifndef BROTLI_ENC_BACKWARD_REFERENCES_HQ_H_ #define BROTLI_ENC_BACKWARD_REFERENCES_HQ_H_ #include "../common/constants.h" #include "../common/context.h" #include "../common/dictionary.h" #include "../common/platform.h" #include <brotli/types.h> #include "./command.h" #include "./hash.h" #include "./memory.h" #include "./quality.h" #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif BROTLI_INTERNAL void BrotliCreateZopfliBackwardReferences(MemoryManager* m, size_t num_bytes, size_t position, const uint8_t* ringbuffer, size_t ringbuffer_mask, ContextLut literal_context_lut, const BrotliEncoderParams* params, Hasher* hasher, int* dist_cache, size_t* last_insert_len, Command* commands, size_t* num_commands, size_t* num_literals); BROTLI_INTERNAL void BrotliCreateHqZopfliBackwardReferences(MemoryManager* m, size_t num_bytes, size_t position, const uint8_t* ringbuffer, size_t ringbuffer_mask, ContextLut literal_context_lut, const BrotliEncoderParams* params, Hasher* hasher, int* dist_cache, size_t* last_insert_len, Command* commands, size_t* num_commands, size_t* num_literals); typedef struct ZopfliNode { /* Best length to get up to this byte (not including this byte itself) highest 7 bit is used to reconstruct the length code. */ uint32_t length; /* Distance associated with the length. */ uint32_t distance; /* Number of literal inserts before this copy; highest 5 bits contain distance short code + 1 (or zero if no short code). */ uint32_t dcode_insert_length; /* This union holds information used by dynamic-programming. During forward pass |cost| it used to store the goal function. When node is processed its |cost| is invalidated in favor of |shortcut|. On path back-tracing pass |next| is assigned the offset to next node on the path. */ union { /* Smallest cost to get to this byte from the beginning, as found so far. */ float cost; /* Offset to the next node on the path. Equals to command_length() of the next node on the path. For last node equals to BROTLI_UINT32_MAX */ uint32_t next; /* Node position that provides next distance for distance cache. */ uint32_t shortcut; } u; } ZopfliNode; BROTLI_INTERNAL void BrotliInitZopfliNodes(ZopfliNode* array, size_t length); /* Computes the shortest path of commands from position to at most position + num_bytes. On return, path->size() is the number of commands found and path[i] is the length of the i-th command (copy length plus insert length). Note that the sum of the lengths of all commands can be less than num_bytes. On return, the nodes[0..num_bytes] array will have the following "ZopfliNode array invariant": For each i in [1..num_bytes], if nodes[i].cost < kInfinity, then (1) nodes[i].copy_length() >= 2 (2) nodes[i].command_length() <= i and (3) nodes[i - nodes[i].command_length()].cost < kInfinity */ BROTLI_INTERNAL size_t BrotliZopfliComputeShortestPath( MemoryManager* m, size_t num_bytes, size_t position, const uint8_t* ringbuffer, size_t ringbuffer_mask, ContextLut literal_context_lut, const BrotliEncoderParams* params, const int* dist_cache, Hasher* hasher, ZopfliNode* nodes); BROTLI_INTERNAL void BrotliZopfliCreateCommands( const size_t num_bytes, const size_t block_start, const ZopfliNode* nodes, int* dist_cache, size_t* last_insert_len, const BrotliEncoderParams* params, Command* commands, size_t* num_literals); #if defined(__cplusplus) || defined(c_plusplus) } /* extern "C" */ #endif #endif /* BROTLI_ENC_BACKWARD_REFERENCES_HQ_H_ */
/* Copyright 2013 Google Inc. All Rights Reserved. Distributed under MIT license. See file LICENSE for detail or copy at https://opensource.org/licenses/MIT */ /* Function to find backward reference copies. */ #ifndef BROTLI_ENC_BACKWARD_REFERENCES_HQ_H_ #define BROTLI_ENC_BACKWARD_REFERENCES_HQ_H_ #include "../common/constants.h" #include "../common/context.h" #include "../common/dictionary.h" #include "../common/platform.h" #include <brotli/types.h> #include "./command.h" #include "./hash.h" #include "./memory.h" #include "./quality.h" #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif BROTLI_INTERNAL void BrotliCreateZopfliBackwardReferences(MemoryManager* m, size_t num_bytes, size_t position, const uint8_t* ringbuffer, size_t ringbuffer_mask, ContextLut literal_context_lut, const BrotliEncoderParams* params, Hasher* hasher, int* dist_cache, size_t* last_insert_len, Command* commands, size_t* num_commands, size_t* num_literals); BROTLI_INTERNAL void BrotliCreateHqZopfliBackwardReferences(MemoryManager* m, size_t num_bytes, size_t position, const uint8_t* ringbuffer, size_t ringbuffer_mask, ContextLut literal_context_lut, const BrotliEncoderParams* params, Hasher* hasher, int* dist_cache, size_t* last_insert_len, Command* commands, size_t* num_commands, size_t* num_literals); typedef struct ZopfliNode { /* Best length to get up to this byte (not including this byte itself) highest 7 bit is used to reconstruct the length code. */ uint32_t length; /* Distance associated with the length. */ uint32_t distance; /* Number of literal inserts before this copy; highest 5 bits contain distance short code + 1 (or zero if no short code). */ uint32_t dcode_insert_length; /* This union holds information used by dynamic-programming. During forward pass |cost| it used to store the goal function. When node is processed its |cost| is invalidated in favor of |shortcut|. On path back-tracing pass |next| is assigned the offset to next node on the path. */ union { /* Smallest cost to get to this byte from the beginning, as found so far. */ float cost; /* Offset to the next node on the path. Equals to command_length() of the next node on the path. For last node equals to BROTLI_UINT32_MAX */ uint32_t next; /* Node position that provides next distance for distance cache. */ uint32_t shortcut; } u; } ZopfliNode; BROTLI_INTERNAL void BrotliInitZopfliNodes(ZopfliNode* array, size_t length); /* Computes the shortest path of commands from position to at most position + num_bytes. On return, path->size() is the number of commands found and path[i] is the length of the i-th command (copy length plus insert length). Note that the sum of the lengths of all commands can be less than num_bytes. On return, the nodes[0..num_bytes] array will have the following "ZopfliNode array invariant": For each i in [1..num_bytes], if nodes[i].cost < kInfinity, then (1) nodes[i].copy_length() >= 2 (2) nodes[i].command_length() <= i and (3) nodes[i - nodes[i].command_length()].cost < kInfinity */ BROTLI_INTERNAL size_t BrotliZopfliComputeShortestPath( MemoryManager* m, size_t num_bytes, size_t position, const uint8_t* ringbuffer, size_t ringbuffer_mask, ContextLut literal_context_lut, const BrotliEncoderParams* params, const int* dist_cache, Hasher* hasher, ZopfliNode* nodes); BROTLI_INTERNAL void BrotliZopfliCreateCommands( const size_t num_bytes, const size_t block_start, const ZopfliNode* nodes, int* dist_cache, size_t* last_insert_len, const BrotliEncoderParams* params, Command* commands, size_t* num_literals); #if defined(__cplusplus) || defined(c_plusplus) } /* extern "C" */ #endif #endif /* BROTLI_ENC_BACKWARD_REFERENCES_HQ_H_ */
-1
dotnet/runtime
66,452
[mono] Stop setting time_date_stamp field in MonoImage
We never read that field in the runtime and it was causing unnecessary disk IO during startup (5ms on my iOS device). It was also never set on Windows already.
akoeplinger
2022-03-10T15:49:37Z
2022-03-10T21:47:58Z
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
d2826308964e4ee4496d6884e09811e1f709005e
[mono] Stop setting time_date_stamp field in MonoImage. We never read that field in the runtime and it was causing unnecessary disk IO during startup (5ms on my iOS device). It was also never set on Windows already.
./src/coreclr/md/compiler/custattr.h
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // #ifndef __CustAttr__h__ #define __CustAttr__h__ //#include "stdafx.h" #include "corhdr.h" #include "cahlprinternal.h" #include "sarray.h" #include "factory.h" //***************************************************************************** // Argument parsing. The custom attributes may have ctor arguments, and may // have named arguments. The arguments are defined by the following tables. // // These tables also include a member to contain the value of the argument, // which is used at runtime. When parsing a given custom attribute, a copy // of the argument descriptors is filled in with the values for the instance // of the custom attribute. // // For each ctor arg, there is a CaArg struct, with the type. At runtime, // a value is filled in for each ctor argument. // // For each named arg, there is a CaNamedArg struct, with the name of the // argument, the expected type of the argument, if the type is an enum, // the name of the enum. Also, at runtime, a value is filled in for // each named argument found. // // Note that arrays and variants are not supported. // // At runtime, after the args have been parsed, the tag field of CaValue // can be used to determine if a particular arg was given. //***************************************************************************** struct CaArg { void InitEnum(CorSerializationType _enumType, INT64 _val = 0) { CaTypeCtor caType(SERIALIZATION_TYPE_ENUM, SERIALIZATION_TYPE_UNDEFINED, _enumType, NULL, 0); Init(caType, _val); } void Init(CorSerializationType _type, INT64 _val = 0) { _ASSERTE(_type != SERIALIZATION_TYPE_ENUM); _ASSERTE(_type != SERIALIZATION_TYPE_SZARRAY); CaTypeCtor caType(_type); Init(caType, _val); } void Init(CaType _type, INT64 _val = 0) { type = _type; memset(&val, 0, sizeof(CaValue)); val.i8 = _val; } CaType type; CaValue val; }; struct CaNamedArg { void InitI4FieldEnum(LPCSTR _szName, LPCSTR _szEnumName, INT64 _val = 0) { CaTypeCtor caType(SERIALIZATION_TYPE_ENUM, SERIALIZATION_TYPE_UNDEFINED, SERIALIZATION_TYPE_I4, _szEnumName, (ULONG)strlen(_szEnumName)); Init(_szName, SERIALIZATION_TYPE_FIELD, caType, _val); } void InitBoolField(LPCSTR _szName, INT64 _val = 0) { CaTypeCtor caType(SERIALIZATION_TYPE_BOOLEAN); Init(_szName, SERIALIZATION_TYPE_FIELD, caType, _val); } void Init(LPCSTR _szName, CorSerializationType _propertyOrField, CaType _type, INT64 _val = 0) { szName = _szName; cName = _szName ? (ULONG)strlen(_szName) : 0; propertyOrField = _propertyOrField; type = _type; memset(&val, 0, sizeof(CaValue)); val.i8 = _val; } LPCSTR szName; ULONG cName; CorSerializationType propertyOrField; CaType type; CaValue val; }; struct CaNamedArgCtor : public CaNamedArg { CaNamedArgCtor() { memset(this, 0, sizeof(CaNamedArg)); } }; HRESULT ParseEncodedType( CustomAttributeParser &ca, CaType* pCaType); HRESULT ParseKnownCaArgs( CustomAttributeParser &ca, // The Custom Attribute blob. CaArg *pArgs, // Array of argument descriptors. ULONG cArgs); // Count of argument descriptors. HRESULT ParseKnownCaNamedArgs( CustomAttributeParser &ca, // The Custom Attribute blob. CaNamedArg *pNamedArgs, // Array of argument descriptors. ULONG cNamedArgs); // Count of argument descriptors. #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // #ifndef __CustAttr__h__ #define __CustAttr__h__ //#include "stdafx.h" #include "corhdr.h" #include "cahlprinternal.h" #include "sarray.h" #include "factory.h" //***************************************************************************** // Argument parsing. The custom attributes may have ctor arguments, and may // have named arguments. The arguments are defined by the following tables. // // These tables also include a member to contain the value of the argument, // which is used at runtime. When parsing a given custom attribute, a copy // of the argument descriptors is filled in with the values for the instance // of the custom attribute. // // For each ctor arg, there is a CaArg struct, with the type. At runtime, // a value is filled in for each ctor argument. // // For each named arg, there is a CaNamedArg struct, with the name of the // argument, the expected type of the argument, if the type is an enum, // the name of the enum. Also, at runtime, a value is filled in for // each named argument found. // // Note that arrays and variants are not supported. // // At runtime, after the args have been parsed, the tag field of CaValue // can be used to determine if a particular arg was given. //***************************************************************************** struct CaArg { void InitEnum(CorSerializationType _enumType, INT64 _val = 0) { CaTypeCtor caType(SERIALIZATION_TYPE_ENUM, SERIALIZATION_TYPE_UNDEFINED, _enumType, NULL, 0); Init(caType, _val); } void Init(CorSerializationType _type, INT64 _val = 0) { _ASSERTE(_type != SERIALIZATION_TYPE_ENUM); _ASSERTE(_type != SERIALIZATION_TYPE_SZARRAY); CaTypeCtor caType(_type); Init(caType, _val); } void Init(CaType _type, INT64 _val = 0) { type = _type; memset(&val, 0, sizeof(CaValue)); val.i8 = _val; } CaType type; CaValue val; }; struct CaNamedArg { void InitI4FieldEnum(LPCSTR _szName, LPCSTR _szEnumName, INT64 _val = 0) { CaTypeCtor caType(SERIALIZATION_TYPE_ENUM, SERIALIZATION_TYPE_UNDEFINED, SERIALIZATION_TYPE_I4, _szEnumName, (ULONG)strlen(_szEnumName)); Init(_szName, SERIALIZATION_TYPE_FIELD, caType, _val); } void InitBoolField(LPCSTR _szName, INT64 _val = 0) { CaTypeCtor caType(SERIALIZATION_TYPE_BOOLEAN); Init(_szName, SERIALIZATION_TYPE_FIELD, caType, _val); } void Init(LPCSTR _szName, CorSerializationType _propertyOrField, CaType _type, INT64 _val = 0) { szName = _szName; cName = _szName ? (ULONG)strlen(_szName) : 0; propertyOrField = _propertyOrField; type = _type; memset(&val, 0, sizeof(CaValue)); val.i8 = _val; } LPCSTR szName; ULONG cName; CorSerializationType propertyOrField; CaType type; CaValue val; }; struct CaNamedArgCtor : public CaNamedArg { CaNamedArgCtor() { memset(this, 0, sizeof(CaNamedArg)); } }; HRESULT ParseEncodedType( CustomAttributeParser &ca, CaType* pCaType); HRESULT ParseKnownCaArgs( CustomAttributeParser &ca, // The Custom Attribute blob. CaArg *pArgs, // Array of argument descriptors. ULONG cArgs); // Count of argument descriptors. HRESULT ParseKnownCaNamedArgs( CustomAttributeParser &ca, // The Custom Attribute blob. CaNamedArg *pNamedArgs, // Array of argument descriptors. ULONG cNamedArgs); // Count of argument descriptors. #endif
-1