HRESULT Library_corlib_native_System_RuntimeType::GetInterfaces___SZARRAY_SystemType( CLR_RT_StackFrame& stack )
{
    NATIVE_PROFILE_CLR_CORE();
    TINYCLR_HEADER();

    CLR_RT_TypeDef_Instance td;    
    CLR_RT_HeapBlock& top = stack.PushValueAndClear();
    CLR_RT_HeapBlock* ptr;
    
    TINYCLR_CHECK_HRESULT(GetTypeDescriptor( stack.Arg0(), td ));

    //
    // Scan the list of interfaces.
    //
    CLR_RT_SignatureParser          parser; parser.Initialize_Interfaces( td.m_assm, td.m_target );
    CLR_RT_SignatureParser::Element res;
    
    TINYCLR_CHECK_HRESULT(CLR_RT_HeapBlock_Array::CreateInstance( top, parser.Available(), g_CLR_RT_WellKnownTypes.m_Type ));
    
    ptr = (CLR_RT_HeapBlock*)top.DereferenceArray()->GetFirstElement();

    while(parser.Available() > 0)
    {
        TINYCLR_CHECK_HRESULT(parser.Advance( res ));        

        ptr->SetReflection( res.m_cls );

        ptr++;
    }    

    TINYCLR_NOCLEANUP();
}
HRESULT Library_corlib_native_System_Reflection_Assembly::GetType___SystemType__STRING( CLR_RT_StackFrame& stack )
{
    NATIVE_PROFILE_CLR_CORE();
    TINYCLR_HEADER();
    
    CLR_RT_Assembly_Instance assm;
    CLR_RT_TypeDef_Index     td;
    CLR_RT_HeapBlock*        hbRef;
    CLR_RT_HeapBlock*        hbObj;
    LPCSTR                   szClass = stack.Arg1().RecoverString(); 
    CLR_RT_HeapBlock*        hbAsm = stack.Arg0().Dereference();

    FAULT_ON_NULL(szClass);
    FAULT_ON_NULL(hbAsm);

    TINYCLR_CHECK_HRESULT(GetTypeDescriptor( *hbAsm, assm ));

    hbRef = &stack.PushValueAndClear();
    
    if(g_CLR_RT_TypeSystem.FindTypeDef( szClass, assm.m_assm, td ))
    {
        TINYCLR_CHECK_HRESULT(g_CLR_RT_ExecutionEngine.NewObjectFromIndex(*hbRef, g_CLR_RT_WellKnownTypes.m_TypeStatic));
        
        hbObj = hbRef->Dereference();
        hbObj->SetReflection( td );
    }

    TINYCLR_NOCLEANUP();
}
HRESULT Library_spot_native_Microsoft_SPOT_Reflection::GetAssemblyFromHash___STATIC__mscorlibSystemReflectionAssembly__U4( CLR_RT_StackFrame& stack )
{
    NATIVE_PROFILE_CLR_CORE();
    TINYCLR_HEADER();

    CLR_RT_HeapBlock& top  = stack.PushValueAndClear();
    CLR_UINT32        hash = stack.Arg0().NumericByRefConst().u4;

    TINYCLR_FOREACH_ASSEMBLY_IN_CURRENT_APPDOMAIN(g_CLR_RT_TypeSystem)
    {
        if(pASSM->ComputeAssemblyHash() == hash)
        {
            CLR_RT_HeapBlock* hbObj;
            CLR_RT_Assembly_Index idx; idx.Set( pASSM->m_idx );
            
            TINYCLR_CHECK_HRESULT(g_CLR_RT_ExecutionEngine.NewObjectFromIndex(top, g_CLR_RT_WellKnownTypes.m_Assembly));
            hbObj = top.Dereference();
            
            hbObj->SetReflection( idx ); 

            TINYCLR_SET_AND_LEAVE(S_OK);
        }
    }
    TINYCLR_FOREACH_ASSEMBLY_IN_CURRENT_APPDOMAIN_END();

    TINYCLR_NOCLEANUP();
}
HRESULT Library_corlib_native_System_Reflection_Assembly::Load___STATIC__SystemReflectionAssembly__SZARRAY_U1( CLR_RT_StackFrame& stack )
{
    NATIVE_PROFILE_CLR_CORE();
    TINYCLR_HEADER();

    CLR_RT_HeapBlock_Array* array = NULL;
    CLR_RT_Assembly*        assm  = NULL;
    CLR_RT_HeapBlock&       top   = stack.PushValueAndClear();
    CLR_RT_HeapBlock*       hbObj;
    CLR_RECORD_ASSEMBLY*    header;

    array = stack.Arg0().DereferenceArray(); FAULT_ON_NULL(array);

    header = (CLR_RECORD_ASSEMBLY*)array->GetFirstElement();
    
    TINYCLR_CHECK_HRESULT(CLR_RT_Assembly::VerifyEndian(header));

    if(header->GoodAssembly())
    {
        //
        // Sorry, you'll have to reboot to load this assembly.
        //
        if(header->flags & CLR_RECORD_ASSEMBLY::c_Flags_NeedReboot)
        {
            TINYCLR_SET_AND_LEAVE(CLR_E_BUSY);
        }

        TINYCLR_CHECK_HRESULT(CLR_RT_Assembly::CreateInstance( header, assm ));

        assm->m_pFile = array;

        g_CLR_RT_TypeSystem.Link( assm );

        TINYCLR_CHECK_HRESULT(g_CLR_RT_TypeSystem.ResolveAll         ());
        TINYCLR_CHECK_HRESULT(g_CLR_RT_TypeSystem.PrepareForExecution());
    }

    if(assm)
    {
        CLR_RT_Assembly_Index idx; idx.Set( assm->m_idx );

        TINYCLR_CHECK_HRESULT(g_CLR_RT_ExecutionEngine.NewObjectFromIndex(top, g_CLR_RT_WellKnownTypes.m_Assembly));
        
        hbObj = top.Dereference();
        hbObj->SetReflection( idx );
    }

    TINYCLR_CLEANUP();

    if(FAILED(hr))
    {
        if(assm)
        {
            assm->DestroyInstance();
        }
    }

    TINYCLR_CLEANUP_END();
}
HRESULT Library_corlib_native_System_Reflection_Assembly::LoadInternal___STATIC__SystemReflectionAssembly__STRING__BOOLEAN__I4__I4__I4__I4( CLR_RT_StackFrame& stack )
{
    NATIVE_PROFILE_CLR_CORE();
    TINYCLR_HEADER();

#if defined(TINYCLR_APPDOMAINS)
    CLR_RT_AppDomain*     appDomain = g_CLR_RT_ExecutionEngine.GetCurrentAppDomain();
#endif
    CLR_RT_HeapBlock*     pArgs     = &stack.Arg0();
    CLR_RT_Assembly*      assembly;
    LPCSTR                szAssembly;
    CLR_RT_Assembly_Index idx; 
    bool                  fVersion;
    CLR_INT16             maj, min, build, rev;
    CLR_RT_HeapBlock&     top = stack.PushValueAndClear();
    
    szAssembly = pArgs[ 0 ].RecoverString(); FAULT_ON_NULL(szAssembly );
    fVersion   = pArgs[ 1 ].NumericByRef().u1 != 0;    
    maj        = pArgs[ 2 ].NumericByRef().s4;    
    min        = pArgs[ 3 ].NumericByRef().s4;
    build      = pArgs[ 4 ].NumericByRef().s4;
    rev        = pArgs[ 5 ].NumericByRef().s4;

    if(fVersion && (maj < 0 || min < 0 || build < 0 || rev < 0))
    {
        TINYCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER);
    }

    if(fVersion)
    {
        CLR_RECORD_VERSION ver;

        ver.iMajorVersion   = (CLR_UINT16)maj;
        ver.iMinorVersion   = (CLR_UINT16)min;
        ver.iBuildNumber    = (CLR_UINT16)build;
        ver.iRevisionNumber = (CLR_UINT16)rev;
        
        assembly = g_CLR_RT_TypeSystem.FindAssembly( szAssembly, &ver, true ); FAULT_ON_NULL_HR(assembly, CLR_E_INVALID_PARAMETER);
    }
    else
    {
        assembly = g_CLR_RT_TypeSystem.FindAssembly( szAssembly, NULL, false ); FAULT_ON_NULL_HR(assembly, CLR_E_INVALID_PARAMETER);
    }
    
#if defined(TINYCLR_APPDOMAINS)
    TINYCLR_CHECK_HRESULT(appDomain->LoadAssembly( assembly ));
#endif
    idx.Set( assembly->m_idx );

    top.SetReflection( idx );

    TINYCLR_CLEANUP();

    //Avoid exception handling in common case.  Just return NULL on failure.
    //Managed code decides to throw the exception or not.  
    hr = S_OK;

    TINYCLR_CLEANUP_END();
}
HRESULT Library_corlib_native_System_Object::MemberwiseClone___OBJECT( CLR_RT_StackFrame& stack )
{
    NATIVE_PROFILE_CLR_CORE();
    TINYCLR_HEADER();

    TINYCLR_SET_AND_LEAVE(g_CLR_RT_ExecutionEngine.CloneObject( stack.PushValueAndClear(), stack.Arg0() ));

    TINYCLR_NOCLEANUP();
}
HRESULT Library_corlib_native_System_RuntimeType::get_FullName___STRING( CLR_RT_StackFrame& stack )
{
    NATIVE_PROFILE_CLR_CORE();
    TINYCLR_HEADER();

    TINYCLR_CHECK_HRESULT(GetName( stack.Arg0(), true, stack.PushValueAndClear() ));
 
    TINYCLR_NOCLEANUP();
}
HRESULT Library_spot_native_Microsoft_SPOT_Messaging_EndPoint::GetMessage___MicrosoftSPOTMessagingMessage__I4( CLR_RT_StackFrame& stack )
{
    NATIVE_PROFILE_CLR_MESSAGING();
    TINYCLR_HEADER();

    CLR_RT_HeapBlock*                   pThis;
    CLR_RT_HeapBlock_EndPoint*          ep;
    CLR_RT_HeapBlock_EndPoint::Message* msg = NULL;
    CLR_INT64*                          timeout;
    bool                                fRes;

    pThis = stack.This(); FAULT_ON_NULL(pThis);

    TINYCLR_CHECK_HRESULT(CLR_RT_HeapBlock_EndPoint::ExtractInstance( pThis[ FIELD__m_handle ], ep ));

    TINYCLR_CHECK_HRESULT(stack.SetupTimeout( stack.Arg1(), timeout ));

    fRes = true;
    while(fRes)
    {
        msg = ep->FindMessage( CLR_Messaging_Commands::c_Messaging_Send, NULL );

        if(msg) break;

        TINYCLR_CHECK_HRESULT(g_CLR_RT_ExecutionEngine.WaitEvents( stack.m_owningThread, *timeout, CLR_RT_ExecutionEngine::c_Event_EndPoint, fRes ));
    }

    stack.PopValue();

    {
        CLR_RT_HeapBlock& top = stack.PushValueAndClear();

        if(msg)
        {
            CLR_RT_HeapBlock*          pMsg;
            CLR_RT_ReflectionDef_Index val; val.InitializeFromHash( msg->m_addr.m_from.m_type );

            TINYCLR_CHECK_HRESULT(g_CLR_RT_ExecutionEngine.NewObjectFromIndex( top, g_CLR_RT_WellKnownTypes.m_Message ));

            pMsg = top.Dereference();
            pMsg[ Library_spot_native_Microsoft_SPOT_Messaging_Message::FIELD__m_source   ].SetObjectReference( pThis                   );
            pMsg[ Library_spot_native_Microsoft_SPOT_Messaging_Message::FIELD__m_selector ].SetReflection     ( val                     );
            pMsg[ Library_spot_native_Microsoft_SPOT_Messaging_Message::FIELD__m_id       ].SetInteger        ( msg->m_addr.m_from.m_id );
            pMsg[ Library_spot_native_Microsoft_SPOT_Messaging_Message::FIELD__m_seq      ].SetInteger        ( msg->m_addr.m_seq       );

            TINYCLR_CHECK_HRESULT(CLR_RT_HeapBlock_Array::CreateInstance( pMsg[ Library_spot_native_Microsoft_SPOT_Messaging_Message::FIELD__m_payload ], msg->m_length, g_CLR_RT_WellKnownTypes.m_UInt8 ));

            memcpy( pMsg[ Library_spot_native_Microsoft_SPOT_Messaging_Message::FIELD__m_payload ].DereferenceArray()->GetFirstElement(), msg->m_data, msg->m_length );

            msg->Unlink(); CLR_RT_Memory::Release( msg );
        }
    }

    TINYCLR_NOCLEANUP();
}
HRESULT Library_corlib_native_System_BitConverter::GetBytes___STATIC__SZARRAY_U1__I4( CLR_RT_StackFrame& stack )
{
	NATIVE_PROFILE_CLR_CORE();
	TINYCLR_HEADER();

	int input = stack.Arg0().NumericByRefConst().s4;

	TINYCLR_CHECK_HRESULT(CLR_RT_HeapBlock_Array::CreateInstance(stack.PushValueAndClear(), 4, g_CLR_RT_WellKnownTypes.m_UInt8));
	BYTE* p;
	p  = stack.TopValue().DereferenceArray()->GetFirstElement();
	*reinterpret_cast<int*>(p) = input;

	TINYCLR_NOCLEANUP();
}
HRESULT Library_spot_Time_native_Microsoft_SPOT_Time_TimeService::Update___STATIC__MicrosoftSPOTTimeTimeServiceStatus__U4__U4( CLR_RT_StackFrame& stack )
{
    TINYCLR_HEADER(); 

    CLR_RT_HeapBlock* managedStatus = NULL;  

    UINT32 serverIP  = stack.Arg0().NumericByRef().u4;
    UINT32 tolerance = stack.Arg1().NumericByRef().u4;    

    TimeService_Status status;

    hr = TimeService_Update( serverIP, tolerance, &status );

    if(hr == CLR_E_RESCHEDULE) 
    {
        TINYCLR_LEAVE();
    }
    else 
    {
        CLR_RT_HeapBlock& top = stack.PushValueAndClear();

        TINYCLR_CHECK_HRESULT(g_CLR_RT_ExecutionEngine.NewObjectFromIndex( top, g_CLR_RT_WellKnownTypes.m_TimeServiceStatus ));
        
        managedStatus = top.Dereference();

        managedStatus[ ManagedStatus::FIELD__Flags            ].SetInteger( status.Flags );
        managedStatus[ ManagedStatus::FIELD__SyncSourceServer ].SetInteger( status.ServerIP );
        managedStatus[ ManagedStatus::FIELD__SyncTimeOffset   ].SetInteger( status.SyncOffset );
        managedStatus[ ManagedStatus::FIELD__TimeUTC          ].SetInteger( status.CurrentTimeUTC );
    }

    TINYCLR_CLEANUP();

    // we are not throwing any exception, we are instead communicating the result through the TimeServiceStatus object we return
    // if the operation did not completed, we need to reschedule this call though
    switch(hr)
    {
        case CLR_E_RESCHEDULE:
            break;
        case CLR_E_TIMEOUT:
        case CLR_E_FAIL:
        default:
            // swallow error
            hr = S_OK; 
            break;
    }

    TINYCLR_CLEANUP_END();
}
HRESULT Library_spot_native_Microsoft_SPOT_Reflection::GetAssemblies___STATIC__SZARRAY_mscorlibSystemReflectionAssembly( CLR_RT_StackFrame& stack )
{
    NATIVE_PROFILE_CLR_CORE();
    TINYCLR_HEADER();

    CLR_RT_HeapBlock& top    = stack.PushValueAndClear();

#if defined(TINYCLR_APPDOMAINS)
    TINYCLR_CHECK_HRESULT(g_CLR_RT_ExecutionEngine.GetCurrentAppDomain()->GetAssemblies( top ));
#else
    int               count  = 0;
    CLR_RT_HeapBlock* pArray = NULL;

    for(int pass=0; pass<2; pass++)
    {
        TINYCLR_FOREACH_ASSEMBLY(g_CLR_RT_TypeSystem)
        {
            if(pASSM->m_header->flags & CLR_RECORD_ASSEMBLY::c_Flags_Patch) continue;

            if(pass == 0)
            {
                count++;
            }
            else
            {
                CLR_RT_HeapBlock* hbObj;
                CLR_RT_Assembly_Index idx; idx.Set( pASSM->m_idx );

                TINYCLR_CHECK_HRESULT(g_CLR_RT_ExecutionEngine.NewObjectFromIndex(*pArray, g_CLR_RT_WellKnownTypes.m_Assembly));
                hbObj = pArray->Dereference();
                
                hbObj->SetReflection( idx ); 

                pArray++;
            }
        }
        TINYCLR_FOREACH_ASSEMBLY_END();

        if(pass == 0)
        {
            TINYCLR_CHECK_HRESULT(CLR_RT_HeapBlock_Array::CreateInstance( top, count, g_CLR_RT_WellKnownTypes.m_Assembly ));

            pArray = (CLR_RT_HeapBlock*)top.DereferenceArray()->GetFirstElement();
        }
    }
#endif //TINYCLR_APPDOMAINS

    TINYCLR_NOCLEANUP();
}
HRESULT Library_spot_native_Microsoft_SPOT_Reflection::GetTypeFromHash___STATIC__mscorlibSystemType__U4( CLR_RT_StackFrame& stack )
{
    NATIVE_PROFILE_CLR_CORE();
    TINYCLR_HEADER();

    CLR_RT_HeapBlock&    top = stack.PushValueAndClear();
    CLR_RT_TypeDef_Index res;

    if(g_CLR_RT_TypeSystem.FindTypeDef( stack.Arg0().NumericByRefConst().u4, res ))
    {
        top.SetReflection( res );
    }

    TINYCLR_NOCLEANUP_NOLABEL();
}
HRESULT Library_corlib_native_System_Reflection_Assembly::GetExecutingAssembly___STATIC__SystemReflectionAssembly( CLR_RT_StackFrame& stack )
{
    NATIVE_PROFILE_CLR_CORE();
    TINYCLR_HEADER();

    CLR_RT_HeapBlock& top = stack.PushValueAndClear();

    CLR_RT_StackFrame* caller = stack.Caller(); if(caller == NULL) TINYCLR_SET_AND_LEAVE(S_OK);

    {
        CLR_RT_Assembly_Index idx; idx.Set( caller->MethodCall().m_assm->m_idx );

        top.SetReflection( idx );
    }
    
    TINYCLR_NOCLEANUP();
}
HRESULT Library_spot_native_Microsoft_SPOT_Hardware_Utility::ExtractRangeFromArray___STATIC__SZARRAY_U1__SZARRAY_U1__I4__I4( CLR_RT_StackFrame& stack )
{
    NATIVE_PROFILE_CLR_CORE();
    TINYCLR_HEADER();

    CLR_RT_HeapBlock*       args = &stack.Arg0();
    CLR_RT_HeapBlock_Array* array;
    CLR_RT_HeapBlock&       ref = stack.PushValueAndClear();

    array = args[ 0 ].DereferenceArray(); FAULT_ON_NULL(array);

    TINYCLR_CHECK_HRESULT(CLR_RT_HeapBlock_Array::CreateInstance( ref, args[ 2 ].NumericByRefConst().s4, array->ReflectionDataConst() ));

    TINYCLR_CHECK_HRESULT(Library_corlib_native_System_Array::Copy( stack, stack.Arg0(), args[ 1 ].NumericByRefConst().s4, ref, 0, args[ 2 ].NumericByRefConst().s4 ));

    TINYCLR_NOCLEANUP();
}
HRESULT Library_corlib_native_System_AppDomain::GetAssemblies___SZARRAY_SystemReflectionAssembly( CLR_RT_StackFrame& stack )
{   
    NATIVE_PROFILE_CLR_CORE();
    TINYCLR_HEADER();
    
    CLR_RT_AppDomain* appDomainSav = NULL;
    CLR_RT_AppDomain* appDomain;    

    TINYCLR_CHECK_HRESULT(GetAppDomain( stack.ThisRef(), appDomain, appDomainSav, true ));

    TINYCLR_CHECK_HRESULT(appDomain->GetAssemblies( stack.PushValueAndClear() ));    

    TINYCLR_CLEANUP();

    g_CLR_RT_ExecutionEngine.SetCurrentAppDomain( appDomainSav );    

    TINYCLR_CLEANUP_END();
}
HRESULT Library_corlib_native_System_RuntimeType::GetElementType___SystemType( CLR_RT_StackFrame& stack )
{
    NATIVE_PROFILE_CLR_CORE();
    TINYCLR_HEADER();
                
    CLR_RT_TypeDescriptor   desc;
    CLR_RT_TypeDescriptor   descSub;    
    CLR_RT_HeapBlock& top = stack.PushValueAndClear();

    TINYCLR_CHECK_HRESULT(desc.InitializeFromReflection( stack.Arg0().ReflectionDataConst() ));

    if(desc.GetElementType( descSub ))
    {
        top.SetReflection( descSub.m_reflex );
    }
        
    TINYCLR_NOCLEANUP();
}
HRESULT Library_corlib_native_System_Reflection_Assembly::GetType___SystemType__STRING( CLR_RT_StackFrame& stack )
{
    NATIVE_PROFILE_CLR_CORE();
    TINYCLR_HEADER();
    
    CLR_RT_Assembly_Instance assm;
    CLR_RT_TypeDef_Index     td;
    CLR_RT_HeapBlock&        top     = stack.PushValueAndClear();
    LPCSTR                   szClass = stack.Arg1().RecoverString(); FAULT_ON_NULL(szClass);

    TINYCLR_CHECK_HRESULT(GetTypeDescriptor( stack.Arg0(), assm ));
    
    if(g_CLR_RT_TypeSystem.FindTypeDef( szClass, assm.m_assm, td ))
    {
        top.SetReflection( td );
    }

    TINYCLR_NOCLEANUP();
}
HRESULT Library_spot_Time_native_Microsoft_SPOT_Time_TimeService::get_LastSyncStatus___STATIC__MicrosoftSPOTTimeTimeServiceStatus( CLR_RT_StackFrame& stack )
{
    TINYCLR_HEADER(); 

    TimeService_Status status;
    CLR_RT_HeapBlock&       top = stack.PushValueAndClear();
    CLR_RT_HeapBlock*       managedStatus = NULL;      

    TINYCLR_CHECK_HRESULT(TimeService_GetLastSyncStatus( &status ));

    TINYCLR_CHECK_HRESULT(g_CLR_RT_ExecutionEngine.NewObjectFromIndex( top, g_CLR_RT_WellKnownTypes.m_TimeServiceStatus ));
    managedStatus = top.Dereference();

    managedStatus[ ManagedStatus::FIELD__Flags            ].SetInteger( status.Flags );
    managedStatus[ ManagedStatus::FIELD__SyncSourceServer ].SetInteger( status.ServerIP );
    managedStatus[ ManagedStatus::FIELD__SyncTimeOffset   ].SetInteger( status.SyncOffset );
    managedStatus[ ManagedStatus::FIELD__TimeUTC          ].SetInteger( status.CurrentTimeUTC );

    TINYCLR_NOCLEANUP();
}
HRESULT Library_spot_native_Microsoft_SPOT_Reflection::GetTypeFromHash___STATIC__mscorlibSystemType__U4( CLR_RT_StackFrame& stack )
{
    NATIVE_PROFILE_CLR_CORE();
    TINYCLR_HEADER();

    CLR_RT_HeapBlock&    top = stack.PushValueAndClear();
    CLR_RT_TypeDef_Index res;

    if(g_CLR_RT_TypeSystem.FindTypeDef( stack.Arg0().NumericByRefConst().u4, res ))
    {
        CLR_RT_HeapBlock* hbObj;

        TINYCLR_CHECK_HRESULT(g_CLR_RT_ExecutionEngine.NewObjectFromIndex(top, g_CLR_RT_WellKnownTypes.m_TypeStatic));
        hbObj = top.Dereference();
        
        hbObj->SetReflection( res ); 
    }

    TINYCLR_NOCLEANUP();
}
HRESULT Library_spot_update_native_Microsoft_SPOT_MFUpdate_MFNativeUpdate::SerializeParameter___STATIC__SZARRAY_U1__OBJECT( CLR_RT_StackFrame& stack )
{
    TINYCLR_HEADER();
    CLR_INT32 offset = 0, size = 0;
    CLR_RT_HeapBlock &ref = stack.PushValueAndClear();
    CLR_UINT8* pData;

    CLR_RT_HeapBlock& obj = stack.Arg0();

    if(!SerializeObject( &obj, NULL, offset, size ) || size <= 0) TINYCLR_SET_AND_LEAVE(CLR_E_FAIL);

    TINYCLR_CHECK_HRESULT(CLR_RT_HeapBlock_Array::CreateInstance(ref, size, g_CLR_RT_WellKnownTypes.m_UInt8));

    pData = (CLR_UINT8*)ref.DereferenceArray()->GetFirstElement();

    offset = 0;

    if(!SerializeObject( &obj, pData, offset, size )) TINYCLR_SET_AND_LEAVE(CLR_E_FAIL);

    TINYCLR_NOCLEANUP();
}
HRESULT Library_corlib_native_System_Reflection_Assembly::GetExecutingAssembly___STATIC__SystemReflectionAssembly( CLR_RT_StackFrame& stack )
{
    NATIVE_PROFILE_CLR_CORE();
    TINYCLR_HEADER();

    CLR_RT_HeapBlock& top = stack.PushValueAndClear();
    CLR_RT_HeapBlock* hbObj;

    CLR_RT_StackFrame* caller = stack.Caller(); if(caller == NULL) TINYCLR_SET_AND_LEAVE(S_OK);

    {
        CLR_RT_Assembly_Index idx; idx.Set( caller->MethodCall().m_assm->m_idx );

        TINYCLR_CHECK_HRESULT(g_CLR_RT_ExecutionEngine.NewObjectFromIndex(top, g_CLR_RT_WellKnownTypes.m_Assembly));
        
        hbObj = top.Dereference();
        hbObj->SetReflection( idx );
    }
    
    TINYCLR_NOCLEANUP();
}
HRESULT Library_spot_Time_native_Microsoft_SPOT_Time_TimeService::get_Settings___STATIC__MicrosoftSPOTTimeTimeServiceSettings( CLR_RT_StackFrame& stack )
{
    TINYCLR_HEADER(); 

    TimeService_Settings    settings;
    CLR_RT_HeapBlock&       top = stack.PushValueAndClear();
    CLR_RT_HeapBlock*       managedSettings = NULL;

    TINYCLR_CHECK_HRESULT(TimeService_LoadSettings(&settings));    

    TINYCLR_CHECK_HRESULT(g_CLR_RT_ExecutionEngine.NewObjectFromIndex( top, g_CLR_RT_WellKnownTypes.m_TimeServiceSettings ));
    managedSettings = top.Dereference();

    managedSettings[ ManagedSettings::FIELD__PrimaryServerIP     ].SetInteger( settings.PrimaryServerIP );
    managedSettings[ ManagedSettings::FIELD__AlternateServerIP   ].SetInteger( settings.AlternateServerIP );
    managedSettings[ ManagedSettings::FIELD__RefreshTime         ].SetInteger( settings.RefreshTime );
    managedSettings[ ManagedSettings::FIELD__Tolerance           ].SetInteger( settings.Tolerance );
    managedSettings[ ManagedSettings::FIELD__ForceSyncAtWakeUp   ].SetBoolean( settings.Flags & TimeService_Settings_Flags_ForceSyncAtWakeUp );
    managedSettings[ ManagedSettings::FIELD__AutoDayLightSavings ].SetBoolean( settings.Flags & TimeService_Settings_Flags_AutoDST );

    TINYCLR_NOCLEANUP();
}
HRESULT Library_corlib_native_System_BitConverter::GetBytes___STATIC__SZARRAY_U1__R8(CLR_RT_StackFrame& stack)
{
	NATIVE_PROFILE_CLR_CORE();
	TINYCLR_HEADER();

#if !defined(TINYCLR_EMULATED_FLOATINGPOINT)
	double input = stack.Arg0().NumericByRefConst().r8;
#else
	CLR_INT64 input = stack.Arg0().NumericByRefConst().r8;
#endif

	TINYCLR_CHECK_HRESULT(CLR_RT_HeapBlock_Array::CreateInstance(stack.PushValueAndClear(), 8, g_CLR_RT_WellKnownTypes.m_UInt8));
	{
		BYTE* p = stack.TopValue().DereferenceArray()->GetFirstElement();
#if !defined(TINYCLR_EMULATED_FLOATINGPOINT)
		*reinterpret_cast<double*>(p) = input;
#else
		*reinterpret_cast<CLR_INT64*>(p) = input;
#endif
	}
	TINYCLR_NOCLEANUP();
}
HRESULT Library_corlib_native_System_Text_UTF8Encoding::GetBytes___SZARRAY_U1__STRING( CLR_RT_StackFrame& stack )
{
    NATIVE_PROFILE_CLR_CORE();
    TINYCLR_HEADER();

    size_t                  cBytes;
    CLR_RT_HeapBlock_Array* arr;
    LPCSTR                  str;
    CLR_RT_HeapBlock&       ret = stack.PushValueAndClear();

    str    = stack.Arg1().RecoverString();
    FAULT_ON_NULL(str);
    cBytes = hal_strlen_s(str);

    TINYCLR_CHECK_HRESULT(CLR_RT_HeapBlock_Array::CreateInstance( ret, (CLR_UINT32)cBytes, g_CLR_RT_WellKnownTypes.m_UInt8 ));

    arr = ret.DereferenceArray();

    memcpy( arr->GetFirstElement(), str, cBytes );

    TINYCLR_NOCLEANUP();
}
HRESULT Library_corlib_native_System_RuntimeType::get_BaseType___SystemType( CLR_RT_StackFrame& stack )
{
    NATIVE_PROFILE_CLR_CORE();
    TINYCLR_HEADER();

    CLR_RT_TypeDef_Instance td;
    CLR_UINT32              levels;
    CLR_RT_HeapBlock&       top = stack.PushValueAndClear();

    TINYCLR_CHECK_HRESULT(GetTypeDescriptor( stack.Arg0(), td, &levels ));
        
    if(levels > 0)
    {
        top.SetReflection( g_CLR_RT_WellKnownTypes.m_Array );
    }
    else if(td.SwitchToParent())
    {
        top.SetReflection( td );
    }

    TINYCLR_NOCLEANUP();
}
HRESULT Library_spot_io_native_Microsoft_SPOT_IO_NativeFindFile::GetNext___MicrosoftSPOTIONativeFileInfo( CLR_RT_StackFrame& stack )
{
    NATIVE_PROFILE_CLR_IO();
    TINYCLR_HEADER();

    CLR_RT_FindFile* ff;
    FS_FILEINFO*     fi;
    BOOL             found;
    
    CLR_RT_HeapBlock& top = stack.PushValueAndClear();

    TINYCLR_CHECK_HRESULT(GetFindFile( stack, ff ));

    TINYCLR_CHECK_HRESULT(ff->GetNext( &fi, &found ));

    if(found)
    {
        CLR_RT_HeapBlock* managedFi;

        TINYCLR_CHECK_HRESULT(g_CLR_RT_ExecutionEngine.NewObjectFromIndex( top, g_CLR_RT_WellKnownTypes.m_NativeFileInfo ));

        managedFi = top.Dereference();

        managedFi[ Library_spot_io_native_Microsoft_SPOT_IO_NativeFileInfo::FIELD__Attributes     ].SetInteger( (CLR_UINT32)fi->Attributes );
        managedFi[ Library_spot_io_native_Microsoft_SPOT_IO_NativeFileInfo::FIELD__CreationTime   ].SetInteger( (CLR_INT64)fi->CreationTime );
        managedFi[ Library_spot_io_native_Microsoft_SPOT_IO_NativeFileInfo::FIELD__LastAccessTime ].SetInteger( (CLR_INT64)fi->LastAccessTime );
        managedFi[ Library_spot_io_native_Microsoft_SPOT_IO_NativeFileInfo::FIELD__LastWriteTime  ].SetInteger( (CLR_INT64)fi->LastWriteTime );
        managedFi[ Library_spot_io_native_Microsoft_SPOT_IO_NativeFileInfo::FIELD__Size           ].SetInteger( (CLR_INT64)fi->Size );

        TINYCLR_CHECK_HRESULT(ff->CreateFilenameString( managedFi[ Library_spot_io_native_Microsoft_SPOT_IO_NativeFileInfo::FIELD__FileName ] ));
    }
    else
    {
        top.SetObjectReference( NULL );
    }

    TINYCLR_NOCLEANUP();
}
HRESULT Library_spot_io_native_Microsoft_SPOT_IO_NativeFindFile::GetFileInfo___STATIC__MicrosoftSPOTIONativeFileInfo__STRING( CLR_RT_StackFrame& stack )
{
    NATIVE_PROFILE_CLR_IO();
    TINYCLR_HEADER();

    FS_FILEINFO                  fileInfo;
    BOOL                         found;
    UnicodeString                pathW;
    FileSystemVolume*            driver;

    CLR_RT_HeapBlock&            top = stack.PushValueAndClear();

    TINYCLR_CHECK_HRESULT(Library_spot_io_native_Microsoft_SPOT_IO_NativeIO::FindVolume( stack.Arg0(), driver, pathW ));

    TINYCLR_CHECK_HRESULT(driver->GetFileInfo( pathW, &fileInfo, &found ));

    if(found)
    {
        CLR_RT_HeapBlock* managedFi;

        TINYCLR_CHECK_HRESULT(g_CLR_RT_ExecutionEngine.NewObjectFromIndex( top, g_CLR_RT_WellKnownTypes.m_NativeFileInfo ));

        managedFi = top.Dereference();

        managedFi[ Library_spot_io_native_Microsoft_SPOT_IO_NativeFileInfo::FIELD__Attributes     ].SetInteger( (CLR_UINT32)fileInfo.Attributes );
        managedFi[ Library_spot_io_native_Microsoft_SPOT_IO_NativeFileInfo::FIELD__CreationTime   ].SetInteger( (CLR_INT64)fileInfo.CreationTime );
        managedFi[ Library_spot_io_native_Microsoft_SPOT_IO_NativeFileInfo::FIELD__LastAccessTime ].SetInteger( (CLR_INT64)fileInfo.LastAccessTime );
        managedFi[ Library_spot_io_native_Microsoft_SPOT_IO_NativeFileInfo::FIELD__LastWriteTime  ].SetInteger( (CLR_INT64)fileInfo.LastWriteTime );
        managedFi[ Library_spot_io_native_Microsoft_SPOT_IO_NativeFileInfo::FIELD__Size           ].SetInteger( (CLR_INT64)fileInfo.Size );
        managedFi[ Library_spot_io_native_Microsoft_SPOT_IO_NativeFileInfo::FIELD__FileName       ].SetObjectReference( NULL );
    }
    else
    {
        top.SetObjectReference( NULL );
    }

    TINYCLR_NOCLEANUP();
}
HRESULT Library_corlib_native_System_Text_UTF8Encoding::Helper__GetChars(CLR_RT_StackFrame& stack, bool fIndexed)
{
    NATIVE_PROFILE_CLR_CORE();
    TINYCLR_HEADER();

    LPSTR szText;
    CLR_RT_HeapBlock ref;
    ref.SetObjectReference( NULL );
    CLR_RT_ProtectFromGC gc( ref );
    CLR_RT_HeapBlock_Array* pArrayBytes = stack.Arg1().DereferenceArray();
    CLR_INT32               byteIdx     = fIndexed ? stack.Arg2().NumericByRef().s4 : 0;
    CLR_INT32               byteCnt     = fIndexed ? stack.Arg3().NumericByRef().s4 : pArrayBytes->m_numOfElements;
    CLR_RT_HeapBlock_Array* pArrayBytesCopy;
    CLR_RT_HeapBlock_Array* arrTmp;
    int cBytesCopy;

    FAULT_ON_NULL(pArrayBytes);

    _ASSERTE(pArrayBytes->m_typeOfElement == DATATYPE_U1);

    if((byteIdx + byteCnt) > (CLR_INT32)pArrayBytes->m_numOfElements) TINYCLR_SET_AND_LEAVE(CLR_E_OUT_OF_RANGE);

    cBytesCopy = byteCnt+1;

    /* Copy the array to a temporary buffer to create a zero-terminated string */
    TINYCLR_CHECK_HRESULT( CLR_RT_HeapBlock_Array::CreateInstance( ref, cBytesCopy, g_CLR_RT_WellKnownTypes.m_UInt8 ));

    pArrayBytesCopy = ref.DereferenceArray();
    szText = (LPSTR)pArrayBytesCopy->GetFirstElement();

    hal_strncpy_s( szText, cBytesCopy, (LPSTR)pArrayBytes->GetElement(byteIdx), byteCnt );

    TINYCLR_CHECK_HRESULT(Library_corlib_native_System_String::ConvertToCharArray( szText, stack.PushValueAndClear(), arrTmp, 0, -1 ));

    TINYCLR_NOCLEANUP();
}
HRESULT Library_spot_native_Microsoft_SPOT_Reflection::GetTypesImplementingInterface___STATIC__SZARRAY_mscorlibSystemType__mscorlibSystemType( CLR_RT_StackFrame& stack )
{
    NATIVE_PROFILE_CLR_CORE();
    TINYCLR_HEADER();

    CLR_RT_HeapBlock&       top    = stack.PushValueAndClear();
    int                     tot    = 0;
    CLR_RT_HeapBlock*       pArray = NULL;
    CLR_RT_TypeDef_Instance tdMatch;
    CLR_RT_HeapBlock*       hbType = stack.Arg0().Dereference();

    TINYCLR_CHECK_HRESULT(Library_corlib_native_System_RuntimeType::GetTypeDescriptor( *hbType, tdMatch ));

    if((tdMatch.m_target->flags & CLR_RECORD_TYPEDEF::TD_Semantics_Mask) != CLR_RECORD_TYPEDEF::TD_Semantics_Interface)
    {
        TINYCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER);
    }

    for(int pass=0; pass<2; pass++)
    {
        int              count = 0;

        TINYCLR_FOREACH_ASSEMBLY_IN_CURRENT_APPDOMAIN(g_CLR_RT_TypeSystem)
        {
            const CLR_RECORD_TYPEDEF* td      = pASSM->GetTypeDef( 0 );
            int                       tblSize = pASSM->m_pTablesSize[ TBL_TypeDef ];

            for(int i=0; i<tblSize; i++, td++)
            {
                if(td->flags & CLR_RECORD_TYPEDEF::TD_Abstract) continue;

                CLR_RT_TypeDef_Index idx; idx.Set( pASSM->m_idx, i );

                if(CLR_RT_ExecutionEngine::IsInstanceOf( idx, tdMatch ))
                {
                    if(pass == 0)
                    {
                        tot++;
                    }
                    else
                    {
                        CLR_RT_HeapBlock* hbObj;
                        TINYCLR_CHECK_HRESULT(g_CLR_RT_ExecutionEngine.NewObjectFromIndex(pArray[count], g_CLR_RT_WellKnownTypes.m_TypeStatic));
                        hbObj = pArray[count].Dereference();
                        hbObj->SetReflection( idx );
                    }

                    count++;
                }
            }
        }
        TINYCLR_FOREACH_ASSEMBLY_IN_CURRENT_APPDOMAIN_END();

        if(pass == 0)
        {
            if(tot == 0) break;

            TINYCLR_CHECK_HRESULT(CLR_RT_HeapBlock_Array::CreateInstance( top, tot, g_CLR_RT_WellKnownTypes.m_TypeStatic ));

            CLR_RT_HeapBlock_Array* array = top.DereferenceArray();

            pArray = (CLR_RT_HeapBlock*)array->GetFirstElement();
        }
    }


    TINYCLR_NOCLEANUP();
}
HRESULT Library_corlib_native_System_Resources_ResourceManager::GetObjectInternal___OBJECT__I2( CLR_RT_StackFrame& stack )
{
    NATIVE_PROFILE_CLR_CORE();
    TINYCLR_HEADER();

    CLR_RT_Assembly_Instance   assm;
    CLR_UINT32                 size;
    const CLR_RECORD_RESOURCE* resource;
    CLR_RT_Assembly*           pAssm;
    const CLR_UINT8*           buf;
    CLR_RT_HeapBlock*          pThis          =   stack.This();
    CLR_RT_HeapBlock*          pArgs          = &(stack.Arg1());
    CLR_UINT32                 resourceFileId = pThis[ FIELD__m_resourceFileId ].NumericByRefConst().s4; 
    CLR_RT_HeapBlock&          top            = stack.PushValueAndClear();

    //
    // Set up for restart on out of memory.
    //
    if(stack.m_customState == 0)
    {
        stack.m_customState  = 1;
        stack.m_flags       |= CLR_RT_StackFrame::c_CompactAndRestartOnOutOfMemory;
    }

    TINYCLR_CHECK_HRESULT(Library_corlib_native_System_Reflection_Assembly::GetTypeDescriptor( *pThis[ FIELD__m_assembly ].Dereference(), assm ));
    
    TINYCLR_CHECK_HRESULT(g_CLR_RT_TypeSystem.LocateResource( assm, resourceFileId, pArgs[ 0 ].NumericByRefConst().s2, resource, size ));

    if(resource != NULL) //otherwise NULL is returned
    {
        pAssm = assm.m_assm;
        buf = pAssm->GetResourceData( resource->offset );
        
        switch(resource->kind)
        {
        case CLR_RECORD_RESOURCE::RESOURCE_String:
            {
                TINYCLR_SET_AND_LEAVE(CLR_RT_HeapBlock_String::CreateInstance( top, (LPCSTR)buf, pAssm ));
            }
            break;

        case CLR_RECORD_RESOURCE::RESOURCE_Bitmap:
            {
                CLR_RT_HeapBlock*        ptr;

                TINYCLR_CHECK_HRESULT(g_CLR_RT_ExecutionEngine.NewObjectFromIndex( top, g_CLR_RT_WellKnownTypes.m_Bitmap ));

                ptr = top.Dereference();

                TINYCLR_SET_AND_LEAVE(CLR_GFX_Bitmap::CreateInstance( ptr[ CLR_GFX_Bitmap::FIELD__m_bitmap ], buf, size, pAssm ));
            }
            break;

        case CLR_RECORD_RESOURCE::RESOURCE_Font:
            {
                CLR_RT_HeapBlock*        ptr;

                TINYCLR_CHECK_HRESULT(g_CLR_RT_ExecutionEngine.NewObjectFromIndex( top, g_CLR_RT_WellKnownTypes.m_Font ));

                ptr = top.Dereference();

                TINYCLR_SET_AND_LEAVE(CLR_GFX_Font::CreateInstance( ptr[ CLR_GFX_Font::FIELD__m_font ], buf, pAssm ));                
            }
            break;
        case CLR_RECORD_RESOURCE::RESOURCE_Binary:
            {
                TINYCLR_CHECK_HRESULT(CLR_RT_HeapBlock_Array::CreateInstance( top, size, g_CLR_RT_WellKnownTypes.m_UInt8 ));

                memcpy( top.DereferenceArray()->GetFirstElement(), buf, size );
            }
            break;

        default:
            _ASSERTE(false); 
            break;
        }
    }
    
    TINYCLR_NOCLEANUP();
}