diff --git a/.gitattributes b/.gitattributes index 2cca06618f618fea308f619430f4a454f7c3ac09..b70096e3457fb579bad22d3df93b3ce0cacfb88c 100644 --- a/.gitattributes +++ b/.gitattributes @@ -109,3 +109,4 @@ miniCUDA124/lib/x64/nvfatbin_static.lib filter=lfs diff=lfs merge=lfs -text miniCUDA124/bin/cublas64_12.dll filter=lfs diff=lfs merge=lfs -text miniCUDA124/lib/x64/nvrtc-builtins_static.lib filter=lfs diff=lfs merge=lfs -text miniMSVC/VC/Redist/MSVC/14.42.34433/debug_nonredist/x64/Microsoft.VC143.DebugCRT/vccorlib140d.dll filter=lfs diff=lfs merge=lfs -text +miniCUDA124/nvvm/bin/cicc.exe filter=lfs diff=lfs merge=lfs -text diff --git a/miniCUDA124/nvvm/bin/cicc.exe b/miniCUDA124/nvvm/bin/cicc.exe new file mode 100644 index 0000000000000000000000000000000000000000..a20f39ebfc86659a63dc0e5130631ae797320ed9 --- /dev/null +++ b/miniCUDA124/nvvm/bin/cicc.exe @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a5f70fd7076807724c0065cff4bc2f19730b492a6e4556188c56f77fcd3e9a9e +size 28270080 diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vccorlib/tmmta.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vccorlib/tmmta.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c9a1ae35dcacd4c06142384c7ab120ee475208e6 --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vccorlib/tmmta.cpp @@ -0,0 +1,51 @@ +// +// Copyright (C) Microsoft Corporation +// All rights reserved. +// +#include + +// From , which we cannot include here +#define _VCCORLIB_THREADING_MODEL_DEFAULT 0 +#define _VCCORLIB_THREADING_MODEL_STA 1 +#define _VCCORLIB_THREADING_MODEL_MTA 2 +#define _VCCORLIB_THREADING_MODEL_OVERRIDE 3 + +extern int __abi___threading_model; + +// Compiler is pulling in the following symbol: +// INCLUDE:___refMTAThread (decorated x86) to enable MTA +extern "C" int __refMTAThread = 0; + +// External symbol to ensure that only one threading model initializer can be +// linked into a module. If a project uses both Platform::STAThreadAttribute +// and Platform::MTAThreadAttribute, this should cause a link error. +extern "C" int __abi___threading_model_initializer = 0; + +static int __cdecl initialize_threading_model_for_mta() throw() +{ + // If the threading model is 'override', some prior initializer has requested that + // we not initialize the threading model. This feature exists to support the XAML + // designer, which loads EXEs as if they were DLLs, and thus needs to be able to + // suppress our initialization. + if (__abi___threading_model == _VCCORLIB_THREADING_MODEL_OVERRIDE) + { + return 0; + } + + if (__abi___threading_model != _VCCORLIB_THREADING_MODEL_DEFAULT) + { + // If you hit this assertion, this indicates that both Platform::STAThreadAttribute + // and Platform::MTAThreadAttribute were used in your source files and libraries. + // These attributes are mutually exclusive. Search your sources for the attributes + // or link your project with the /verbose option and find which object files caused + // the __refSTAThread and __refMTAThread symbols to be linked into your binary. + _ASSERTE(("__abi___threading_model has already been initialized", 0)); + return 1; + } + + __abi___threading_model = _VCCORLIB_THREADING_MODEL_MTA; + return 0; +} + +#pragma section(".CRT$XIYA", long, read) +__declspec(allocate(".CRT$XIYA")) static auto initializer = initialize_threading_model_for_mta; diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vccorlib/tmsta.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vccorlib/tmsta.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dbdfd6386df2eda18f6c6bd086a5652e6119d922 --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vccorlib/tmsta.cpp @@ -0,0 +1,51 @@ +// +// Copyright (C) Microsoft Corporation +// All rights reserved. +// +#include + +// From , which we cannot include here +#define _VCCORLIB_THREADING_MODEL_DEFAULT 0 +#define _VCCORLIB_THREADING_MODEL_STA 1 +#define _VCCORLIB_THREADING_MODEL_MTA 2 +#define _VCCORLIB_THREADING_MODEL_OVERRIDE 3 + +extern int __abi___threading_model; + +// Compiler is pulling in the following symbol: +// INCLUDE:___refSTAThread (decorated x86) to enable STA +extern "C" int __refSTAThread = 0; + +// External symbol to ensure that only one threading model initializer can be +// linked into a module. If a project uses both Platform::STAThreadAttribute +// and Platform::MTAThreadAttribute, this should cause a link error. +extern "C" int __abi___threading_model_initializer = 0; + +static int __cdecl initialize_threading_model_for_sta() throw() +{ + // If the threading model is 'override', some prior initializer has requested that + // we not initialize the threading model. This feature exists to support the XAML + // designer, which loads EXEs as if they were DLLs, and thus needs to be able to + // suppress our initialization. + if (__abi___threading_model == _VCCORLIB_THREADING_MODEL_OVERRIDE) + { + return 0; + } + + if (__abi___threading_model != _VCCORLIB_THREADING_MODEL_DEFAULT) + { + // If you hit this assertion, this indicates that both Platform::STAThreadAttribute + // and Platform::MTAThreadAttribute were used in your source files and libraries. + // These attributes are mutually exclusive. Search your sources for the attributes + // or link your project with the /verbose option and find which object files caused + // the __refSTAThread and __refMTAThread symbols to be linked into your binary. + _ASSERTE(("__abi___threading_model has already been initialized", 0)); + return 1; + } + + __abi___threading_model = _VCCORLIB_THREADING_MODEL_STA; + return 0; +} + +#pragma section(".CRT$XIYA", long, read) +__declspec(allocate(".CRT$XIYA")) static auto initializer = initialize_threading_model_for_sta; diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vccorlib/type.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vccorlib/type.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d68b5ce555e524786e0ff668cf71501641b12d43 --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vccorlib/type.cpp @@ -0,0 +1,271 @@ +// +// Copyright (C) Microsoft Corporation +// All rights reserved. +// + +#include "pch.h" +#pragma hdrstop + +#pragma warning(disable:4483) + +size_t SafeAdd(size_t left, size_t right) +{ + if (static_cast(-1) - left < right) + { + throw ref new ::Platform::COMException(HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW)); + } + + return left + right; +} + +size_t SafeMultiply(size_t left, size_t right) +{ + if (static_cast(-1) / left < right) + { + throw ref new ::Platform::COMException(HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW)); + } + + return left * right; +} + +struct { + const __wchar_t* typeName; + const __wchar_t* platformName; + ::Platform::TypeCode typeId; + ::Windows::Foundation::PropertyType propertyType; +} primitiveMatchArr[] = { + { L"Boolean", L"Boolean", ::Platform::TypeCode::Boolean , ::Windows::Foundation::PropertyType::Boolean }, + { L"Char16", L"Char16", ::Platform::TypeCode::Char16 , ::Windows::Foundation::PropertyType::Char16 }, + { L"Int8", L"Int8", ::Platform::TypeCode::Int8 , static_cast<::Windows::Foundation::PropertyType>(-1) }, + { L"UInt8", L"UInt8", ::Platform::TypeCode::UInt8 , ::Windows::Foundation::PropertyType::UInt8 }, + { L"Int16", L"Int16", ::Platform::TypeCode::Int16 , ::Windows::Foundation::PropertyType::Int16 }, + { L"UInt16", L"UInt16", ::Platform::TypeCode::UInt16 , ::Windows::Foundation::PropertyType::UInt16 }, + { L"Int32", L"Int32", ::Platform::TypeCode::Int32 , ::Windows::Foundation::PropertyType::Int32 }, + { L"UInt32", L"UInt32", ::Platform::TypeCode::UInt32 , ::Windows::Foundation::PropertyType::UInt32 }, + { L"Int64", L"Int64", ::Platform::TypeCode::Int64 , ::Windows::Foundation::PropertyType::Int64 }, + { L"UInt64", L"UInt64", ::Platform::TypeCode::UInt64 , ::Windows::Foundation::PropertyType::UInt64 }, + { L"Single", L"Single", ::Platform::TypeCode::Single , ::Windows::Foundation::PropertyType::Single }, + { L"Double", L"Double", ::Platform::TypeCode::Double , ::Windows::Foundation::PropertyType::Double }, + { L"String", L"Platform.String", ::Platform::TypeCode::String , ::Windows::Foundation::PropertyType::String }, + { L"Guid", L"Platform.Guid", ::Platform::TypeCode::Guid , ::Windows::Foundation::PropertyType::Guid }, + { L"DateTime", L"Windows.Foundation.DateTime", ::Platform::TypeCode::DateTime , ::Windows::Foundation::PropertyType::DateTime }, + { L"TimeSpan", L"Windows.Foundation.TimeSpan", ::Platform::TypeCode::TimeSpan , ::Windows::Foundation::PropertyType::TimeSpan }, + { L"Point", L"Windows.Foundation.Point", ::Platform::TypeCode::Point , ::Windows::Foundation::PropertyType::Point }, + { L"Rect", L"Windows.Foundation.Rect", ::Platform::TypeCode::Rect , ::Windows::Foundation::PropertyType::Rect }, + { L"Size", L"Windows.Foundation.Size", ::Platform::TypeCode::Size , ::Windows::Foundation::PropertyType::Size }, + { L"Object", L"Platform.Object", ::Platform::TypeCode::Object , ::Windows::Foundation::PropertyType::Inspectable} +}; + +__abi_type_descriptor* CreateDescriptior(const __wchar_t* typeName, int typeId) +{ + size_t len = ::wcslen(typeName); + + len = SafeAdd(len, 4); + + size_t size = SafeMultiply(len, sizeof(__wchar_t)); + size = SafeAdd(size, sizeof(__abi_type_descriptor)); + + __abi_type_descriptor* descriptor = reinterpret_cast<__abi_type_descriptor*>(Platform::Details::Heap::Allocate(size)); + descriptor->__typeName = reinterpret_cast(descriptor + 1); + wcscpy_s( const_cast<__wchar_t*>(descriptor->__typeName), len, typeName); + descriptor->__typeId = typeId; + + return descriptor; +} + +namespace Platform +{ + /* + extern "C" CPPCLI_FUNC void __identifier("?@Type@Platform@@U$AAAXXZ")(Platform::Type^ pThis) + { + // no-op. We don't need 'delete Type' to do anything. + } + */ + + CPPCLI_FUNC void Type::__identifier("")() + { + if (_owndescriptor) + { + Platform::Details::Heap::Free(_descriptor); + } + } + + // Add this back in when non-virtual private destructors are available. + // CPPCLI_FUNC void Type::~Type() + // { + // if (_owndescriptor) + // { + // Platform::Details::Heap::Free(_descriptor); + // } + // } + + CPPCLI_FUNC Type::Type(IntPtr descriptor) : _descriptor( (void *)descriptor ), _owndescriptor(false) + { + } + + CPPCLI_FUNC Type::Type(Windows::UI::Xaml::Interop::TypeName type) : _descriptor(nullptr), _owndescriptor(true) + { + const __wchar_t *typeName = type.Name->Data(); + int typeId = 0; + + switch(type.Kind) + { + case Windows::UI::Xaml::Interop::TypeKind::Metadata: + typeId = static_cast(Platform::TypeCode::Object); + break; + case Windows::UI::Xaml::Interop::TypeKind::Custom: + typeId = static_cast(Platform::TypeCode::Custom); + break; + case Windows::UI::Xaml::Interop::TypeKind::Primitive: + { + for(unsigned int i = 0; i < _countof(primitiveMatchArr); i++) + { + if (::wcscmp(typeName, primitiveMatchArr[i].typeName) == 0) + { + typeId = static_cast(primitiveMatchArr[i].typeId); + typeName = primitiveMatchArr[i].platformName; + break; + } + } + break; + } + default: + throw ref new ::Platform::FailureException(); + } + + _descriptor = CreateDescriptior(typeName, typeId); + } + + CPPCLI_FUNC Type::Type(Object^ obj) : _owndescriptor(true) + { + Windows::Foundation::IPropertyValue^ propertyValue; + ::Platform::Guid gdIPropertyValue(__uuidof(Windows::Foundation::IPropertyValue^)); + HRESULT hr = obj->__abi_QueryInterface(gdIPropertyValue, reinterpret_cast(&propertyValue)); + if (SUCCEEDED(hr)) + { + auto propertyType = propertyValue->Type; + + for (unsigned int i = 0; i < _countof(primitiveMatchArr); i++) + { + if (propertyType == primitiveMatchArr[i].propertyType) + { + _descriptor = CreateDescriptior(primitiveMatchArr[i].platformName, static_cast(primitiveMatchArr[i].typeId)); + return; + } + } + } + + Platform::String^ typeName; + hr = obj->__abi_GetRuntimeClassName(reinterpret_cast(&typeName)); + __abi_ThrowIfFailed(hr); + + int typeId = static_cast(Platform::TypeCode::Object); + + _descriptor = CreateDescriptior(typeName->Data(), typeId); + } + + CPPCLI_FUNC String^ Type::FullName::get() + { + __abi_type_descriptor* descriptor = (__abi_type_descriptor*)(void*)_descriptor; + return ref new String(descriptor->__typeName); + } + + CPPCLI_FUNC TypeCode Type::GetTypeCode(Type^ type) + { + if (type == nullptr) + { + return TypeCode::Empty; + } + + __abi_type_descriptor* descriptor = (__abi_type_descriptor*)(void*)type->_descriptor; + return (TypeCode)descriptor->__typeId; + } + + + CPPCLI_FUNC int32 Type::GetHashCode() + { + return Object::GetHashCode(); + } + + CPPCLI_FUNC String^ Type::ToString() + { + return FullName; + } + + CPPCLI_FUNC bool Type::Equals(Object^ o) + { + Type^ type = dynamic_cast(o); + if (type == nullptr) + { + return this == nullptr; + } + + return _descriptor == type->_descriptor; + } + + CPPCLI_FUNC Platform::Type::operator class Windows::UI::Xaml::Interop::TypeName(class Platform::Type^ type) + { + Windows::UI::Xaml::Interop::TypeName typeName; + typeName.Name = type->FullName; + + switch(::Platform::Type::GetTypeCode(type)) + { + case ::Platform::TypeCode::Empty: + case ::Platform::TypeCode::Object: + case ::Platform::TypeCode::DateTime: + case ::Platform::TypeCode::TimeSpan: + case ::Platform::TypeCode::Point: + case ::Platform::TypeCode::Size: + case ::Platform::TypeCode::Rect: + typeName.Kind = Windows::UI::Xaml::Interop::TypeKind::Metadata; + break; + case ::Platform::TypeCode::Custom: + typeName.Kind = Windows::UI::Xaml::Interop::TypeKind::Custom; + break; + case ::Platform::TypeCode::Boolean: + case ::Platform::TypeCode::Char16: + case ::Platform::TypeCode::Int8: + case ::Platform::TypeCode::UInt8: + case ::Platform::TypeCode::Int16: + case ::Platform::TypeCode::UInt16: + case ::Platform::TypeCode::Int32: + case ::Platform::TypeCode::UInt32: + case ::Platform::TypeCode::Int64: + case ::Platform::TypeCode::UInt64: + case ::Platform::TypeCode::Single: + case ::Platform::TypeCode::Double: + case ::Platform::TypeCode::String: + case ::Platform::TypeCode::Guid: + typeName.Kind = Windows::UI::Xaml::Interop::TypeKind::Primitive; + break; + } + + // Gettting string name from typeName.Name because we hold reference to it + const wchar_t *name = typeName.Name->Data(); + if (name != nullptr) + { + for(unsigned int i = 0; i < _countof(primitiveMatchArr); i++) + { + if (::wcscmp(name, primitiveMatchArr[i].platformName) == 0) + { + typeName.Name = ref new ::Platform::String(primitiveMatchArr[i].typeName); + break; + } + } + } + + return typeName; + } + + CPPCLI_FUNC Platform::Type::operator class Platform::Type ^(class Windows::UI::Xaml::Interop::TypeName typeName) + { + return ref new ::Platform::Type(typeName); + } + +} // namespace Platform + +CPPCLI_FUNC Platform::Type^ __stdcall __abi_make_type_id(const __abi_type_descriptor& typeInfo) +{ + Platform::IntPtr ptr = const_cast<__abi_type_descriptor*>(&typeInfo); + return ref new Platform::Type(ptr); +} diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vccorlib/vccorlib.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vccorlib/vccorlib.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ed8535825060a45b5dff89b598ef2366b5996d57 --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vccorlib/vccorlib.cpp @@ -0,0 +1,116 @@ +// +// Copyright (C) Microsoft Corporation +// All rights reserved. +// +#include "pch.h" + +CPPCLI_FUNC void __stdcall FlushFactoryCache(); +CPPCLI_FUNC void EnableFactoryCache(); +void DisableFactoryCache(); + +__abi_Module* __abi_module = nullptr; + +#include "crtdefs.h" +#include + +__declspec(noreturn) __declspec(dllexport) void __stdcall __abi_FailFast() +{ + _invoke_watson(nullptr, nullptr, nullptr, 0, 0); +} + +namespace Platform { + namespace Details { + + class InternalModule : + public __abi_Module + { + public: + InternalModule() + { + __abi_module = this; + } + + virtual ~InternalModule() + { + __abi_module = nullptr; + } + + virtual unsigned long __stdcall __abi_IncrementObjectCount() + { + return 0; + } + + virtual unsigned long __stdcall __abi_DecrementObjectCount() + { + return 0; + } + }; + +#pragma warning( disable: 4073 ) // initializers put in library initialization area +#pragma init_seg( lib ) + + InternalModule internalModule_; + + VCCORLIB_API HRESULT InitializeData(int threadingModel) + { + if (threadingModel != _VCCORLIB_THREADING_MODEL_DEFAULT) + { + RO_INIT_TYPE initType = threadingModel == _VCCORLIB_THREADING_MODEL_STA + ? static_cast(0) /* RO_INIT_SINGLETHREADED */ + : RO_INIT_MULTITHREADED; + + HRESULT hr = Windows::Foundation::Initialize(initType); + if (FAILED(hr)) + { +#ifdef _DEBUG + if (IsDebuggerPresent()) + { + OutputDebugStringW(L"Call to Windows::Foundation::Initialize failed."); + } +#endif + return hr; + } + + EnableFactoryCache(); + } + return S_OK; + } + + VCCORLIB_API void UninitializeData(int threadingModel) + { + if (threadingModel != 0) + { + DisableFactoryCache(); + Windows::Foundation::Uninitialize(); + } + } + + VCCORLIB_API HRESULT STDMETHODCALLTYPE GetActivationFactory( + _In_ Microsoft::WRL::Details::ModuleBase* module, + _In_ HSTRING pActivatibleClassId, + _Deref_out_ ::IActivationFactory** ppFactory) + { + return Microsoft::WRL::Details::GetActivationFactory(module, nullptr, pActivatibleClassId, ppFactory); + } + + VCCORLIB_API bool STDMETHODCALLTYPE TerminateModule(_In_ Microsoft::WRL::Details::ModuleBase* module) + { + return Microsoft::WRL::Details::TerminateMap(module, nullptr, false); + } + +VCCORLIB_API wchar_t** GetCmdArguments(_Out_ int* argc) +{ + _ASSERTE(argc != nullptr); + + if (_configure_wide_argv(_get_startup_argv_mode()) != 0) + { + *argc = 0; + return nullptr; + } + + *argc = __argc; + return __wargv; +} + + + } } // namespace Platform::Details diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vccorlib/vcwinrt.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vccorlib/vcwinrt.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d8466979d6120d5a8988d6cd7f849f8fe51746a7 --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vccorlib/vcwinrt.cpp @@ -0,0 +1,494 @@ +// +// Copyright (C) Microsoft Corporation +// All rights reserved. +// + +#include "pch.h" +#include +#include +#include +#include +#include "activation.h" +#pragma hdrstop +#include +#include +#include + +using namespace Microsoft::WRL; +using namespace std; + +struct conditional_deleter +{ + conditional_deleter(bool bDelete = true) : _bDelete(bDelete) + { + } + conditional_deleter(const conditional_deleter& other) : _bDelete(other._bDelete) + { + } + conditional_deleter(conditional_deleter&& other) : _bDelete(other._bDelete) + { + other._bDelete = true; + } + conditional_deleter& operator=(conditional_deleter other) + { + _bDelete = other._bDelete; + } + void operator()(const wchar_t* p) + { + if (_bDelete) + { + delete p; // TRANSITION, should be delete[] + } + return; + } +private: + bool _bDelete; +}; + +template +struct hash_unique_wchar +{ + size_t operator()(const unique_ptr& ele) const + { + const wstring_view sv{ele.get()}; + return hash{}(sv); + } +}; + +template +struct equal_unique_wchar +{ + bool operator()(const unique_ptr& first, const unique_ptr& second) const + { + return wcscmp(first.get(), second.get()) == 0; + } +}; + +CPPCLI_FUNC HRESULT __stdcall __getActivationFactoryByHSTRING(HSTRING str, ::Platform::Guid& riid, PVOID * ppActivationFactory) +{ + HRESULT hr = S_OK; + IActivationFactory* pActivationFactory; + hr = Windows::Foundation::GetActivationFactory(str, &pActivationFactory); + if (SUCCEEDED(hr)) + { + hr = pActivationFactory->QueryInterface(reinterpret_cast(riid), ppActivationFactory); + pActivationFactory->Release(); + } + + return hr; +} + +class PerApartmentFactoryCache : public RuntimeClass, IApartmentShutdown, FtmBase> +{ + UINT64 _apartmentId; +protected: + typedef unique_ptr ActivatableID; // TRANSITION, should be const wchar_t[] +private: + unordered_map, + hash_unique_wchar, + equal_unique_wchar> _factoryCache; +protected: + virtual HRESULT AddFactoryInternal(std::pair > &&entry) + { + auto ret = _factoryCache.insert(std::move(entry)); + if (ret.second == false) + { + return S_FALSE; + } + + return S_OK; + } + + virtual HRESULT GetFactoryInternal(const wchar_t* acid, Platform::Guid& iid, void** pFactory, bool& addToCache) + { + __WRL_ASSERT__(addToCache == true); // The default value for addToCache should be true + + *pFactory = nullptr; + // Don't delete buffer + ActivatableID activatableID(acid, false); + auto it = _factoryCache.find(std::move(activatableID)); + if (it == _factoryCache.end()) + { + return E_FAIL; + } + + // The factory pointer is nullptr only + // in case that the factory has proxy + IUnknown* unk = it->second.Get(); + if (unk == nullptr) + { + addToCache = false; + return E_FAIL; + } + + return unk->QueryInterface(iid, pFactory); + } +public: + HRESULT RuntimeClassInitialize(UINT64 appartmentId) + { + _apartmentId = appartmentId; + return S_OK; + } + + HRESULT AddFactory(const wchar_t* acid, IUnknown *factory) + { + try + { + auto len = wcslen(acid) + 1; + wchar_t* acidCopy = new wchar_t[len]; + wcscpy_s(acidCopy, len, acid); + ActivatableID activatableID(acidCopy); + + ComPtr multiQI; + // In case of OOP component there is possibility of RPC errors + // that can result in cache poisoning as there is no easy way + // to detect that the factory encounterd RPC errors. + // The QI for IMultiQI allows us to identify the proxy stub for OOP component + if (factory->QueryInterface(__uuidof(::IMultiQI), &multiQI) == S_OK) + { + // Insert empty marker to indicate that it's out of proc factory + return AddFactoryInternal(make_pair(std::move(activatableID), nullptr)); + } + else + { + ComPtr unk = factory; + return AddFactoryInternal(make_pair(std::move(activatableID), std::move(unk))); + } + } + catch (const bad_alloc&) + { + return E_OUTOFMEMORY; + } + catch (const exception&) + { + return E_FAIL; + } + } + + // addToCache parameter prevents from adding the factory into the cache + // this is used for MTA appartment to reduce contention + HRESULT GetFactory(const wchar_t* acid, Platform::Guid& iid, void** pFactory, bool& addToCache) + { + *pFactory = nullptr; + try + { + return GetFactoryInternal(acid, iid, pFactory, addToCache); + } + catch (const bad_alloc&) + { + return E_OUTOFMEMORY; + } + } + + void __stdcall OnUninitialize(UINT64 apartmentIdentifier); +}; + +static bool IsMTA() +{ + APTTYPE AptType; + APTTYPEQUALIFIER AptQualifier; + HRESULT hr = CoGetApartmentType(&AptType, &AptQualifier); + if (SUCCEEDED(hr) && (AptType == APTTYPE::APTTYPE_MTA || AptType == APTTYPE::APTTYPE_NA)) + { + return true; + } + else + { + return false; + } +} + +class PerApartmentFactoryCacheMTA : public PerApartmentFactoryCache +{ + Wrappers::SRWLock _SRWLock; +protected: + virtual HRESULT AddFactoryInternal(std::pair > &&entry) + { + __WRL_ASSERT__(IsMTA()); + + // Lock exclusive on addition so we always make sure that we cache the value + auto lock = _SRWLock.LockExclusive(); + return PerApartmentFactoryCache::AddFactoryInternal(std::move(entry)); + } + + virtual HRESULT GetFactoryInternal(const wchar_t* acid, Platform::Guid& iid, void** pFactory, bool& addToCache) + { + __WRL_ASSERT__(IsMTA()); + + // If we cannot access cache because of addition or deletion + // vccorlib will call windows to create new factory + auto lock = _SRWLock.TryLockShared(); + if (!lock.IsLocked()) + { + // The lock couldn't be taken so there must be either addition or removal happening + // in this case we will not try to put the factory to the cache + addToCache = false; + return E_FAIL; + } + + return PerApartmentFactoryCache::GetFactoryInternal(acid, iid, pFactory, addToCache); + } +}; + +static HRESULT CreateFactoryCache(PerApartmentFactoryCache** pFactory, UINT64 apartmentID) +{ + if (IsMTA()) + { + return MakeAndInitialize(reinterpret_cast(pFactory), apartmentID); + } + else + { + return MakeAndInitialize(pFactory, apartmentID); + } +} + +class FactoryCache +{ + vector>>> perApartmentCache; + Wrappers::CriticalSection _criticalSection; + static volatile long _cacheEnabled; + static volatile long _cacheDestroyed; +public: + static void Enable() + { + ::_InterlockedCompareExchange(&_cacheEnabled, 1, 0); + } + static void Disable() + { + ::_InterlockedCompareExchange(&_cacheEnabled, 0, 1); + } + static bool IsEnabled() + { + return (_cacheEnabled == 1); + } + static bool IsDestroyed() + { + return (_cacheDestroyed != 0); + } + + ~FactoryCache() + { + Disable(); + ::_InterlockedIncrement(&_cacheDestroyed); + Flush(); + } + void Flush() + { + auto lock = _criticalSection.Lock(); + for(auto it = perApartmentCache.begin(); it != perApartmentCache.end(); it++) + { + // Ignore any failures when unregistering cookies as there's nothing else we can do + (void) ::RoUnregisterForApartmentShutdown(it->second.first); + + // Leak all per apartment factory cache as during shutdown + // we may try to release the factories in the wrong context + it->second.second.Detach(); + } + perApartmentCache.clear(); + } + HRESULT GetFactory(LPCWSTR acid, Platform::Guid& iid, void** pFactory) + { + UINT64 apartmentID; + bool addToCache = true; + + HRESULT hr = ::RoGetApartmentIdentifier(&apartmentID); + ComPtr apartmentCache; + if (SUCCEEDED(hr) && IsEnabled()) + { + auto lock = _criticalSection.Lock(); + for(auto it = perApartmentCache.begin(); it != perApartmentCache.end(); it++) + { + if (it->first == apartmentID) + { + apartmentCache = it->second.second; + lock.Unlock(); + hr = apartmentCache->GetFactory(acid, iid, pFactory, addToCache); + if (SUCCEEDED(hr)) + { + return hr; + } + break; + } + } + if (apartmentCache == nullptr) + { + hr = CreateFactoryCache(&apartmentCache, apartmentID); + if (SUCCEEDED(hr)) + { + UINT64 regAppartmentId; + APARTMENT_SHUTDOWN_REGISTRATION_COOKIE regCookie; + hr = ::RoRegisterForApartmentShutdown(apartmentCache.Get(), ®AppartmentId, ®Cookie); + if (SUCCEEDED(hr)) + { + __WRL_ASSERT__(regAppartmentId == apartmentID); + perApartmentCache.push_back(pair>> + (apartmentID, pair>(regCookie, apartmentCache.Get()))); + } + } + } + } + + // Create Factory + HSTRING className; + HSTRING_HEADER classNameHeader; + hr = ::WindowsCreateStringReference(acid, static_cast(wcslen(acid)), &classNameHeader, &className); + if (FAILED(hr)) + { + return hr; + } + + ComPtr factory; + Platform::Guid riidUnknown(__uuidof(IUnknown)); + hr = __getActivationFactoryByHSTRING(className, riidUnknown, &factory); + + ::WindowsDeleteString(className); + + if (FAILED(hr)) + { + return hr; + } + + if (apartmentCache != nullptr && addToCache) + { + apartmentCache->AddFactory(acid, factory.Get()); + } + + return factory.CopyTo(iid, pFactory); + } + + void RemoveApartmentCache(UINT64 apartmentIdentifier) + { + auto lock = _criticalSection.Lock(); + + for(auto it = perApartmentCache.begin(); it != perApartmentCache.end(); it++) + { + if (it->first == apartmentIdentifier) + { + perApartmentCache.erase(it); + break; + } + } + } +}; + +volatile long FactoryCache::_cacheEnabled = 0; +volatile long FactoryCache::_cacheDestroyed = 0; +FactoryCache g_FactoryCache; + +void __stdcall PerApartmentFactoryCache::OnUninitialize(UINT64 apartmentIdentifier) +{ + if (apartmentIdentifier == _apartmentId) + { + g_FactoryCache.RemoveApartmentCache(apartmentIdentifier); + } +} + +CPPCLI_FUNC void EnableFactoryCache() +{ + FactoryCache::Enable(); +} + +void DisableFactoryCache() +{ + FactoryCache::Disable(); +} + +CPPCLI_FUNC void __stdcall FlushFactoryCache() +{ + if (!FactoryCache::IsDestroyed()) + { + g_FactoryCache.Flush(); + } +} + +CPPCLI_FUNC HRESULT __stdcall GetActivationFactoryByPCWSTR(void* str, ::Platform::Guid& riid, void** ppActivationFactory) +{ + wchar_t* acid = static_cast(str); + if (!FactoryCache::IsEnabled()) + { + HSTRING className; + HSTRING_HEADER classNameHeader; + HRESULT hr = ::WindowsCreateStringReference(acid, static_cast(wcslen(acid)), &classNameHeader, &className); + if (SUCCEEDED(hr)) + { + hr = __getActivationFactoryByHSTRING(className, riid, ppActivationFactory); + ::WindowsDeleteString(className); + } + return hr; + } + return g_FactoryCache.GetFactory(acid, riid, ppActivationFactory); +} + +CPPCLI_FUNC HRESULT __stdcall GetIidsFn(int nIids, unsigned long* iidCount, const __s_GUID* pIids, ::Platform::Guid** ppDuplicated) +{ + int nBytes = nIids * sizeof(::Platform::Guid); + + *ppDuplicated = (::Platform::Guid*)CoTaskMemAlloc(nBytes); + if (*ppDuplicated) + { + memcpy(*ppDuplicated, pIids, nBytes); + *iidCount = nIids; + return S_OK; + } + + *iidCount = 0; + return E_OUTOFMEMORY; +} + +#include "compiler.cpp" +#include "activation.cpp" + + +#pragma warning( disable: 4073 ) // initializers put in library initialization area +#pragma init_seg( lib ) + +#include "ehdata.h" +extern "C" void __cdecl _SetWinRTOutOfMemoryExceptionCallback(PGETWINRT_OOM_EXCEPTION pCallback); + +namespace Platform { namespace Details { + extern bool __abi_firstAlloc; + extern bool __abi_is_global_oom_init; + extern void* __abi_oom_controlblock; + extern IUnknown* __abi_oom_singleton; +} } + +void* __stdcall GetOutOfMemoryExceptionCallback() +{ + Platform::Details::__abi_oom_singleton->AddRef(); + return Platform::Details::__abi_oom_singleton; +} + +class CInitExceptions +{ +public: + CInitExceptions() + { + // Ignore the effect on the ref new below on __abi_firstAlloc. + bool wasFirstAlloc = Platform::Details::__abi_firstAlloc; + + Platform::Details::__abi_is_global_oom_init = true; + + // Would take down the process if it throws. This is fine. + Platform::OutOfMemoryException^ oom = ref new Platform::OutOfMemoryException(); + + Platform::Details::__abi_is_global_oom_init = false; + + // Recover firstalloc, so that user can set TrackingLevel in main. + Platform::Details::__abi_firstAlloc = wasFirstAlloc; + + Platform::Details::__abi_oom_singleton = reinterpret_cast(oom); + Platform::Details::__abi_oom_singleton->AddRef(); + + _SetWinRTOutOfMemoryExceptionCallback(GetOutOfMemoryExceptionCallback); + } + + ~CInitExceptions() + { + _SetWinRTOutOfMemoryExceptionCallback(nullptr); + Platform::Details::__abi_oom_singleton->Release(); + } +}; + +CInitExceptions initExceptions; diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vccorlib/weakreference.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vccorlib/weakreference.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bd5c2ca8de7cb09462681604dac088f58f13d75c --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vccorlib/weakreference.cpp @@ -0,0 +1,112 @@ +// +// Copyright (C) Microsoft Corporation +// All rights reserved. +// + +#include "pch.h" +#pragma hdrstop + +namespace Platform { namespace Details { + + VCCORLIB_API void ControlBlock::ReleaseTarget() + { + // called by __abi_release after calling the destructor of object + if (!__bSingleAllocation && __strongRefCount < 0 && __target != nullptr) + { + if (__bAlignedAllocation) + { + if (__bExceptionAllocation) + { + ::Platform::Details::Heap::AlignedFreeException(__target); + } + else + { + ::Platform::Details::Heap::AlignedFree(__target); + } + } + else + { + if (__bExceptionAllocation) + { + ::Platform::Details::Heap::FreeException(__target); + } + else + { + ::Platform::Details::Heap::Free(__target); + } + } + __target = nullptr; + } + } + + VCCORLIB_API long __stdcall ControlBlock::__abi_Resolve(::Platform::Guid& __riid, __abi_IInspectable ** __objectReference) + { + for(;;) + { + long __ref = __strongRefCount; + if (__ref <= 0) + { + return 0; + } + + // InterlockedCompareExchange calls _InterlockedCompareExchange intrinsic thus we call directly _InterlockedCompareExchange to save the call + if (::_InterlockedCompareExchange(&__strongRefCount, __ref + 1, __ref) == __ref) + { + break; + } + } + + long __hr = __target->__abi_QueryInterface(__riid, reinterpret_cast(__objectReference)); + + // Undo the "addref" that happened above during the _InterlockedCompareExchange call + __target->__abi_Release(); + + return __hr; + } + + // Object has a reference to control block + VCCORLIB_API void ControlBlock::InitControlBlock(void* __object, bool __bSingleAllocationParam, bool __bAlignedAllocationParam, bool __bExceptionAllocationParam) + { + __vtable_initialize(ControlBlock); + __weakRefCount = 1; + __strongRefCount = 1; + __target = reinterpret_cast<__abi_IUnknown*>(__object); + __bSingleAllocation = __bSingleAllocationParam; + __bAlignedAllocation = __bAlignedAllocationParam; + __bExceptionAllocation = __bExceptionAllocationParam; + } + +#pragma warning(push) +#pragma warning(disable: 4400) + VCCORLIB_API __abi_IUnknown* __stdcall GetWeakReference(const volatile Platform::Object^ const other) +#pragma warning(pop) + { + if (other == nullptr) + { + throw ref new ::Platform::InvalidArgumentException(); + } + + Microsoft::WRL::WeakRef ref; + HRESULT hr = Microsoft::WRL::AsWeak(reinterpret_cast(const_cast(other)), &ref); + __abi_ThrowIfFailed(hr); + + return reinterpret_cast<__abi_IUnknown*>(ref.Detach()); + } + + VCCORLIB_API + __declspec(no_refcount) + ::Platform::Object^ __stdcall ResolveWeakReference(const ::_GUID& guid, __abi_IUnknown** weakRef) + { + ::Platform::Object ^strongRef = nullptr; + + if (*weakRef != nullptr) + { + Microsoft::WRL::WeakRef *ref = reinterpret_cast(weakRef); + HRESULT hr = ref->CopyTo(guid, reinterpret_cast(&strongRef)); + __abi_ThrowIfFailed(hr); + } + + return strongRef; + } + +} } // namesapce Platform::Details diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vccorlib/winmain.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vccorlib/winmain.cpp new file mode 100644 index 0000000000000000000000000000000000000000..44113067c70016882ec3acc91390691ea71fadfb --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vccorlib/winmain.cpp @@ -0,0 +1,13 @@ +// +// Copyright (C) Microsoft Corporation +// All rights reserved. +// + +#include "pch.h" + +int __cdecl _main(); + +int CALLBACK WinMain(_In_ HINSTANCE, _In_opt_ HINSTANCE, _In_ LPSTR, _In_ int) +{ + return _main(); +} diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/ManagedMain.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/ManagedMain.cpp new file mode 100644 index 0000000000000000000000000000000000000000..04d74a002833b4b99be479f0ba567e0d4ace45a5 --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/ManagedMain.cpp @@ -0,0 +1,28 @@ +/*** +*ManagedMain.cpp - Initialization for Windows EXE using CRT DLL and managed entry point +* +* Copyright (c) Microsoft Corporation. All rights reserved. +* +*Purpose: +* This is the startup routine for applications using the managed entry +* point int __clrcall main(array^). +* It calls the user's main routine after performing C Run-Time Library initialization. +* +*******************************************************************************/ + +#define _MANAGED_MAIN + +#define WPRFLAG 1 /* Flag used by startup code to indicate wide strings */ + +#ifndef _UNICODE +#define _UNICODE 1 +#endif /* _UNICODE */ + +#ifndef UNICODE +#define UNICODE 1 +#endif /* UNICODE */ + +#undef _MBCS /* UNICODE not _MBCS */ + + +#include "mcrtexe.cpp" diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/app_appinit.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/app_appinit.cpp new file mode 100644 index 0000000000000000000000000000000000000000..49f442cbfae7722359dcafee9153e2bfb6da9137 --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/app_appinit.cpp @@ -0,0 +1,19 @@ +// +// app_appinit.cpp +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// This object is part of the import library for the Windows Store app CRT. It +// coordinates the call to RoInitialize with vccorlib, to ensure that either +// vccorlib or the CRT (but not both) call RoInitialize. This object is linked +// into the client app if and only if it does not use vccorlib. +// +#include + + + +extern "C" int __crtWinrtInitType = RO_INIT_MULTITHREADED; + + + +#pragma detect_mismatch("vccorlib_lib_should_be_specified_before_msvcrt_lib_to_linker", "0") diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/argv_mode.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/argv_mode.cpp new file mode 100644 index 0000000000000000000000000000000000000000..951638c66951e2abccf6b9df3583be839f242908 --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/argv_mode.cpp @@ -0,0 +1,16 @@ +// +// argv_mode.cpp +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// Gets the default argv population mode, used during executable startup. This +// behavior is overridable at link-time by linking with one of the link options. +// +#include + + + +extern "C" _crt_argv_mode __CRTDECL _get_startup_argv_mode() +{ + return _crt_argv_unexpanded_arguments; +} diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/c11_atomic_support.c b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/c11_atomic_support.c new file mode 100644 index 0000000000000000000000000000000000000000..729e2e4da223ff58843d3cd1e456d0d8bff355a7 --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/c11_atomic_support.c @@ -0,0 +1,150 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// C11 atomic support routines: extern inline definitions +#include + +extern inline void _Check_memory_order(const unsigned int _Order); +extern inline void _Atomic_thread_fence(const unsigned int _Order); + +extern inline void _Atomic_lock_acquire(volatile long* _Spinlock); +extern inline void _Atomic_lock_release(volatile long* _Spinlock); + +extern inline void _Atomic_signal_fence(int _Order); +extern inline _Bool _Atomic_is_lock_free(size_t _Sz); + +extern inline void _Atomic_store8(volatile char* _Ptr, char _Desired, int _Order); +extern inline void _Atomic_store16(volatile short* _Ptr, short _Desired, int _Order); +extern inline void _Atomic_store32(volatile int* _Ptr, int _Desired, int _Order); +extern inline void _Atomic_store64(volatile long long* _Ptr, long long _Desired, int _Order); +extern inline void _Atomic_storef(volatile float* _Ptr, float _Desired, int _Order); +extern inline void _Atomic_stored(volatile double* _Ptr, double _Desired, int _Order); + +extern inline char _Atomic_load8(const volatile char* _Ptr, int _Order); +extern inline short _Atomic_load16(const volatile short* _Ptr, int _Order); +extern inline int _Atomic_load32(const volatile int* _Ptr, int _Order); +extern inline long long _Atomic_load64(const volatile long long* _Ptr, int _Order); +extern inline float _Atomic_loadf(const volatile float* _Ptr, int _Order); +extern inline double _Atomic_loadd(const volatile double* _Ptr, int _Order); + +extern inline _Bool _Atomic_compare_exchange_strong8(volatile char* _Ptr, char* _Expected, char _Desired, int _Order); +extern inline _Bool _Atomic_compare_exchange_strong16( + volatile short* _Ptr, short* _Expected, short _Desired, int _Order); +extern inline _Bool _Atomic_compare_exchange_strong32(volatile int* _Ptr, int* _Expected, int _Desired, int _Order); +extern inline _Bool _Atomic_compare_exchange_strong64( + volatile long long* _Ptr, long long* _Expected, long long _Desired, int _Order); +extern inline _Bool _Atomic_compare_exchange_strongf(volatile float* _Ptr, float* _Expected, float _Desired, int _Order); +extern inline _Bool _Atomic_compare_exchange_strongd( + volatile double* _Ptr, double* _Expected, double _Desired, int _Order); + +extern inline char _Atomic_exchange8(volatile char* _Ptr, int _Desired, int _Order); +extern inline short _Atomic_exchange16(volatile short* _Ptr, int _Desired, int _Order); +extern inline int _Atomic_exchange32(volatile int* _Ptr, int _Desired, int _Order); +extern inline long long _Atomic_exchange64(volatile long long* _Ptr, long long _Desired, int _Order); +extern inline float _Atomic_exchangef(volatile float* _Ptr, float _Desired, int _Order); +extern inline double _Atomic_exchanged(volatile double* _Ptr, double _Desired, int _Order); + +extern inline char _Atomic_fetch_add8(volatile char* _Ptr, int val, int _Order); +extern inline short _Atomic_fetch_add16(volatile short* _Ptr, int val, int _Order); +extern inline int _Atomic_fetch_add32(volatile int* _Ptr, int val, int _Order); +extern inline long long _Atomic_fetch_add64(volatile long long* _Ptr, long long val, int _Order); +extern inline float _Atomic_fetch_addf(volatile float* _Ptr, float val, int _Order); +extern inline double _Atomic_fetch_addd(volatile double* _Ptr, double val, int _Order); + +extern inline char _Atomic_add_fetch8(volatile char* _Ptr, int val, int _Order); +extern inline short _Atomic_add_fetch16(volatile short* _Ptr, int val, int _Order); +extern inline int _Atomic_add_fetch32(volatile int* _Ptr, int val, int _Order); +extern inline long long _Atomic_add_fetch64(volatile long long* _Ptr, long long val, int _Order); +extern inline float _Atomic_add_fetchf(volatile float* _Ptr, float val, int _Order); +extern inline double _Atomic_add_fetchd(volatile double* _Ptr, double val, int _Order); + +extern inline char _Atomic_fetch_sub8(volatile char* _Ptr, int val, int _Order); +extern inline short _Atomic_fetch_sub16(volatile short* _Ptr, int val, int _Order); +extern inline int _Atomic_fetch_sub32(volatile int* _Ptr, int val, int _Order); +extern inline long long _Atomic_fetch_sub64(volatile long long* _Ptr, long long val, int _Order); +extern inline float _Atomic_fetch_subf(volatile float* _Ptr, float val, int _Order); +extern inline double _Atomic_fetch_subd(volatile double* _Ptr, double val, int _Order); + +extern inline char _Atomic_sub_fetch8(volatile char* _Ptr, int val, int _Order); +extern inline short _Atomic_sub_fetch16(volatile short* _Ptr, int val, int _Order); +extern inline int _Atomic_sub_fetch32(volatile int* _Ptr, int val, int _Order); +extern inline long long _Atomic_sub_fetch64(volatile long long* _Ptr, long long val, int _Order); +extern inline float _Atomic_sub_fetchf(volatile float* _Ptr, float val, int _Order); +extern inline double _Atomic_sub_fetchd(volatile double* _Ptr, double val, int _Order); + +extern inline char _Atomic_fetch_and8(volatile char* _Ptr, int val, int _Order); +extern inline short _Atomic_fetch_and16(volatile short* _Ptr, int val, int _Order); +extern inline int _Atomic_fetch_and32(volatile int* _Ptr, int val, int _Order); +extern inline long long _Atomic_fetch_and64(volatile long long* _Ptr, long long val, int _Order); + +extern inline char _Atomic_and_fetch8(volatile char* _Ptr, int val, int _Order); +extern inline short _Atomic_and_fetch16(volatile short* _Ptr, int val, int _Order); +extern inline int _Atomic_and_fetch32(volatile int* _Ptr, int val, int _Order); +extern inline long long _Atomic_and_fetch64(volatile long long* _Ptr, long long val, int _Order); + +extern inline char _Atomic_fetch_or8(volatile char* _Ptr, int val, int _Order); +extern inline short _Atomic_fetch_or16(volatile short* _Ptr, int val, int _Order); +extern inline int _Atomic_fetch_or32(volatile int* _Ptr, int val, int _Order); +extern inline long long _Atomic_fetch_or64(volatile long long* _Ptr, long long val, int _Order); + +extern inline char _Atomic_or_fetch8(volatile char* _Ptr, int val, int _Order); +extern inline short _Atomic_or_fetch16(volatile short* _Ptr, int val, int _Order); +extern inline int _Atomic_or_fetch32(volatile int* _Ptr, int val, int _Order); +extern inline long long _Atomic_or_fetch64(volatile long long* _Ptr, long long val, int _Order); + +extern inline char _Atomic_fetch_xor8(volatile char* _Ptr, int val, int _Order); +extern inline short _Atomic_fetch_xor16(volatile short* _Ptr, int val, int _Order); +extern inline int _Atomic_fetch_xor32(volatile int* _Ptr, int val, int _Order); +extern inline long long _Atomic_fetch_xor64(volatile long long* _Ptr, long long val, int _Order); + +extern inline char _Atomic_xor_fetch8(volatile char* _Ptr, int val, int _Order); +extern inline short _Atomic_xor_fetch16(volatile short* _Ptr, int val, int _Order); +extern inline int _Atomic_xor_fetch32(volatile int* _Ptr, int val, int _Order); +extern inline long long _Atomic_xor_fetch64(volatile long long* _Ptr, long long val, int _Order); + +extern inline char _Atomic_mult_fetch8(volatile char* _Ptr, int val, int _Order); +extern inline short _Atomic_mult_fetch16(volatile short* _Ptr, int val, int _Order); +extern inline int _Atomic_mult_fetch32(volatile int* _Ptr, int val, int _Order); +extern inline long long _Atomic_mult_fetch64(volatile long long* _Ptr, long long val, int _Order); +extern inline float _Atomic_mult_fetchf(volatile float* _Ptr, float val, int _Order); +extern inline double _Atomic_mult_fetchd(volatile double* _Ptr, double val, int _Order); + +extern inline unsigned char _Atomic_div_fetch8(volatile unsigned char* _Ptr, unsigned int val, int _Order); +extern inline unsigned short _Atomic_div_fetch16(volatile unsigned short* _Ptr, unsigned int val, int _Order); +extern inline unsigned int _Atomic_div_fetch32(volatile unsigned int* _Ptr, unsigned int val, int _Order); +extern inline unsigned long long _Atomic_div_fetch64( + volatile unsigned long long* _Ptr, unsigned long long val, int _Order); +extern inline float _Atomic_div_fetchf(volatile float* _Ptr, float val, int _Order); +extern inline double _Atomic_div_fetchd(volatile double* _Ptr, double val, int _Order); + +extern inline signed char _Atomic_idiv_fetch8(volatile char* _Ptr, int val, int _Order); +extern inline short _Atomic_idiv_fetch16(volatile short* _Ptr, int val, int _Order); +extern inline int _Atomic_idiv_fetch32(volatile int* _Ptr, int val, int _Order); +extern inline long long _Atomic_idiv_fetch64(volatile long long* _Ptr, long long val, int _Order); + +extern inline char _Atomic_shl_fetch8(volatile char* _Ptr, int val, int _Order); +extern inline short _Atomic_shl_fetch16(volatile short* _Ptr, int val, int _Order); +extern inline int _Atomic_shl_fetch32(volatile int* _Ptr, int val, int _Order); +extern inline long long _Atomic_shl_fetch64(volatile long long* _Ptr, long long val, int _Order); + +extern inline char _Atomic_shr_fetch8(volatile char* _Ptr, int val, int _Order); +extern inline short _Atomic_shr_fetch16(volatile short* _Ptr, int val, int _Order); +extern inline int _Atomic_shr_fetch32(volatile int* _Ptr, int val, int _Order); +extern inline long long _Atomic_shr_fetch64(volatile long long* _Ptr, long long val, int _Order); + +extern inline signed char _Atomic_imod_fetch8(volatile char* _Ptr, int val, int _Order); +extern inline short _Atomic_imod_fetch16(volatile short* _Ptr, int val, int _Order); +extern inline int _Atomic_imod_fetch32(volatile int* _Ptr, int val, int _Order); +extern inline long long _Atomic_imod_fetch64(volatile long long* _Ptr, long long val, int _Order); + +extern inline unsigned char _Atomic_mod_fetch8(volatile unsigned char* _Ptr, unsigned int val, int _Order); +extern inline unsigned short _Atomic_mod_fetch16(volatile unsigned short* _Ptr, unsigned int val, int _Order); +extern inline unsigned int _Atomic_mod_fetch32(volatile unsigned int* _Ptr, unsigned int val, int _Order); +extern inline unsigned long long _Atomic_mod_fetch64( + volatile unsigned long long* _Ptr, unsigned long long val, int _Order); + +extern inline void _Atomic_lock_and_store(volatile void* _Obj, const void* _Desired, int _Offset, size_t _Size); +extern inline void _Atomic_lock_and_load(volatile void* _Obj, void* _Dest, int _Offset, size_t _Size); +extern inline void _Atomic_lock_and_exchange( + volatile void* _Obj, const void* _Desired, void* _Dest, int _Offset, size_t _Size); +extern inline _Bool _Atomic_lock_and_compare_exchange_strong( + volatile void* _Obj, void* _Expected, const void* _Desired, int _Offset, size_t _Size); diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/checkcfg.c b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/checkcfg.c new file mode 100644 index 0000000000000000000000000000000000000000..42924e22b10f50bfc2448af9031eb50fc357a676 --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/checkcfg.c @@ -0,0 +1,70 @@ +/*** +*checkcfg.c - logic and globals to support the Guard security feature +* +* Copyright (c) Microsoft Corporation. All rights reserved. +* +*Purpose: +* Define the globals and default check routine for the Guard security +* feature. +* +* N.B. Code and data declared by this module must be in the form of +* selectany COMDATs, so that duplicate definitions between the +* CRT and no_cfg_support are permitted for the restricted use +* cases of the no_cfg_support module. +* +*******************************************************************************/ + +#if defined(_M_ARM64) || defined(_M_ARM64EC) +// the codegen from the C version of this breaks ABI on ARM64 +#error "This file should not be built on ARM64" +#endif + +#include + +extern PVOID __guard_check_icall_fptr; + +typedef +void +(__fastcall *GUARDCF_CHECK_ROUTINE) ( + uintptr_t Target + ); + +#pragma warning(suppress: 4918) // 'y' is not necessarily supported on all architectures +BEGIN_PRAGMA_OPTIMIZE_ENABLE("y", DevDivVSO:162582, "Required to avoid poor codegen") + +extern +__declspec(guard(ignore)) +__inline +void +__fastcall +_guard_check_icall ( + _In_ uintptr_t Target + ) + +/*++ + +Routine Description: + + This function performs an ICall check when invoked by the compiler to + check the integrity of a function pointer for Control Flow Guard (/guard). + + N.B. This function is only retained for compatibility with pre-17.1 LKG4 + compilers that do not directly invoke through the + __guard_check_icall_fptr function pointer. + +Arguments: + + Target - Supplies the function pointer to check. + +Return Value: + + None. If the function pointer supplied was invalid, then a fast fail event + or an access violation is raised. + +--*/ + +{ + + ((GUARDCF_CHECK_ROUTINE)__guard_check_icall_fptr)(Target); + return; +} diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/commit_mode.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/commit_mode.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9e8ce415b4d3e73b7a5bf2b28edff613133bf39f --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/commit_mode.cpp @@ -0,0 +1,16 @@ +// +// commit_mode.cpp +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// Gets the default commit mode, used during executable startup. This behavior +// is overridable at link-time by linking with one of the link options. +// +#include + + + +extern "C" int __CRTDECL _get_startup_commit_mode() +{ + return 0; // No commit +} diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/debugger_jmc.c b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/debugger_jmc.c new file mode 100644 index 0000000000000000000000000000000000000000..5f55cdb96a345b9d44929b513124cce6f6243a26 --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/debugger_jmc.c @@ -0,0 +1,29 @@ +/*** +*debugger_jmc.c +* +* Copyright (c) Microsoft Corporation. All rights reserved. +* +*Purpose: +* Define the helper function for VS debugger Just My Code stepping feature. +* +*******************************************************************************/ + +#include +#include + +#pragma warning( disable : 4102 ) +#pragma warning( disable : 4189 ) + +#pragma optimize( "", off ) + +__declspec(selectany) DWORD __DebuggerCurrentSteppingThreadId; + +void __fastcall __CheckForDebuggerJustMyCode(unsigned char *JMC_flag) +{ + unsigned char *__DebuggerLocalJMCFlag = JMC_flag; + + if (*JMC_flag && __DebuggerCurrentSteppingThreadId != 0 && __DebuggerCurrentSteppingThreadId == GetCurrentThreadId()) { +NopLabel: + __nop(); + } +} diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/default_precision.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/default_precision.cpp new file mode 100644 index 0000000000000000000000000000000000000000..64f130b910556ece251e4b5f0388ec2961d961db --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/default_precision.cpp @@ -0,0 +1,22 @@ +// +// default_precision.cpp +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// Initializes the floating point precision to the default state. This behavior +// is overridable at link-time by linking with one of the link options. +// +#ifndef _M_IX86 + #error This file may only be built for x86 +#endif + +#include +#include + + + +extern "C" void __CRTDECL _initialize_default_precision() +{ + if (_controlfp_s(nullptr, _PC_53, _MCW_PC) != 0) + __scrt_fastfail(FAST_FAIL_FATAL_APP_EXIT); +} diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/delete_array.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/delete_array.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5e3048714ea9baf650e3d38eedf482a380b8233a --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/delete_array.cpp @@ -0,0 +1,32 @@ +// +// delete_array.cpp +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// Defines the array operator delete. +// +#include +#include + +//////////////////////////////////////////////////////////////// +// delete() Fallback Ordering +// +// +-------------+ +// |delete_scalar<----+-----------------------+ +// +--^----------+ | | +// | | | +// +--+---------+ +--+---------------+ +----+----------------+ +// |delete_array| |delete_scalar_size| |delete_scalar_nothrow| +// +--^----^----+ +------------------+ +---------------------+ +// | | +// | +-------------------+ +// | | +// +--+--------------+ +------+-------------+ +// |delete_array_size| |delete_array_nothrow| +// +-----------------+ +--------------------+ + +_CRT_SECURITYCRITICAL_ATTRIBUTE +void __CRTDECL operator delete[](void* const block) noexcept +{ + operator delete(block); +} diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/delete_array_align.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/delete_array_align.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cc58d6f45a3aaee92fed68e3419cf56a3452e17e --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/delete_array_align.cpp @@ -0,0 +1,31 @@ +// +// delete_array_align.cpp +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// Defines the array operator delete, align_val_t overload. +// +#include +#include + +////////////////////////////////////////////////////////////////////////////////// +// Aligned delete() Fallback Ordering +// +// +-------------------+ +// |delete_scalar_align<----+---------------------------+ +// +--^----------------+ | | +// | | | +// +--+---------------+ +--+---------------------+ +--+------------------------+ +// |delete_array_align| |delete_scalar_size_align| |delete_scalar_align_nothrow| +// +--^-----^---------+ +------------------------+ +---------------------------+ +// | | +// | +------------------------+ +// | | +// +--+--------------------+ +------+-------------------+ +// |delete_array_size_align| |delete_array_align_nothrow| +// +-----------------------+ +--------------------------+ + +void __CRTDECL operator delete[](void* const block, std::align_val_t const al) noexcept +{ + operator delete(block, al); +} diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/delete_array_align_nothrow.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/delete_array_align_nothrow.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c5dbd4d4b12835678afcdfde9867488163135910 --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/delete_array_align_nothrow.cpp @@ -0,0 +1,31 @@ +// +// delete_array_align_nothrow.cpp +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// Defines the array operator delete, align_val_t and nothrow_t overload. +// +#include +#include + +////////////////////////////////////////////////////////////////////////////////// +// Aligned delete() Fallback Ordering +// +// +-------------------+ +// |delete_scalar_align<----+---------------------------+ +// +--^----------------+ | | +// | | | +// +--+---------------+ +--+---------------------+ +--+------------------------+ +// |delete_array_align| |delete_scalar_size_align| |delete_scalar_align_nothrow| +// +--^-----^---------+ +------------------------+ +---------------------------+ +// | | +// | +------------------------+ +// | | +// +--+--------------------+ +------+-------------------+ +// |delete_array_size_align| |delete_array_align_nothrow| +// +-----------------------+ +--------------------------+ + +void __CRTDECL operator delete[](void* const block, std::align_val_t const al, std::nothrow_t const&) noexcept +{ + operator delete[](block, al); +} diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/delete_array_nothrow.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/delete_array_nothrow.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8dd7367ff55acb278d7b53c6e0a689686001c22c --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/delete_array_nothrow.cpp @@ -0,0 +1,31 @@ +// +// delete_array_nothrow.cpp +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// Defines the array operator delete, nothrow_t overload. +// +#include +#include + +//////////////////////////////////////////////////////////////// +// delete() Fallback Ordering +// +// +-------------+ +// |delete_scalar<----+-----------------------+ +// +--^----------+ | | +// | | | +// +--+---------+ +--+---------------+ +----+----------------+ +// |delete_array| |delete_scalar_size| |delete_scalar_nothrow| +// +--^----^----+ +------------------+ +---------------------+ +// | | +// | +-------------------+ +// | | +// +--+--------------+ +------+-------------+ +// |delete_array_size| |delete_array_nothrow| +// +-----------------+ +--------------------+ + +void __CRTDECL operator delete[](void* const block, std::nothrow_t const&) noexcept +{ + operator delete[](block); +} diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/delete_array_size.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/delete_array_size.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f38e5424c37aabcdc2a1fbcc336930b9d6a0a770 --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/delete_array_size.cpp @@ -0,0 +1,32 @@ +// +// delete_array_size.cpp +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// Defines the array operator delete, size_t overload. +// +#include +#include + +//////////////////////////////////////////////////////////////// +// delete() Fallback Ordering +// +// +-------------+ +// |delete_scalar<----+-----------------------+ +// +--^----------+ | | +// | | | +// +--+---------+ +--+---------------+ +----+----------------+ +// |delete_array| |delete_scalar_size| |delete_scalar_nothrow| +// +--^----^----+ +------------------+ +---------------------+ +// | | +// | +-------------------+ +// | | +// +--+--------------+ +------+-------------+ +// |delete_array_size| |delete_array_nothrow| +// +-----------------+ +--------------------+ + +_CRT_SECURITYCRITICAL_ATTRIBUTE +void __CRTDECL operator delete[](void* const block, size_t const) noexcept +{ + operator delete[](block); +} diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/delete_array_size_align.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/delete_array_size_align.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e48e771ad41286d8701131bdec9d08d0320f1324 --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/delete_array_size_align.cpp @@ -0,0 +1,31 @@ +// +// delete_array_size_align.cpp +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// Defines the array operator delete, size_t and align_val_t overload. +// +#include +#include + +////////////////////////////////////////////////////////////////////////////////// +// Aligned delete() Fallback Ordering +// +// +-------------------+ +// |delete_scalar_align<----+---------------------------+ +// +--^----------------+ | | +// | | | +// +--+---------------+ +--+---------------------+ +--+------------------------+ +// |delete_array_align| |delete_scalar_size_align| |delete_scalar_align_nothrow| +// +--^-----^---------+ +------------------------+ +---------------------------+ +// | | +// | +------------------------+ +// | | +// +--+--------------------+ +------+-------------------+ +// |delete_array_size_align| |delete_array_align_nothrow| +// +-----------------------+ +--------------------------+ + +void __CRTDECL operator delete[](void* const block, size_t const, std::align_val_t const al) noexcept +{ + operator delete[](block, al); +} diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/delete_debug.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/delete_debug.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3161dffe203932242ae7d6eee180d34274173407 --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/delete_debug.cpp @@ -0,0 +1,72 @@ +// +// delete_debug.cpp +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// Defines the debug operator delete (both scalar and array forms). +// +#include +#include + + + +#ifdef _DEBUG + + _CRT_SECURITYCRITICAL_ATTRIBUTE + void __CRTDECL operator delete( + void* block, + int const block_use, + char const* file_name, + int const line_number + ) noexcept + { + UNREFERENCED_PARAMETER(file_name); + UNREFERENCED_PARAMETER(line_number); + + _free_dbg(block, block_use); + } + + _CRT_SECURITYCRITICAL_ATTRIBUTE + void __CRTDECL operator delete[]( + void* block, + int const block_use, + char const* file_name, + int const line_number + ) noexcept + { + return operator delete(block, block_use, file_name, line_number); + } + +#else // ^^^ _DEBUG ^^^ // vvv !_DEBUG vvv // + + _CRT_SECURITYCRITICAL_ATTRIBUTE + void __CRTDECL operator delete( + void* block, + int const block_use, + char const* file_name, + int const line_number + ) noexcept + { + UNREFERENCED_PARAMETER(block_use); + UNREFERENCED_PARAMETER(file_name); + UNREFERENCED_PARAMETER(line_number); + + return operator delete(block); + } + + _CRT_SECURITYCRITICAL_ATTRIBUTE + void __CRTDECL operator delete[]( + void* block, + int const block_use, + char const* file_name, + int const line_number + ) noexcept + { + UNREFERENCED_PARAMETER(block_use); + UNREFERENCED_PARAMETER(file_name); + UNREFERENCED_PARAMETER(line_number); + + return operator delete[](block); + } + +#endif diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/delete_scalar.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/delete_scalar.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9df7c80ee8f09ab1411edf1796604310c3d0e53b --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/delete_scalar.cpp @@ -0,0 +1,38 @@ +// +// delete_scalar.cpp +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// Defines the scalar operator delete. +// +#include +#include +#include +#include + +//////////////////////////////////////////////////////////////// +// delete() Fallback Ordering +// +// +-------------+ +// |delete_scalar<----+-----------------------+ +// +--^----------+ | | +// | | | +// +--+---------+ +--+---------------+ +----+----------------+ +// |delete_array| |delete_scalar_size| |delete_scalar_nothrow| +// +--^----^----+ +------------------+ +---------------------+ +// | | +// | +-------------------+ +// | | +// +--+--------------+ +------+-------------+ +// |delete_array_size| |delete_array_nothrow| +// +-----------------+ +--------------------+ + +_CRT_SECURITYCRITICAL_ATTRIBUTE +void __CRTDECL operator delete(void* const block) noexcept +{ + #ifdef _DEBUG + _free_dbg(block, _UNKNOWN_BLOCK); + #else + free(block); + #endif +} diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/delete_scalar_align.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/delete_scalar_align.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4545daa5b51e7d06254aba14e80d6a9ac0f8a59d --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/delete_scalar_align.cpp @@ -0,0 +1,33 @@ +// +// delete_scalar_align.cpp +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// Defines the scalar operator delete, align_val_t overload. +// +#include +#include +#include + +////////////////////////////////////////////////////////////////////////////////// +// Aligned delete() Fallback Ordering +// +// +-------------------+ +// |delete_scalar_align<----+---------------------------+ +// +--^----------------+ | | +// | | | +// +--+---------------+ +--+---------------------+ +--+------------------------+ +// |delete_array_align| |delete_scalar_size_align| |delete_scalar_align_nothrow| +// +--^-----^---------+ +------------------------+ +---------------------------+ +// | | +// | +------------------------+ +// | | +// +--+--------------------+ +------+-------------------+ +// |delete_array_size_align| |delete_array_align_nothrow| +// +-----------------------+ +--------------------------+ + +_CRT_SECURITYCRITICAL_ATTRIBUTE +void __CRTDECL operator delete(void* const block, std::align_val_t const) noexcept +{ + _aligned_free(block); +} diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/delete_scalar_align_nothrow.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/delete_scalar_align_nothrow.cpp new file mode 100644 index 0000000000000000000000000000000000000000..029f77992cbab70499f77571c624b52fc5c1a1f4 --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/delete_scalar_align_nothrow.cpp @@ -0,0 +1,31 @@ +// +// delete_scalar_align_nothrow.cpp +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// Defines the scalar operator delete, align_val_t and nothrow_t overload. +// +#include +#include + +////////////////////////////////////////////////////////////////////////////////// +// Aligned delete() Fallback Ordering +// +// +-------------------+ +// |delete_scalar_align<----+---------------------------+ +// +--^----------------+ | | +// | | | +// +--+---------------+ +--+---------------------+ +--+------------------------+ +// |delete_array_align| |delete_scalar_size_align| |delete_scalar_align_nothrow| +// +--^-----^---------+ +------------------------+ +---------------------------+ +// | | +// | +------------------------+ +// | | +// +--+--------------------+ +------+-------------------+ +// |delete_array_size_align| |delete_array_align_nothrow| +// +-----------------------+ +--------------------------+ + +void __CRTDECL operator delete(void* const block, std::align_val_t const al, std::nothrow_t const&) noexcept +{ + operator delete(block, al); +} diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/delete_scalar_nothrow.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/delete_scalar_nothrow.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bafabd703d47a88ea7d4f3213d71176072232d48 --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/delete_scalar_nothrow.cpp @@ -0,0 +1,31 @@ +// +// delete_scalar_nothrow.cpp +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// Defines the scalar operator delete, nothrow_t overload. +// +#include +#include + +//////////////////////////////////////////////////////////////// +// delete() Fallback Ordering +// +// +-------------+ +// |delete_scalar<----+-----------------------+ +// +--^----------+ | | +// | | | +// +--+---------+ +--+---------------+ +----+----------------+ +// |delete_array| |delete_scalar_size| |delete_scalar_nothrow| +// +--^----^----+ +------------------+ +---------------------+ +// | | +// | +-------------------+ +// | | +// +--+--------------+ +------+-------------+ +// |delete_array_size| |delete_array_nothrow| +// +-----------------+ +--------------------+ + +void __CRTDECL operator delete(void* const block, std::nothrow_t const&) noexcept +{ + operator delete(block); +} diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/delete_scalar_size.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/delete_scalar_size.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a29321c74edb002cb52cffb47d4932517251f5e6 --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/delete_scalar_size.cpp @@ -0,0 +1,32 @@ +// +// delete_scalar_size.cpp +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// Defines the scalar operator delete, size_t overload. +// +#include +#include + +//////////////////////////////////////////////////////////////// +// delete() Fallback Ordering +// +// +-------------+ +// |delete_scalar<----+-----------------------+ +// +--^----------+ | | +// | | | +// +--+---------+ +--+---------------+ +----+----------------+ +// |delete_array| |delete_scalar_size| |delete_scalar_nothrow| +// +--^----^----+ +------------------+ +---------------------+ +// | | +// | +-------------------+ +// | | +// +--+--------------+ +------+-------------+ +// |delete_array_size| |delete_array_nothrow| +// +-----------------+ +--------------------+ + +_CRT_SECURITYCRITICAL_ATTRIBUTE +void __CRTDECL operator delete(void* const block, size_t const) noexcept +{ + operator delete(block); +} diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/delete_scalar_size_align.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/delete_scalar_size_align.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0977024c4bb3c1d75a6bf72360ad6756e66d88b4 --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/delete_scalar_size_align.cpp @@ -0,0 +1,31 @@ +// +// delete_scalar_size_align.cpp +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// Defines the scalar operator delete, size_t and align_val_t overload. +// +#include +#include + +////////////////////////////////////////////////////////////////////////////////// +// Aligned delete() Fallback Ordering +// +// +-------------------+ +// |delete_scalar_align<----+---------------------------+ +// +--^----------------+ | | +// | | | +// +--+---------------+ +--+---------------------+ +--+------------------------+ +// |delete_array_align| |delete_scalar_size_align| |delete_scalar_align_nothrow| +// +--^-----^---------+ +------------------------+ +---------------------------+ +// | | +// | +------------------------+ +// | | +// +--+--------------------+ +------+-------------------+ +// |delete_array_size_align| |delete_array_align_nothrow| +// +-----------------------+ +--------------------------+ + +void __CRTDECL operator delete(void* const block, size_t const, std::align_val_t const al) noexcept +{ + operator delete(block, al); +} diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/denormal_control.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/denormal_control.cpp new file mode 100644 index 0000000000000000000000000000000000000000..92cfe6fbabc3d5150e747f9a9587be3d754b0cc8 --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/denormal_control.cpp @@ -0,0 +1,16 @@ +// +// denormal_control.cpp +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// Initializes the denormal mode to the default state. This behavior is +// overridable at link-time by linking with one of the link options. +// +#include + + + +extern "C" void __CRTDECL _initialize_denormal_control() +{ + // No-op +} diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/dll_dllmain.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/dll_dllmain.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1d1ae24bf4f123232663ed1fc3ad19bcd564c0fd --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/dll_dllmain.cpp @@ -0,0 +1,335 @@ +// +// dll_dllmain.cpp +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// The DLL entry point that initializes the DLL and calls the client-defined +// DllMain entry point. +// +#include +#include +#include + + + +// The client may define a _pRawDllMain. This function gets called for attach +// notifications before any other function is called, and gets called for detach +// notifications after any other function is called. If no _pRawDllMain is +// defined, it is aliased to the no-op _pDefaultRawDllMain. +extern "C" extern __scrt_dllmain_type const _pRawDllMain; +extern "C" extern __scrt_dllmain_type const _pDefaultRawDllMain = nullptr; +_VCRT_DECLARE_ALTERNATE_NAME_DATA(_pRawDllMain, _pDefaultRawDllMain) + + + +// This flag is incremented each time DLL_PROCESS_ATTACH is processed successfully +// and is decremented each time DLL_PROCESS_DETACH is processed (the detach is +// always assumed to complete successfully). +static int __proc_attached = 0; + + + +static BOOL __cdecl dllmain_crt_process_attach(HMODULE const instance, + LPVOID const reserved) +{ + if (!__scrt_initialize_crt(__scrt_module_type::dll)) + return FALSE; + + bool const is_nested = __scrt_acquire_startup_lock(); + bool fail = true; + __try + { + if (__scrt_current_native_startup_state != __scrt_native_startup_state::uninitialized) + __scrt_fastfail(FAST_FAIL_FATAL_APP_EXIT); + + __scrt_current_native_startup_state = __scrt_native_startup_state::initializing; + + if (!__scrt_dllmain_before_initialize_c()) + __leave; + + #ifdef _RTC + _RTC_Initialize(); + #endif + + __scrt_initialize_type_info(); + + __scrt_initialize_default_local_stdio_options(); + + if (_initterm_e(__xi_a, __xi_z) != 0) + __leave; + + if (!__scrt_dllmain_after_initialize_c()) + __leave; + + _initterm(__xc_a, __xc_z); + + __scrt_current_native_startup_state = __scrt_native_startup_state::initialized; + fail = false; + } + __finally + { + __scrt_release_startup_lock(is_nested); + } + if (fail) + return FALSE; + + // If we have any dynamically initialized __declspec(thread) variables, we + // invoke their initialization for the thread on which the DLL is being + // loaded. We cannot rely on the OS performing the initialization with the + // DLL_PROCESS_ATTACH notification because, on Windows Server 2003 and below, + // that call happens before the CRT is initialized. + PIMAGE_TLS_CALLBACK const* const tls_init_callback = __scrt_get_dyn_tls_init_callback(); + if (*tls_init_callback != nullptr && __scrt_is_nonwritable_in_current_image(tls_init_callback)) + { + (*tls_init_callback)(instance, DLL_THREAD_ATTACH, reserved); + } + + ++__proc_attached; + return TRUE; +} + +// clang-format off +// +// DLL Uninitialization of the CRT +// +// +----------------------+ +// | UserEXE!main returns | +// +--------+-------------+ +// | +// +--------v-----------------------+ +// | ExitProcess/LdrShutdownProcess | +// +--------+-----------------------+ +// | +// +--------v--------+ +// | UserDLL!DLLMain | +// +--------+--------+ +// | +// +--------v----------------------------------------------+ +// | UserDLL!dllmain_crt_process_detach | +-----------------------------+ +// | +-----------------> UCRT _cexit() | +// | + Startup Lock +-------------------+ | | | | +// | | | | | | Run onexit table | +// | | __scrt_dllmain_uninitialize_c() | | | | Run XP* and XT* terminators | +// | | /MD: Run onexit table | | | | | +// | | /MT: _cexit() +-------------------------+ | +-----------------------------+ +// | | | | +// | | | | +---------------------------------------------+ +// | | __scrt_uninitialize_type_info() | | +---> UCRT Uninitializer Order | +// | | | | | | (__acrt_uninitialize) | +// | | _RTC_Terminate() | | | | | +// | | Run RTC terminators | | | | Release when terminating: | +// | | | | | | _flushall() | +// | +----------------------------------+ | | | | +// | | | | Debug (always), Release unless terminating: | +// | __scrt_uninitialize_crt() | | | uninitialize_c() | +// | /MT: __acrt_uninitialize() + __vcrt_uninitialize() +-----+ | uninitialize_environment() | +// | /MD: no-op (handled by UCRT/VCRuntime DLL unload) | | | uninitialize_allocated_memory() | +// | | | | uninitialize_allocated_io_buffers() | +// | + __finally +--------------------------------------+ | | | report_memory_leaks() | +// | | | | | | __acrt_uninitialize_command_line() | +// | | __scrt_dllmain_uninitialize_critical() | | | | __acrt_uninitialize_lowio() | +// | | /MT: __acrt_uninitialize_ptd() +----------------------------->__acrt_uninitialize_ptd() | +// | | __vcrt_uninitialize_ptd() +--------------------+ | | uninitialize_vcruntime() (the OS one) | +// | | /MD: no-op | | | | | __acrt_uninitialize_heap() | +// | | (handled by UCRT/VCRuntime DLL unload) | | | | | __acrt_uninitialize_locks() | +// | | | | | | | uninitialize_global_state_isolation() | +// | | Ensures PTD is released on error | | | | | | +// | | so FLS callbacks don't refer to unloaded module | | | | +---------------------------------------------+ +// | | | | | | +// | +--------------------------------------------------+ | | | +--------------------------------------+ +// | | | +---> VCRuntime Uninitializer Order | +// +-------------------------------------------------------+ | | (__vcrt_uninitialize) | +// | | | +// +---------------------------------+ | | Debug unless terminating: | +// | /MD Only | +-------->__vcrt_uninitialize_ptd() | +// | | | __vcrt_uninitialize_locks() | +// | ucrtbase(d)!__acrt_DllMain | | __vcrt_uninitialize_winapi_thunks() | +// | __acrt_uninitialize() | | | +// | | +--------------------------------------+ +// | | +// | vcruntime140(d)!__vcrt_DllMain | +// | __vcrt_uninitialize() | +// | | +// +---------------------------------+ +// +// clang-format on + +static BOOL __cdecl dllmain_crt_process_detach(bool const is_terminating) +{ + // If the attach did not complete successfully, or if the detach was already + // executed, do not execute the detach: + if (__proc_attached <= 0) + { + return FALSE; + } + + --__proc_attached; + + BOOL result = TRUE; + + __try + { + bool const is_nested = __scrt_acquire_startup_lock(); + __try + { + if (__scrt_current_native_startup_state != __scrt_native_startup_state::initialized) + { + __scrt_fastfail(FAST_FAIL_FATAL_APP_EXIT); + } + + __scrt_dllmain_uninitialize_c(); + + __scrt_uninitialize_type_info(); + + #ifdef _RTC + _RTC_Terminate(); + #endif + + __scrt_current_native_startup_state = __scrt_native_startup_state::uninitialized; + } + __finally + { + __scrt_release_startup_lock(is_nested); + } + + if (!__scrt_uninitialize_crt(is_terminating, false)) + { + result = FALSE; + __leave; + } + } + __finally + { + __scrt_dllmain_uninitialize_critical(); + } + + return result; +} + + + +static BOOL WINAPI dllmain_crt_dispatch( + HINSTANCE const instance, + DWORD const reason, + LPVOID const reserved + ) +{ + switch (reason) + { + case DLL_PROCESS_ATTACH: return dllmain_crt_process_attach(instance, reserved); + case DLL_PROCESS_DETACH: return dllmain_crt_process_detach(reserved != nullptr); + case DLL_THREAD_ATTACH: return __scrt_dllmain_crt_thread_attach(); + case DLL_THREAD_DETACH: return __scrt_dllmain_crt_thread_detach(); + } + + return TRUE; +} + +// Define the _CRT_INIT function for compatibility. +extern "C" BOOL WINAPI _CRT_INIT( + HINSTANCE const instance, + DWORD const reason, + LPVOID const reserved + ) +{ + return dllmain_crt_dispatch(instance, reason, reserved); +} + +static BOOL WINAPI dllmain_raw( + HINSTANCE const instance, + DWORD const reason, + LPVOID const reserved + ) +{ + if (!_pRawDllMain) + return TRUE; + + return _pRawDllMain(instance, reason, reserved); +} + + + +static BOOL __cdecl dllmain_dispatch( + HINSTANCE const instance, + DWORD const reason, + LPVOID const reserved + ) +{ + // If this is a process detach notification, check that there was a prior + // process attach notification that was processed successfully. This is + // to ensure that we don't detach more times than we attach. + if (reason == DLL_PROCESS_DETACH && __proc_attached <= 0) + { + return FALSE; + } + + BOOL result = TRUE; + + __try + { + if (reason == DLL_PROCESS_ATTACH || reason == DLL_THREAD_ATTACH) + { + result = dllmain_raw(instance, reason, reserved); + if (!result) + __leave; + + result = dllmain_crt_dispatch(instance, reason, reserved); + if (!result) + __leave; + } + + result = DllMain(instance, reason, reserved); + + // If the client DllMain routine failed, unwind the initialization: + if (reason == DLL_PROCESS_ATTACH && !result) + { + DllMain(instance, DLL_PROCESS_DETACH, reserved); + dllmain_crt_dispatch(instance, DLL_PROCESS_DETACH, reserved); + dllmain_raw(instance, DLL_PROCESS_DETACH, reserved); + } + + if (reason == DLL_PROCESS_DETACH || reason == DLL_THREAD_DETACH) + { + result = dllmain_crt_dispatch(instance, reason, reserved); + if (!result) + __leave; + + result = dllmain_raw(instance, reason, reserved); + if (!result) + __leave; + } + } + __except(__scrt_dllmain_exception_filter( + instance, + reason, + reserved, + dllmain_crt_dispatch, + GetExceptionCode(), + GetExceptionInformation())) + { + result = FALSE; + } + + return result; +} + + + +// The entry point for this DLL. +extern "C" BOOL WINAPI _DllMainCRTStartup( + HINSTANCE const instance, + DWORD const reason, + LPVOID const reserved + ) +{ + if (reason == DLL_PROCESS_ATTACH) + { + // The /GS security cookie must be initialized before any exception + // handling targeting the current image is registered. No function + // using exception handling can be called in the current image until + // after this call: + __security_init_cookie(); + } + + return dllmain_dispatch(instance, reason, reserved); +} diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/dll_dllmain_stub.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/dll_dllmain_stub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4c875fa192c44d140cc90ef1a7c1b6e8fb3fbb8f --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/dll_dllmain_stub.cpp @@ -0,0 +1,38 @@ +// +// dll_dllmain_stub.cpp +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// A DllMain to be used if the client does not define one. +// +#include + + + +extern "C" extern __scrt_dllmain_type const _pRawDllMain; + + + +extern "C" BOOL WINAPI DllMain( + _In_ HINSTANCE const instance, + _In_ DWORD const reason, + _In_ LPVOID const reserved + ) +{ + UNREFERENCED_PARAMETER(instance); + UNREFERENCED_PARAMETER(reason); + UNREFERENCED_PARAMETER(reserved); + + // When the dynamic CRT libraries are used, the client DLL does not need the + // thread attach and detach notifications if the client does not provide a + // DllMain or _pRawDllMain, so we can disable them. (When the static CRT + // libraries are used, the CRT's DllMain that is linked into the DLL requires + // these notifications.) + // Enclaves do not support this performance optimization API. + #if defined CRTDLL && !defined _SCRT_ENCLAVE_BUILD + if (reason == DLL_PROCESS_ATTACH && !_pRawDllMain) + DisableThreadLibraryCalls(instance); + #endif + + return TRUE; +} diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/dyn_tls_init.c b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/dyn_tls_init.c new file mode 100644 index 0000000000000000000000000000000000000000..12029c9784a547c7d3dc2e07bb7eda8ce7e10161 --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/dyn_tls_init.c @@ -0,0 +1,21 @@ +// +// dyn_tls_init.c +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// This source file provides a fallback definition of __dyn_tls_init_callback, +// used whenever TLS initialization is not required. +// +// This relies on a feature of the C compiler known as "communal variables." +// This does not work in C++, and the linker's alternatename features is not +// sufficient here. +// +#include + +#pragma warning(disable: 4132) // const object should be initialized +const PIMAGE_TLS_CALLBACK __dyn_tls_init_callback; + +PIMAGE_TLS_CALLBACK const* __cdecl __scrt_get_dyn_tls_init_callback() +{ + return &__dyn_tls_init_callback; +} diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/ehhelpers.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/ehhelpers.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1bc229fec0392285b5e129a235e6a44b229a8add --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/ehhelpers.cpp @@ -0,0 +1,333 @@ +/*** +*ehhelpers.cpp - Some target-independent helper routines used by the EH frame handler. +* +* Copyright (c) Microsoft Corporation. All rights reserved. +* +****/ + +#include // User-visible routines for eh +#include // This project's versions of standard assert macros +#include // Declarations of all types used for EH +#include +#include // Declarations of hook variables and callbacks +#include // Routines to handle transfer of control (trnsctrl.asm) +#include +#include + +#include +#include + +#include "ehhelpers.h" + +// If we call DestructExceptionObject directly from C_Specific_Handler/ +// _except_handler3, then this obj file will be pulled in by the linker +// even in programs which do not have C++ exceptions. So we call it using a +// function pointer _pDestructExceptionObject which gets initialized to 0 by +// default. If C++ exceptions are present, this file will be pulled in naturally +// and _pDestructExceptionObject will point to __DestructExceptionObject. + +extern "C" void (__cdecl * const _pDestructExceptionObject)(EHExceptionRecord *,BOOLEAN) + = &__DestructExceptionObject; + +//////////////////////////////////////////////////////////////////////////////// +// +// __AdjustPointer - Adjust the pointer to the exception object to a pointer to a +// base instance. +// +// Output: +// The address point of the base. +// +// Side-effects: +// NONE. + +extern "C" _VCRTIMP void *__AdjustPointer( + void *pThis, // Address point of exception object + const PMD& pmd // Generalized pointer-to-member + // descriptor +) { + char *pRet = (char *)pThis + pmd.mdisp; + + if (pmd.pdisp >= 0) { + pRet += *(__int32 *)((char *)*(ptrdiff_t *)((char *)pThis + pmd.pdisp) +#if defined(_WIN64) + + (unsigned __int64)pmd.vdisp +#else + + pmd.vdisp +#endif + ); + pRet += pmd.pdisp; + } + + return pRet; +} + +//////////////////////////////////////////////////////////////////////////////// +// +// __GetPlatformExceptionInfo - Get Platform Exception extra information from current exception +// +// Output: +// The address of WINRTEXCEPTIONINFO structure +// +// Side-effects: +// NONE. +extern "C" _VCRTIMP void * __GetPlatformExceptionInfo( + int *pIsBadAlloc +) { + *pIsBadAlloc = 0; + EHExceptionRecord *pExcept = _pCurrentException; + if (pExcept) + { + ThrowInfo* pTI = PER_PTHROW(pExcept); + if (pTI) + { + if (THROW_ISWINRT( (*pTI) ) ) + { + ULONG_PTR *exceptionInfoPointer = *reinterpret_cast(PER_PEXCEPTOBJ(pExcept)); + exceptionInfoPointer--; + return reinterpret_cast(*exceptionInfoPointer); + } + else + { + _EXCEPTION_POINTERS exceptionPointers; + exceptionPointers.ExceptionRecord = reinterpret_cast(pExcept); + exceptionPointers.ContextRecord = nullptr; + + *pIsBadAlloc = _is_exception_typeof(typeid(std::bad_alloc), &exceptionPointers); + } + } + } + + return nullptr; +} + +/////////////////////////////////////////////////////////////////////////////// +// +// __current_exception(), __current_exception_context(), __processing_throw() +// - Accessors for the per-thread exception state, used +// by the managed EH implementation, exception_ptr, etc. +// + +// Don't define these "locally" for satellite DLL build, the satellite +// needs to call these from the base vcruntime to infer the location of the PTD +#if !defined _VCRT_SAT_1 +extern "C" void** __cdecl __current_exception() +{ + return &RENAME_BASE_PTD(__vcrt_getptd)()->_curexception; +} + +extern "C" void** __cdecl __current_exception_context() +{ + return &RENAME_BASE_PTD(__vcrt_getptd)()->_curcontext; +} + +extern "C" int* __cdecl __processing_throw() +{ + return &RENAME_BASE_PTD(__vcrt_getptd)()->_ProcessingThrow; +} +#endif + +//////////////////////////////////////////////////////////////////////////////// +// +// __FrameUnwindFilter - Allows possibility of continuing through SEH during +// unwind. +// + +extern "C" _VCRTIMP int __cdecl __FrameUnwindFilter( + EXCEPTION_POINTERS *pExPtrs +) { + EHExceptionRecord *pExcept = (EHExceptionRecord *)pExPtrs->ExceptionRecord; + + switch (PER_CODE(pExcept)) { + case EH_EXCEPTION_NUMBER: + _pCurrentException = pExcept; + _pCurrentExContext = pExPtrs->ContextRecord; + terminate(); + + case MANAGED_EXCEPTION_CODE: + case MANAGED_EXCEPTION_CODE_V4: + /* + See VSW#544593 for more details. __ProcessingThrow is used to implement + std::uncaught_exception(). The interaction between C++, SEH and managed + exception wrt __ProcessingThrow is unspec'ed. From code inspection, it + looks like that __ProcessingThrow works ok with all C++ exceptions. + + In this case, when we encounter a managed exception thrown from a destructor + during unwind, we choose to decrement the count. This means that the previous + C++ exception which incremented the count won't be considered any longer. + In fact, the managed exception will be thrown, and the native C++ one will + not have any possibility to be caught any longer. + + We should revisit std::uncaught_exception() and SEH/managed exception in the + next version. + */ + if (__ProcessingThrow > 0) + { + --__ProcessingThrow; + } + return EXCEPTION_CONTINUE_SEARCH; + + default: + return EXCEPTION_CONTINUE_SEARCH; + } +} + + +PGETWINRT_OOM_EXCEPTION __WinRTOutOfMemoryExceptionCallback = nullptr; + +extern "C" _VCRTIMP void __cdecl _SetWinRTOutOfMemoryExceptionCallback(PGETWINRT_OOM_EXCEPTION pCallback) +{ + __WinRTOutOfMemoryExceptionCallback = pCallback; +} + +////////////////////////////////////////////////////////////////////////////////// +// __std_terminate: Helper function referenced by the front-end to assist in +// implementing noexcept. Noexcept termination semantics are generally handled +// by FindHandler() above, when we cross a function with the noexcept bit set +// in the xdata when looking for a handler. When noexcept functions are inlined, +// though, we may no longer cross a noexcept function boundary when searching for +// a handler. In this case the inlined code contains an EH state that will invoke +// this function should an exception occur. +extern "C" __declspec(noreturn) void __cdecl __std_terminate() +{ + terminate(); +} + +//////////////////////////////////////////////////////////////////////////////// +// +// __DestructExceptionObject - Call the destructor (if any) of the original +// exception object. +// +// Returns: None. +// +// Side-effects: +// Original exception object is destructed. +// +// Notes: +// If destruction throws any exception, and we are destructing the exception +// object as a result of a new exception, we give up. If the destruction +// throws otherwise, we let it be. + +static DWORD _FilterSetCurrentException(EXCEPTION_POINTERS* pointers, BOOLEAN fThrowNotAllowed) +{ + if (fThrowNotAllowed) { + const auto eRecord = reinterpret_cast(pointers->ExceptionRecord); + if (PER_IS_MSVC_EH(eRecord)) + { + // Can't have new exceptions when we're unwinding due to another + // exception. + _pCurrentException = eRecord; + _pCurrentExContext = pointers->ContextRecord; + terminate(); + } + } + + return EXCEPTION_CONTINUE_SEARCH; +} + +extern "C" _VCRTIMP void __cdecl __DestructExceptionObject( + EHExceptionRecord *pExcept, // The original exception record + BOOLEAN fThrowNotAllowed // TRUE if destructor not allowed to + // throw +) { + // Ignore if not a C++ exception (since this is now called from + // _except_handler3) + if (pExcept == nullptr || !(PER_IS_MSVC_EH(pExcept))) + { + return; + } + + EHTRACE_FMT1("Destroying object @ 0x%p", PER_PEXCEPTOBJ(pExcept)); + + /*UNDONE:Is this _SYSCRT specific */ +#pragma prefast(suppress:__WARNING_REDUNDANT_POINTER_TEST, "Current definition of PER_CODE ensures that pExcept cannot be nullptr") + if (PER_PTHROW(pExcept)) { + if (THROW_UNWINDFUNC(*PER_PTHROW(pExcept)) != 0) { + + __try { + +#if _EH_RELATIVE_TYPEINFO + _CallMemberFunction0(PER_PEXCEPTOBJ(pExcept), + THROW_UNWINDFUNC_IB(*PER_PTHROW(pExcept),(ptrdiff_t)PER_PTHROWIB(pExcept))); +#else + _CallMemberFunction0(PER_PEXCEPTOBJ(pExcept), + THROW_UNWINDFUNC(*PER_PTHROW(pExcept))); +#endif + + } __except(_FilterSetCurrentException(GetExceptionInformation(), fThrowNotAllowed)) {} + } + else if (THROW_ISWINRT(*PER_PTHROW(pExcept))) { + // Release if WinRT reference type exception + IUnknown* const pUnknown = *static_cast(PER_PEXCEPTOBJ(pExcept)); + if (pUnknown) { + pUnknown->Release(); + } + } + } +} + +///////////////////////////////////////////////////////////////////////////// +// +// _IsExceptionObjectToBeDestroyed - Determine if an exception object is still +// in use by a more deeply nested catch frame, or if it unused and should be +// destroyed on exiting from the current catch block. +// +// Returns: +// TRUE if exception object not found and should be destroyed. +// +extern "C" BOOL __cdecl _IsExceptionObjectToBeDestroyed( + PVOID pExceptionObject +) { + FRAMEINFO * pFrameInfo; + + for (pFrameInfo = pFrameInfoChain; pFrameInfo; pFrameInfo = pFrameInfo->pNext ) { + if (pFrameInfo->pExceptionObject == pExceptionObject) { + return FALSE; + } + } + return TRUE; +} + +////////////////////////////////////////////////////////////////////////////////// +// _is_exception_typeof - checks if the thrown exception is the type, the caller +// has passed in. +// +extern "C" _VCRTIMP int __cdecl _is_exception_typeof(_In_ const type_info & type, _In_ struct _EXCEPTION_POINTERS * ep) +{ + _VCRT_VERIFY(ep); + + EHExceptionRecord *pExcept = (EHExceptionRecord *)ep->ExceptionRecord; + + // Is this our Exception? + _VCRT_VERIFY(pExcept && PER_IS_MSVC_EH(pExcept)); + +#if _EH_RELATIVE_TYPEINFO + __int32 const *ppCatchable; + ptrdiff_t imgBase = (ptrdiff_t)pExcept->params.pThrowImageBase; + ppCatchable = THROW_CTLIST_IB(*PER_PTHROW(pExcept), imgBase ); + int catchables = THROW_COUNT_IB(*PER_PTHROW(pExcept), imgBase ); +#else + CatchableType * const *ppCatchable; + ppCatchable = THROW_CTLIST(*PER_PTHROW(pExcept)); + int catchables = THROW_COUNT(*PER_PTHROW(pExcept)); +#endif + + CatchableType *pCatchable; + + // Scan all types that thrown object can be converted to. + for (; catchables > 0; catchables--, ppCatchable++) + { +#if _EH_RELATIVE_TYPEINFO + pCatchable = (CatchableType *)(imgBase + *ppCatchable); + if(strcmp(type.raw_name(), CT_NAME_IB(*pCatchable, imgBase)) == 0) +#else + pCatchable = *ppCatchable; + if(strcmp(type.raw_name(), CT_NAME(*pCatchable)) == 0) +#endif + { + // Found a Match. + return 1; + } + } + + return 0; +} diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/ehhelpers.h b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/ehhelpers.h new file mode 100644 index 0000000000000000000000000000000000000000..97f6e866ea3641c6a43d8193d211ba56c57a9f41 --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/ehhelpers.h @@ -0,0 +1,87 @@ +// +// Copyright (c) Microsoft Corporation. All Rights reserved. +// + +#pragma once + +#if defined(_M_X64) || defined(_M_ARM_NT) || defined(_M_ARM64) || defined(_CHPE_X86_ARM64_EH_) + +#define _pForeignExcept (*((EHExceptionRecord **)&(RENAME_BASE_PTD(__vcrt_getptd)()->_pForeignException))) + +#endif + +#define pFrameInfoChain (*((FRAMEINFO **) &(RENAME_BASE_PTD(__vcrt_getptd)()->_pFrameInfoChain))) + +// Pre-V4 managed exception code +#define MANAGED_EXCEPTION_CODE 0XE0434F4D + +// V4 and later managed exception code +#define MANAGED_EXCEPTION_CODE_V4 0XE0434352 + +extern "C" void +__except_validate_context_record( + _In_ PCONTEXT ContextRecord + ); + +extern "C" _VCRTIMP void * __AdjustPointer( + void *, + const PMD& +); + +extern "C" _VCRTIMP void * __GetPlatformExceptionInfo( + int * +); + +extern "C" _VCRTIMP int __cdecl __FrameUnwindFilter( + EXCEPTION_POINTERS * +); + +extern PGETWINRT_OOM_EXCEPTION __WinRTOutOfMemoryExceptionCallback; + +extern "C" _VCRTIMP void __cdecl __DestructExceptionObject( + EHExceptionRecord *, + BOOLEAN +); + +extern "C" _VCRTIMP void __cdecl RENAME_EH_EXTERN(__BuildCatchObject)( + EHExceptionRecord *, + void *, + HandlerType *, + CatchableType * +); + +extern "C" _VCRTIMP int __cdecl RENAME_EH_EXTERN(__TypeMatch4)( + FH4::HandlerType4 *, + CatchableType *, + ThrowInfo * + ); + +extern "C" _VCRTIMP int __cdecl RENAME_EH_EXTERN(__TypeMatch)( + HandlerType *, + CatchableType *, + ThrowInfo * +); + +// +// Prototype for the internal handler +// + +template +EXCEPTION_DISPOSITION __InternalCxxFrameHandlerWrapper( + EHExceptionRecord *pExcept, + EHRegistrationNode *pRN, + CONTEXT *pContext, + DispatcherContext *pDC, + typename T::FuncInfo *pFuncInfo, + int CatchDepth, + EHRegistrationNode *pMarkerRN, + BOOLEAN recursive); + +#if _EH_RELATIVE_TYPEINFO + +#undef THROW_COUNT +#define THROW_COUNT(ti) THROW_COUNT_IB(ti, _GetThrowImageBase()) +#undef THROW_CTLIST +#define THROW_CTLIST(ti) THROW_CTLIST_IB(ti, _GetThrowImageBase()) + +#endif // _EH_RELATIVE_TYPEINFO diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/ehstate.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/ehstate.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ce2cb2f79bbd33ca85bff564cbecc955c6d53f51 --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/ehstate.cpp @@ -0,0 +1,237 @@ +/*** +* ehstate.cpp +* +* Copyright (c) Microsoft Corporation. All rights reserved. +*Purpose: +* Contains state management code for all platforms. +* +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "ehhelpers.h" +#include + +#if _EH_RELATIVE_FUNCINFO +#if defined(_M_ARM_NT) || defined(_M_ARM64) || defined(_CHPE_X86_ARM64_EH_) || defined(_M_ARM64EC) +static uintptr_t adjustIp(DispatcherContext *pDC, uintptr_t Ip) +{ +#if defined(_M_ARM64EC) + if(RtlIsEcCode(Ip)) { + PDISPATCHER_CONTEXT_ARM64EC pECDC; + pECDC = (PDISPATCHER_CONTEXT_ARM64EC) pDC; + + if(pECDC->ControlPcIsUnwound != FALSE) { + Ip -= 4; + } + } +#else + + // + // If this context came from an unwind to a call, then the ControlPc points + // to a return address, which could put us at the start of a neighboring + // scope. To correct for this, back the PC up by the minimum instruction + // size to ensure we are in the same scope as the original call opcode. + // + if (pDC->ControlPcIsUnwound) { + +#if defined(_M_ARM_NT) + + Ip -= 2; + +#else + + Ip -= 4; + +#endif // _M_ARM_NT + + } + +#endif // _M_ARM64EC + return Ip; +} + +#else +static uintptr_t adjustIp(DispatcherContext* /*pDC*/, uintptr_t Ip) +{ + return Ip; +} +#endif // (_M_ARM_NT) || defined(_M_ARM64) || defined(_CHPE_X86_ARM64_EH_) || defined(_M_ARM64EC) + +__ehstate_t RENAME_EH_EXTERN(__FrameHandler4)::StateFromIp( + FuncInfo *pFuncInfo, + DispatcherContext *pDC, + uintptr_t Ip +) +{ + unsigned int index; // loop control variable + unsigned int nIPMapEntry; // # of IpMapEntry; must be > 0 + + Ip = adjustIp(pDC, Ip); + + if (pFuncInfo->dispIPtoStateMap == 0) + { + return EH_EMPTY_STATE; + } + + PBYTE buffer = (PBYTE)__RVAtoRealOffset(pDC, pFuncInfo->dispIPtoStateMap); + + nIPMapEntry = FH4::ReadUnsigned(&buffer); + + __ehstate_t prevState = EH_EMPTY_STATE; + unsigned int funcRelIP = 0; + for (index = 0; index < nIPMapEntry; index++) { + // States are delta-encoded relative to start of the function + funcRelIP += FH4::ReadUnsigned(&buffer); + if (Ip < __FuncRelToRealOffset(pDC, funcRelIP)) { + break; + } + // States are encoded +1 so as to not encode a negative + prevState = FH4::ReadUnsigned(&buffer) - 1; + } + + if (index == 0) { + // We are at the first entry, could be an error + return EH_EMPTY_STATE; + } + + // We over-shot one iteration; return state from the previous slot + return prevState; +} + +__ehstate_t RENAME_EH_EXTERN(__FrameHandler3)::StateFromIp( + FuncInfo *pFuncInfo, + DispatcherContext *pDC, + uintptr_t Ip +) +{ + + unsigned int index; // loop control variable + unsigned int nIPMapEntry; // # of IpMapEntry; must be > 0 + + Ip = adjustIp(pDC, Ip); + + _VCRT_VERIFY(pFuncInfo); + nIPMapEntry = FUNC_NIPMAPENT(*pFuncInfo); + + _VCRT_VERIFY(FUNC_IPMAP(*pFuncInfo, pDC->ImageBase)); + + for (index = 0; index < nIPMapEntry; index++) { + IptoStateMapEntry *pIPtoStateMap = FUNC_PIPTOSTATE(*pFuncInfo, index, pDC->ImageBase); + if (Ip < (uintptr_t)__RVAtoRealOffset(pDC, pIPtoStateMap->Ip)) { + break; + } + } + + if (index == 0) { + // We are at the first entry, could be an error + + return EH_EMPTY_STATE; + } + + // We over-shot one iteration; return state from the previous slot + + return FUNC_IPTOSTATE(*pFuncInfo, index - 1, pDC->ImageBase).State; + +} + +__ehstate_t RENAME_EH_EXTERN(__FrameHandler3)::StateFromControlPc( + FuncInfo *pFuncInfo, + DispatcherContext *pDC +) +{ + uintptr_t Ip = pDC->ControlPc; + + return StateFromIp(pFuncInfo, pDC, Ip); +} + +__ehstate_t RENAME_EH_EXTERN(__FrameHandler4)::StateFromControlPc( + FuncInfo *pFuncInfo, + DispatcherContext *pDC +) +{ + uintptr_t Ip = pDC->ControlPc; + + return StateFromIp(pFuncInfo, pDC, Ip); +} + +void RENAME_EH_EXTERN(__FrameHandler3)::SetUnwindTryBlock( + EHRegistrationNode *pRN, + DispatcherContext *pDC, + FuncInfo *pFuncInfo, + int curState +) +{ + EHRegistrationNode EstablisherFramePointers; + EstablisherFramePointers = *RENAME_EH_EXTERN(__FrameHandler3)::GetEstablisherFrame(pRN, pDC, pFuncInfo, &EstablisherFramePointers); + if (curState > UNWINDTRYBLOCK(EstablisherFramePointers, FUNC_DISPUNWINDHELP(*pFuncInfo))) { + UNWINDTRYBLOCK(EstablisherFramePointers, FUNC_DISPUNWINDHELP(*pFuncInfo)) = (int)curState; + } +} + +__ehstate_t RENAME_EH_EXTERN(__FrameHandler3)::GetUnwindTryBlock( + EHRegistrationNode *pRN, + DispatcherContext *pDC, + FuncInfo *pFuncInfo +) +{ + EHRegistrationNode EstablisherFramePointers; + EstablisherFramePointers = *RENAME_EH_EXTERN(__FrameHandler3)::GetEstablisherFrame(pRN, pDC, pFuncInfo, &EstablisherFramePointers); + return UNWINDTRYBLOCK(EstablisherFramePointers, FUNC_DISPUNWINDHELP(*pFuncInfo)); +} + +__ehstate_t RENAME_EH_EXTERN(__FrameHandler3)::GetCurrentState( + EHRegistrationNode *pRN, + DispatcherContext *pDC, + FuncInfo *pFuncInfo +) +{ + if (UNWINDSTATE(*pRN, FUNC_DISPUNWINDHELP(*pFuncInfo)) == -2) { + return RENAME_EH_EXTERN(__FrameHandler3)::StateFromControlPc(pFuncInfo, pDC); + } + else { + return UNWINDSTATE(*pRN, FUNC_DISPUNWINDHELP(*pFuncInfo)); + } +} + +void RENAME_EH_EXTERN(__FrameHandler3)::SetState( + EHRegistrationNode *pRN, + FuncInfo *pFuncInfo, + __ehstate_t newState +) +{ + UNWINDSTATE(*pRN, FUNC_DISPUNWINDHELP(*pFuncInfo)) = newState; +} +#else +__ehstate_t RENAME_EH_EXTERN(__FrameHandler3)::GetCurrentState( + EHRegistrationNode *pRN, + DispatcherContext* /*pDC*/, + FuncInfo *pFuncInfo +) +{ + // In the initial implementation, the state is simply stored in the registration node. + // Added support for byte states when max state <= 128. Note that max state is 1+real max state + if (pFuncInfo->maxState <= 128) + { + return (__ehstate_t)(signed char)((pRN)->state & 0xff); + } + else { + return (pRN)->state; + } +} + +void RENAME_EH_EXTERN(__FrameHandler3)::SetState( + EHRegistrationNode *pRN, + FuncInfo* /*pFuncInfo*/, + __ehstate_t newState +) +{ + pRN->state = newState; +} +#endif diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/ehvccctr.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/ehvccctr.cpp new file mode 100644 index 0000000000000000000000000000000000000000..68cd1fa0c1593861b4a3a4b1f5932521af993fb3 --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/ehvccctr.cpp @@ -0,0 +1,94 @@ +/*** +*ehvccctr.cpp - EH-aware version of copy constructor iterator helper function +* +* Copyright (c) Microsoft Corporation. All rights reserved. +* +*Purpose: +* These functions are called when constructing and destructing arrays of +* objects. Their purpose is to assure that constructed elements get +* destructed if the constructor for one of the elements throws. +* +* Must be compiled using "-d1Binl" to be able to specify __thiscall +* at the user level +****/ + +#include + +/* + * Note that we will be compiling all this with /clr option not /clr:pure + */ +#if defined _M_CEE + #define CALLTYPE __clrcall + #define CALLEETYPE __clrcall + #define __RELIABILITY_CONTRACT \ + [System::Runtime::ConstrainedExecution::ReliabilityContract( \ + System::Runtime::ConstrainedExecution::Consistency::WillNotCorruptState, \ + System::Runtime::ConstrainedExecution::Cer::Success \ + )] +#else + #define CALLEETYPE __stdcall + #define __RELIABILITY_CONTRACT + + #if defined _M_IX86 + #define CALLTYPE __thiscall + #else + #define CALLTYPE __stdcall + #endif +#endif + +using constructor_type = void (CALLTYPE*)(void*, void*); +using destructor_type = void (CALLTYPE*)(void*); + +__RELIABILITY_CONTRACT +void CALLEETYPE __ArrayUnwind( + void* ptr, // Pointer to array to destruct + size_t size, // Size of each element (including padding) + size_t count, // Number of elements in the array + destructor_type destructor // The destructor to call + ); + +__RELIABILITY_CONTRACT +void CALLEETYPE __ehvec_copy_ctor( + void* dst, // Pointer to destination array + void* src, // Pointer to source array + size_t size, // Size of each element (including padding) + size_t count, // Number of elements in the array + constructor_type constructor, // Constructor to call + destructor_type destructor // Destructor to call should exception be thrown + ) +{ + size_t i{0}; + bool success{false}; + + __try + { + for (; i != count; ++i) + { + constructor(dst, src); + dst = static_cast(dst) + size; + src = static_cast(src) + size; + } + + success = true; + } + __finally + { + if (!success) + { + __ArrayUnwind(dst, size, i, destructor); + } + } +} + +__RELIABILITY_CONTRACT +void CALLEETYPE __ehvec_copy_ctor( + void* dst, // Pointer to destination array + void* src, // Pointer to source array + size_t size, // Size of each element (including padding) + int count, // Number of elements in the array + constructor_type constructor, // Constructor to call + destructor_type destructor // Destructor to call should exception be thrown + ) +{ + __ehvec_copy_ctor(dst, src, size, static_cast(count), constructor, destructor); +} diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/ehvcccvb.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/ehvcccvb.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e336244db6fa46f17fd987987082a8515ed257f5 --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/ehvcccvb.cpp @@ -0,0 +1,95 @@ +/*** +*ehvcccvb.cpp - EH copy-ctor iterator helper function for class w/ virtual bases +* +* Copyright (c) Microsoft Corporation. All rights reserved. +* +*Purpose: +* These functions are called when constructing and destructing arrays of +* objects. Their purpose is to assure that constructed elements get +* destructed if the constructor for one of the elements throws. +* +* Must be compiled using "-d1Binl" to be able to specify __thiscall +* at the user level +****/ + +#include + +#if defined _M_CEE + #define CALLTYPE __clrcall + #define CALLEETYPE __clrcall + #define __RELIABILITY_CONTRACT \ + [System::Runtime::ConstrainedExecution::ReliabilityContract( \ + System::Runtime::ConstrainedExecution::Consistency::WillNotCorruptState, \ + System::Runtime::ConstrainedExecution::Cer::Success \ + )] +#else + #define CALLEETYPE __stdcall + #define __RELIABILITY_CONTRACT + + #if defined _M_IX86 + #define CALLTYPE __thiscall + #else + #define CALLTYPE __stdcall + #endif +#endif + +using constructor_type = void (CALLTYPE*)(void*, void*); +using destructor_type = void (CALLTYPE*)(void*); + +__RELIABILITY_CONTRACT +void CALLEETYPE __ArrayUnwind( + void* ptr, // Pointer to array to destruct + size_t size, // Size of each element (including padding) + size_t count, // Number of elements in the array + destructor_type destructor // The destructor to call + ); + +__RELIABILITY_CONTRACT +void CALLEETYPE __ehvec_copy_ctor_vb( + void* dst, // Pointer to destination array + void* src, // Pointer to source array + size_t size, // Size of each element (including padding) + size_t count, // Number of elements in the array + constructor_type constructor, // Constructor to call + destructor_type destructor // Destructor to call should exception be thrown + ) +{ + size_t i{0}; + bool success{false}; + + __try + { + for (; i != count; ++i) + { + #pragma warning(push) + #pragma warning(disable: 4191) // unsafe conversion + reinterpret_cast(constructor)(dst, src, 1); + #pragma warning(pop) + + dst = static_cast(dst) + size; + src = static_cast(src) + size; + } + + success = true; + } + __finally + { + if (!success) + { + __ArrayUnwind(dst, size, i, destructor); + } + } +} + +__RELIABILITY_CONTRACT +void CALLEETYPE __ehvec_copy_ctor_vb( + void* dst, // Pointer to destination array + void* src, // Pointer to source array + size_t size, // Size of each element (including padding) + int count, // Number of elements in the array + constructor_type constructor, // Constructor to call + destructor_type destructor // Destructor to call should exception be thrown + ) +{ + __ehvec_copy_ctor_vb(dst, src, size, static_cast(count), constructor, destructor); +} diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/ehvecctr.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/ehvecctr.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a08460dacf8fa030bd83c590f3c38a013ead3849 --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/ehvecctr.cpp @@ -0,0 +1,89 @@ +/*** +*ehvecctr.cpp - EH-aware version of constructor iterator helper function +* +* Copyright (c) Microsoft Corporation. All rights reserved. +* +*Purpose: +* These functions are called when constructing and destructing arrays of +* objects. Their purpose is to assure that constructed elements get +* destructed if the constructor for one of the elements throws. +* +* Must be compiled using "-d1Binl" to be able to specify __thiscall +* at the user level +****/ + +#include + +#if defined _M_CEE + #define CALLTYPE __clrcall + #define CALLEETYPE __clrcall + #define __RELIABILITY_CONTRACT \ + [System::Runtime::ConstrainedExecution::ReliabilityContract( \ + System::Runtime::ConstrainedExecution::Consistency::WillNotCorruptState, \ + System::Runtime::ConstrainedExecution::Cer::Success \ + )] +#else + #define CALLEETYPE __stdcall + #define __RELIABILITY_CONTRACT + + #if defined _M_IX86 + #define CALLTYPE __thiscall + #else + #define CALLTYPE __stdcall + #endif +#endif + +using constructor_type = void (CALLTYPE*)(void*); +using destructor_type = void (CALLTYPE*)(void*); + +__RELIABILITY_CONTRACT +void CALLEETYPE __ArrayUnwind( + void* ptr, // Pointer to array to destruct + size_t size, // Size of each element (including padding) + size_t count, // Number of elements in the array + destructor_type destructor // The destructor to call + ); + +__RELIABILITY_CONTRACT +void CALLEETYPE __ehvec_ctor( + void* ptr, // Pointer to array to destruct + size_t size, // Size of each element (including padding) + size_t count, // Number of elements in the array + constructor_type constructor, // Constructor to call + destructor_type destructor // Destructor to call should exception be thrown + ) +{ + size_t i{0}; + bool success{false}; + + __try + { + for (; i != count; ++i) + { + constructor(ptr); + + ptr = static_cast(ptr) + size; + } + + success = true; + } + __finally + { + if (!success) + { + __ArrayUnwind(ptr, size, i, destructor); + } + } +} + +__RELIABILITY_CONTRACT +void CALLEETYPE __ehvec_ctor( + void* ptr, // Pointer to array to destruct + size_t size, // Size of each element (including padding) + int count, // Number of elements in the array + constructor_type constructor, // Constructor to call + destructor_type destructor // Destructor to call should exception be thrown + ) +{ + __ehvec_ctor(ptr, size, static_cast(count), constructor, destructor); +} diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/ehveccvb.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/ehveccvb.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2915e80c9c869c63ef1068fa1855902cc90a1f7d --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/ehveccvb.cpp @@ -0,0 +1,99 @@ +/*** +*ehveccvb.cpp - EH c-tor iterator helper function for class w/ virtual bases +* +* Copyright (c) Microsoft Corporation. All rights reserved. +* +*Purpose: +* EH-aware version of constructor iterator helper function for class +* with virtual bases +* +* These functions are called when constructing and destructing arrays of +* objects. Their purpose is to assure that constructed elements get +* destructed if the constructor for one of the elements throws. +* +* These functions are called when constructing and destructing arrays of +* objects. Their purpose is to assure that constructed elements get +* destructed if the constructor for one of the elements throws. +* +* Must be compiled using "-d1Binl" to be able to specify __thiscall +* at the user level +****/ + +#include + +#if defined _M_CEE + #define CALLTYPE __clrcall + #define CALLEETYPE __clrcall + #define __RELIABILITY_CONTRACT \ + [System::Runtime::ConstrainedExecution::ReliabilityContract( \ + System::Runtime::ConstrainedExecution::Consistency::WillNotCorruptState, \ + System::Runtime::ConstrainedExecution::Cer::Success \ + )] +#else + #define CALLEETYPE __stdcall + #define __RELIABILITY_CONTRACT + + #if defined _M_IX86 + #define CALLTYPE __thiscall + #else + #define CALLTYPE __stdcall + #endif +#endif + +using constructor_type = void (CALLTYPE*)(void*); +using destructor_type = void (CALLTYPE*)(void*); + +__RELIABILITY_CONTRACT +void CALLEETYPE __ArrayUnwind( + void* ptr, // Pointer to array to destruct + size_t size, // Size of each element (including padding) + size_t count, // Number of elements in the array + destructor_type destructor // The destructor to call + ); + +__RELIABILITY_CONTRACT +void CALLEETYPE __ehvec_ctor_vb( + void* ptr, // Pointer to array to destruct + size_t size, // Size of each element (including padding) + size_t count, // Number of elements in the array + constructor_type constructor, // Constructor to call + destructor_type destructor // Destructor to call should exception be thrown + ) +{ + size_t i{0}; + bool success{false}; + + __try + { + for (; i != count; ++i) + { + #pragma warning(push) + #pragma warning(disable: 4191) // unsafe conversion + reinterpret_cast(constructor)(ptr, 1); + #pragma warning(pop) + + ptr = static_cast(ptr) + size; + } + + success = true; + } + __finally + { + if (!success) + { + __ArrayUnwind(ptr, size, i, destructor); + } + } +} + +__RELIABILITY_CONTRACT +void CALLEETYPE __ehvec_ctor_vb( + void* ptr, // Pointer to array to destruct + size_t size, // Size of each element (including padding) + int count, // Number of elements in the array + constructor_type constructor, // Constructor to call + destructor_type destructor // Destructor to call should exception be thrown + ) +{ + __ehvec_ctor_vb(ptr, size, static_cast(count), constructor, destructor); +} diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/ehvecdtr.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/ehvecdtr.cpp new file mode 100644 index 0000000000000000000000000000000000000000..aaa99f0e94e0a50983b2e4fc3ae0d7ca98d1b64c --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/ehvecdtr.cpp @@ -0,0 +1,140 @@ +/*** +*ehvecdtr.cpp - EH-aware version of destructor iterator helper function +* +* Copyright (c) Microsoft Corporation. All rights reserved. +* +*Purpose: +* These functions are called when constructing and destructing arrays of +* objects. Their purpose is to assure that constructed elements get +* destructed if the constructor for one of the elements throws. +* +* Must be compiled using "-d1Binl" to be able to specify __thiscall +* at the user level +****/ + +#include +#include +#include + +#if defined _M_CEE + #define CALLTYPE __clrcall + #define CALLEETYPE __clrcall + #define __RELIABILITY_CONTRACT \ + [System::Runtime::ConstrainedExecution::ReliabilityContract( \ + System::Runtime::ConstrainedExecution::Consistency::WillNotCorruptState, \ + System::Runtime::ConstrainedExecution::Cer::Success \ + )] + + #define ASSERT_UNMANAGED_CODE_ATTRIBUTE [System::Security::Permissions::SecurityPermissionAttribute(System::Security::Permissions::SecurityAction::Assert, UnmanagedCode = true)] + #define SECURITYCRITICAL_ATTRIBUTE [System::Security::SecurityCritical] +#else + #define CALLEETYPE __stdcall + #define __RELIABILITY_CONTRACT + #define ASSERT_UNMANAGED_CODE_ATTRIBUTE + #define SECURITYCRITICAL_ATTRIBUTE + + #if defined _M_IX86 + #define CALLTYPE __thiscall + #else + #define CALLTYPE __stdcall + #endif +#endif + +using destructor_type = void (CALLTYPE*)(void*); + +__RELIABILITY_CONTRACT +void CALLEETYPE __ArrayUnwind( + void* ptr, // Pointer to array to destruct + size_t size, // Size of each element (including padding) + size_t count, // Number of elements in the array + destructor_type destructor // The destructor to call + ); + +__RELIABILITY_CONTRACT +SECURITYCRITICAL_ATTRIBUTE +void CALLEETYPE __ehvec_dtor( + void* ptr, // Pointer to array to destruct + size_t size, // Size of each element (including padding) + size_t count, // Number of elements in the array + destructor_type destructor // The destructor to call + ) +{ + bool success{false}; + + // Advance pointer past end of array + ptr = static_cast(ptr) + size * count; + + __try + { + // Destruct elements + while (count-- > 0) + { + ptr = static_cast(ptr) - size; + destructor(ptr); + } + + success = true; + } + __finally + { + if (!success) + { + __ArrayUnwind(ptr, size, count, destructor); + } + } +} + +__RELIABILITY_CONTRACT +ASSERT_UNMANAGED_CODE_ATTRIBUTE +SECURITYCRITICAL_ATTRIBUTE +static int ArrayUnwindFilter(EXCEPTION_POINTERS* pExPtrs) +{ + EHExceptionRecord *pExcept = reinterpret_cast(pExPtrs->ExceptionRecord); + + switch(PER_CODE(pExcept)) + { + case EH_EXCEPTION_NUMBER: + _pCurrentException = pExcept; + _pCurrentExContext = pExPtrs->ContextRecord; + terminate(); + default: + return EXCEPTION_CONTINUE_SEARCH; + } +} + +__RELIABILITY_CONTRACT +SECURITYCRITICAL_ATTRIBUTE +void CALLEETYPE __ArrayUnwind( + void* ptr, // Pointer to array to destruct + size_t size, // Size of each element (including padding) + size_t count, // Number of elements in the array + destructor_type destructor // The destructor to call + ) +{ + // 'unwind' rest of array + + __try + { + for (size_t i{0}; i != count; ++i) + { + ptr = static_cast(ptr) - size; + destructor(ptr); + } + } + __except(ArrayUnwindFilter(exception_info())) + { + ; // Deliberately do nothing + } +} + +__RELIABILITY_CONTRACT +SECURITYCRITICAL_ATTRIBUTE +void CALLEETYPE __ehvec_dtor( + void* ptr, // Pointer to array to destruct + size_t size, // Size of each element (including padding) + int count, // Number of elements in the array + destructor_type destructor // The destructor to call + ) +{ + __ehvec_dtor(ptr, size, static_cast(count), destructor); +} diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/env_mode.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/env_mode.cpp new file mode 100644 index 0000000000000000000000000000000000000000..24f72f6edf6505e2787043e2b64b6e9bc9cb2b6e --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/env_mode.cpp @@ -0,0 +1,16 @@ +// +// env_mode.cpp +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// Specifies whether the environment should be initialized. +// This behavior is overridable at link-time by linking with noenv.obj. +// +#include + + + +extern "C" bool __CRTDECL _should_initialize_environment() +{ + return true; +} diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/exe_common.inl b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/exe_common.inl new file mode 100644 index 0000000000000000000000000000000000000000..0eabb749c4fd8fcb549257ad260caa0befc4b028 --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/exe_common.inl @@ -0,0 +1,331 @@ +// +// exe_common.inl +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// The implementation of the common executable entry point code. There are four +// executable entry points defined by the CRT, one for each of the user-definable +// entry points: +// +// * mainCRTStartup => main +// * wmainCRTStartup => wmain +// * WinMainCRTStartup => WinMain +// * wWinMainCRTStartup => wWinMain +// +// These functions all behave the same, except for which user-definable main +// function they call and whether they accumulate and pass narrow or wide string +// arguments. This file contains the common code shared by all four of those +// entry points. +// +// The actual entry points are defined in four .cpp files alongside this .inl +// file. At most one of these .cpp files will be linked into the resulting +// executable, so we can treat this .inl file as if its contents are only linked +// into the executable once as well. +// +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +//-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +// +// Common main()/WinMain() implementation +// +//-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +struct __scrt_main_policy +{ + static void set_app_type() { _set_app_type(_crt_console_app); } +}; + +struct __scrt_winmain_policy +{ + static void set_app_type() { _set_app_type(_crt_gui_app); } +}; + +struct __scrt_enclavemain_policy +{ + static void set_app_type() { } +}; + +struct __scrt_file_policy +{ + static void set_fmode() { _set_fmode(_get_startup_file_mode()); } + static void set_commode() { _commode = _get_startup_commit_mode(); } +}; + +struct __scrt_nofile_policy +{ + static void set_fmode() { } + static void set_commode() { } +}; + +#if defined _SCRT_STARTUP_MAIN + + using main_policy = __scrt_main_policy; + using file_policy = __scrt_file_policy; + using argv_policy = __scrt_narrow_argv_policy; + using environment_policy = __scrt_narrow_environment_policy; + + static int __cdecl invoke_main() + { + return main(__argc, __argv, _get_initial_narrow_environment()); + } + +#elif defined _SCRT_STARTUP_WMAIN + + using main_policy = __scrt_main_policy; + using file_policy = __scrt_file_policy; + using argv_policy = __scrt_wide_argv_policy; + using environment_policy = __scrt_wide_environment_policy; + + static int __cdecl invoke_main() + { + return wmain(__argc, __wargv, _get_initial_wide_environment()); + } + +#elif defined _SCRT_STARTUP_WINMAIN + + using main_policy = __scrt_winmain_policy; + using file_policy = __scrt_file_policy; + using argv_policy = __scrt_narrow_argv_policy; + using environment_policy = __scrt_narrow_environment_policy; + + static int __cdecl invoke_main() + { + return WinMain( + reinterpret_cast(&__ImageBase), + nullptr, + _get_narrow_winmain_command_line(), + __scrt_get_show_window_mode()); + } + +#elif defined _SCRT_STARTUP_WWINMAIN + + using main_policy = __scrt_winmain_policy; + using file_policy = __scrt_file_policy; + using argv_policy = __scrt_wide_argv_policy; + using environment_policy = __scrt_wide_environment_policy; + + static int __cdecl invoke_main() + { + return wWinMain( + reinterpret_cast(&__ImageBase), + nullptr, + _get_wide_winmain_command_line(), + __scrt_get_show_window_mode()); + } + +#elif defined _SCRT_STARTUP_ENCLAVE || defined _SCRT_STARTUP_WENCLAVE + + using main_policy = __scrt_enclavemain_policy; + using file_policy = __scrt_nofile_policy; + using argv_policy = __scrt_no_argv_policy; + using environment_policy = __scrt_no_environment_policy; + +#if defined _SCRT_STARTUP_ENCLAVE + static int __cdecl invoke_main() + { + return main(0, nullptr, nullptr); + } +#else + static int __cdecl invoke_main() + { + return wmain(0, nullptr, nullptr); + } +#endif + +#endif + +static int __cdecl pre_c_initialization() +{ + main_policy::set_app_type(); + + file_policy::set_fmode(); + file_policy::set_commode(); + + if (!__scrt_initialize_onexit_tables(__scrt_module_type::exe)) + __scrt_fastfail(FAST_FAIL_FATAL_APP_EXIT); + + #ifdef _M_IX86 + // Clear the x87 exception flags. Any other floating point initialization + // should already have taken place before this function is called. + _asm { fnclex } + #endif + + #ifdef _RTC + _RTC_Initialize(); + atexit(_RTC_Terminate); + #endif + + if (argv_policy::configure_argv() != 0) + __scrt_fastfail(FAST_FAIL_FATAL_APP_EXIT); + + __scrt_initialize_type_info(); + + // If the user provided a _matherr handler, register it with the Universal + // CRT. Windows OS components cannot set a custom matherr handler (this is + // a policy decision, to reduce complexity). + #ifndef _CRT_WINDOWS + if (__scrt_is_user_matherr_present()) + { + __setusermatherr(_matherr); + } + #endif + + _initialize_invalid_parameter_handler(); + _initialize_denormal_control(); + + #ifdef _M_IX86 + _initialize_default_precision(); + #endif + + _configthreadlocale(_get_startup_thread_locale_mode()); + + if (_should_initialize_environment()) + environment_policy::initialize_environment(); + + __scrt_initialize_winrt(); + + if (__scrt_initialize_mta() != 0) + { + __scrt_fastfail(FAST_FAIL_FATAL_APP_EXIT); + } + + return 0; +} + +static int __cdecl post_pgo_initialization() +{ + // This function calls the __local_stdio_{printf,scanf}_options() functions. + // These functions are defined in public headers with external linkage and + // thus may be PGO-instrumented. We must not call these functions before the + // PGO instrumentation library is initialized. + __scrt_initialize_default_local_stdio_options(); + + return 0; +} + +static void __cdecl pre_cpp_initialization() +{ + // Before we begin C++ initialization, set the unhandled exception + // filter so that unhandled C++ exceptions result in std::terminate + // being called: + __scrt_set_unhandled_exception_filter(); + + _set_new_mode(_get_startup_new_mode()); +} + +// When both the PGO instrumentation library and the CRT are statically linked, +// PGO will initialize itself in XIAB. We do most pre-C initialization before +// PGO is initialized, but defer some initialization steps to after. See the +// commentary in post_pgo_initialization for details. +_CRTALLOC(".CRT$XIAA") static _PIFV pre_c_initializer = pre_c_initialization; +_CRTALLOC(".CRT$XIAC") static _PIFV post_pgo_initializer = post_pgo_initialization; +_CRTALLOC(".CRT$XCAA") static _PVFV pre_cpp_initializer = pre_cpp_initialization; + + + +static __declspec(noinline) int __cdecl __scrt_common_main_seh() +{ + if (!__scrt_initialize_crt(__scrt_module_type::exe)) + __scrt_fastfail(FAST_FAIL_FATAL_APP_EXIT); + + bool has_cctor = false; + __try + { + bool const is_nested = __scrt_acquire_startup_lock(); + + if (__scrt_current_native_startup_state == __scrt_native_startup_state::initializing) + { + __scrt_fastfail(FAST_FAIL_FATAL_APP_EXIT); + } + else if (__scrt_current_native_startup_state == __scrt_native_startup_state::uninitialized) + { + __scrt_current_native_startup_state = __scrt_native_startup_state::initializing; + + if (_initterm_e(__xi_a, __xi_z) != 0) + return 255; + + _initterm(__xc_a, __xc_z); + + __scrt_current_native_startup_state = __scrt_native_startup_state::initialized; + } + else + { + has_cctor = true; + } + + __scrt_release_startup_lock(is_nested); + + // If this module has any dynamically initialized __declspec(thread) + // variables, then we invoke their initialization for the primary thread + // used to start the process: + _tls_callback_type const* const tls_init_callback = __scrt_get_dyn_tls_init_callback(); + if (*tls_init_callback != nullptr && __scrt_is_nonwritable_in_current_image(tls_init_callback)) + { + (*tls_init_callback)(nullptr, DLL_THREAD_ATTACH, nullptr); + } + + // If this module has any thread-local destructors, register the + // callback function with the Unified CRT to run on exit. + _tls_callback_type const * const tls_dtor_callback = __scrt_get_dyn_tls_dtor_callback(); + if (*tls_dtor_callback != nullptr && __scrt_is_nonwritable_in_current_image(tls_dtor_callback)) + { + _register_thread_local_exe_atexit_callback(*tls_dtor_callback); + } + + // + // Initialization is complete; invoke main... + // + + int const main_result = invoke_main(); + + // + // main has returned; exit somehow... + // + + if (!__scrt_is_managed_app()) + exit(main_result); + + if (!has_cctor) + _cexit(); + + // Finally, we terminate the CRT: + __scrt_uninitialize_crt(true, false); + return main_result; + } + __except (_seh_filter_exe(GetExceptionCode(), GetExceptionInformation())) + { + // Note: We should never reach this except clause. + int const main_result = GetExceptionCode(); + + if (!__scrt_is_managed_app()) + _exit(main_result); + + if (!has_cctor) + _c_exit(); + + return main_result; + } +} + + + +// This is the common main implementation to which all of the CRT main functions +// delegate (for executables; DLLs are handled separately). +static __forceinline int __cdecl __scrt_common_main() +{ + // The /GS security cookie must be initialized before any exception handling + // targeting the current image is registered. No function using exception + // handling can be called in the current image until after this call: + __security_init_cookie(); + + return __scrt_common_main_seh(); +} diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/exe_main.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/exe_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0a73696609f1874d4792113a95bde92a821f76a5 --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/exe_main.cpp @@ -0,0 +1,17 @@ +// +// exe_main.cpp +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// The mainCRTStartup() entry point, linked into client executables that +// uses main(). +// +#define _SCRT_STARTUP_MAIN +#include "exe_common.inl" + + + +extern "C" DWORD mainCRTStartup(LPVOID) +{ + return __scrt_common_main(); +} diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/exe_winmain.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/exe_winmain.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5d7317179cec29acf6c2ffbd23d7a46287322f73 --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/exe_winmain.cpp @@ -0,0 +1,17 @@ +// +// exe_winmain.cpp +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// The WinMainCRTStartup() entry point, linked into a client executable that +// uses WinMain(). +// +#define _SCRT_STARTUP_WINMAIN +#include "exe_common.inl" + + + +extern "C" DWORD WinMainCRTStartup(LPVOID) +{ + return __scrt_common_main(); +} diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/exe_wmain.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/exe_wmain.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3101f0de34f0ceef3b42e450c9ce7e9e8fbf5c75 --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/exe_wmain.cpp @@ -0,0 +1,17 @@ +// +// exe_wmain.cpp +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// The wmainCRTStartup() entry point, linked into client executables that +// uses wmain(). +// +#define _SCRT_STARTUP_WMAIN +#include "exe_common.inl" + + + +extern "C" DWORD wmainCRTStartup(LPVOID) +{ + return __scrt_common_main(); +} diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/exe_wwinmain.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/exe_wwinmain.cpp new file mode 100644 index 0000000000000000000000000000000000000000..134f23b28a223045281fcdd6b18d9a1c80a27a8d --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/exe_wwinmain.cpp @@ -0,0 +1,17 @@ +// +// exe_wwinmain.cpp +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// The wWinMainCRTStartup() entry point, linked into client executables that +// uses wWinMain(). +// +#define _SCRT_STARTUP_WWINMAIN +#include "exe_common.inl" + + + +extern "C" DWORD wWinMainCRTStartup(LPVOID) +{ + return __scrt_common_main(); +} diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/file_mode.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/file_mode.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9ec55a7f801549d416cd069bf383adf9973d9cab --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/file_mode.cpp @@ -0,0 +1,17 @@ +// +// file_mode.cpp +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// Gets the default file open mode, used during executable startup. This +// behavior is overridable at link-time by linking with one of the link options. +// +#include +#include + + + +extern "C" int __CRTDECL _get_startup_file_mode() +{ + return _O_TEXT; +} diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/fltused.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/fltused.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e0130453284167ef2fdc2a40bf28c2a9927b0ec0 --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/fltused.cpp @@ -0,0 +1,9 @@ +// +// fltused.cpp +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// Default definition of _fltused. +// + +extern "C" int _fltused{0x9875}; diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/frame.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/frame.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9fafc667058a23e7fc83824a53722a7066f0d665 --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/frame.cpp @@ -0,0 +1,2162 @@ +/*** +*frame.cpp - The frame handler and everything associated with it. +* +* Copyright (c) Microsoft Corporation. All rights reserved. +* +*Purpose: +* The frame handler and everything associated with it. +* +* Entry points: +* _CxxFrameHandler - the frame handler. +* +* Open issues: +* Handling re-throw from dynamically nested scope. +* Fault-tolerance (checking for data structure validity). +****/ + +#include // User-visible routines for eh +#include // This project's versions of standard assert macros +#include // Declarations of all types used for EH +#include +#include // Declarations of hook variables and callbacks +#include // Routines to handle transfer of control (trnsctrl.asm) +#include +#include + +#include +#include +#include "ehhelpers.h" + +#if defined(_M_ARM64EC) +#include //PDISPATCHER_CONTEXT_ARM64EC +#include +#endif + +// Make non-namespace prefixed names available for FH4 +using namespace FH4; + +// The CallUnexpected function is only called in some build configurations. +#pragma warning(disable: 4505) // unreferenced local function has been removed +#pragma warning(disable: 4702) // unreachable code + +#define cxxReThrow (RENAME_BASE_PTD(__vcrt_getptd)()->_cxxReThrow) + + +//////////////////////////////////////////////////////////////////////////////// +// +// Intel x86-specific definitions +// +#if defined(_M_IX86) && !defined(_CHPE_X86_ARM64_EH_) + +void RENAME_EH_EXTERN(__FrameHandler3)::FrameUnwindToEmptyState( + EHRegistrationNode *pRN, + DispatcherContext *pDC, + FuncInfo *pFuncInfo +) +{ + FrameUnwindToState(pRN, pDC, pFuncInfo, EH_EMPTY_STATE); +} + +//////////////////////////////////////////////////////////////////////////////// +// +// x64/arm/arm64-specific definitions +// +#elif _EH_RELATIVE_FUNCINFO + +#define FUNC_ESTYPES(fi) ((fi).dispESTypeList ? FUNC_ESTYPES_IB(fi, _GetImageBase()) : nullptr ) +#define FUNC_PESTYPES(fi) ((*(fi)).dispESTypeList ? FUNC_PESTYPES_IB((fi), _GetImageBase()) : nullptr ) + +#if _EH_RELATIVE_TYPEINFO + +// The throw site +#undef CT_PTD +#define CT_PTD(ct) (CT_PTD_IB(ct, _GetThrowImageBase())) +#undef CT_COPYFUNC +#define CT_COPYFUNC(ct) ((ct).copyFunction? CT_COPYFUNC_IB(ct, _GetThrowImageBase()):nullptr) + +#define EST_ARRAY(x,n) EST_ARRAY_IB(x, _GetImageBase(), n) + +#undef THROW_FORWARDCOMPAT +#define THROW_FORWARDCOMPAT(ti) ((ti).pForwardCompat? THROW_FORWARDCOMPAT_IB(ti, _GetThrowImageBase()):nullptr) + +#endif // _EH_RELATIVE_TYPEINFO + +// The catch site +#undef HT_HANDLER +#define HT_HANDLER(ht) (HT_HANDLER_IB(ht, _GetImageBase())) +#undef UWE_ACTION +#define UWE_ACTION(uwe) ((uwe).action? UWE_ACTION_IB(uwe, _GetImageBase()):nullptr) + +#undef FUNC_UNWIND +#define FUNC_UNWIND(fi,st) (FUNC_PUNWINDMAP(fi,_GetImageBase())[st]) +#undef TBME_CATCH +#define TBME_CATCH(hm,n) (TBME_PLIST(hm,_GetImageBase())[n]) +#undef TBME_PCATCH +#define TBME_PCATCH(hm,n) (&(TBME_PLIST(hm,_GetImageBase())[n])) + +#undef HT_PTD +#define HT_PTD(ht) ((TypeDescriptor*)((ht).dispType? HT_PTD_IB(ht,_GetImageBase()):nullptr)) + +#undef abnormal_termination +#define abnormal_termination() FALSE + +#else +#error Unrecognized platform +#endif + +extern "C" { +typedef struct { + unsigned long dwSig; + unsigned long uoffDestination; + unsigned long dwCode; + unsigned long uoffFramePointer; +} _NLG_INFO; + +extern _NLG_INFO _NLG_Destination; +} + +//////////////////////////////////////////////////////////////////////////////// +// +// Forward declaration of local functions: +// + +template +static void FindHandler( + EHExceptionRecord *, + EHRegistrationNode *, + CONTEXT *, + DispatcherContext *, + typename T::FuncInfo *, + BOOLEAN, + int, + EHRegistrationNode* +); + +template +static void CatchIt( + EHExceptionRecord *, + EHRegistrationNode *, + CONTEXT *, + DispatcherContext *, + typename T::FuncInfo *, + typename T::HandlerType *, + CatchableType *, + typename T::TryBlockMapEntry *, + int, + EHRegistrationNode *, + BOOLEAN, + BOOLEAN +); + +static void * CallCatchBlock( + EHExceptionRecord *, + EHRegistrationNode *, + CONTEXT *, + FuncInfo *, + void *, + int, + unsigned long +); + +template +static void FindHandlerForForeignException( + EHExceptionRecord *, + EHRegistrationNode *, CONTEXT *, + DispatcherContext *, + typename T::FuncInfo *, + __ehstate_t, + int, + EHRegistrationNode * +); + +static int ExFilterRethrow( + EXCEPTION_POINTERS * +#if _EH_RELATIVE_FUNCINFO + ,EHExceptionRecord *, + int * +#endif +); + +#if _EH_RELATIVE_FUNCINFO +static int ExFilterRethrowFH4( + EXCEPTION_POINTERS *, + EHExceptionRecord *, + __ehstate_t, + int * +); +#endif + +static BOOLEAN IsInExceptionSpec( + EHExceptionRecord *pExcept, // Information for this (logical) + // exception + ESTypeList *pFuncInfo // Static information for subject frame +); + +static void CallUnexpected(ESTypeList* pESTypeList); + +static BOOLEAN Is_bad_exception_allowed(ESTypeList *pExceptionSpec); + +// +// This describes the most recently handled exception, in case of a rethrow: +// +#define _pCurrentFuncInfo (*((ESTypeList **)&(RENAME_BASE_PTD(__vcrt_getptd)()->_curexcspec))) + +inline ESTypeList* RENAME_EH_EXTERN(__FrameHandler3)::getESTypes(FuncInfo* pFuncInfo) +{ + return FUNC_PESTYPES(pFuncInfo); +} + +//////////////////////////////////////////////////////////////////////////////// +// +// __InternalCxxFrameHandlerWrapper - Wraps the frame handler so we have a place +// to apply cleanup on this function + +template +EXCEPTION_DISPOSITION __InternalCxxFrameHandlerWrapper( + EHExceptionRecord* pExcept, // Information for this exception + EHRegistrationNode* pRN, // Dynamic information for this frame + CONTEXT* pContext, // Context info + DispatcherContext* pDC, // Context within subject frame + typename T::FuncInfo* pFuncInfo, // Static information for this frame + int CatchDepth, // How deeply nested are we? + EHRegistrationNode* pMarkerRN, // Marker node for when checking inside catch block + BOOLEAN recursive // Are we handling a translation? +) { + +#if defined(_M_HYBRID_X86_ARM64) && !defined(_CHPE_X86_ARM64_EH_) + _HybridGenerateThunks(__InternalCxxFrameHandlerWrapper, 1); +#endif + + if constexpr (std::is_same_v) + { + EXCEPTION_DISPOSITION retVal{}; + + __try + { + retVal = __InternalCxxFrameHandler(pExcept, pRN, pContext, pDC, pFuncInfo, CatchDepth, pMarkerRN, recursive); + } + __finally + { +#if _VCRT_BUILD_FH4 + // For FrameHandler4, this value should always be invalid past an invocation of this function. + CatchStateInParent = INVALID_CATCH_SPECIFIC_STATE; +#endif + } + + return retVal; + } + else + { + // Compile-time disable the __try/__finally unless we need it. On x86 even a no-op finally triggers a call + // to local_unwind and can change behavior of the handler. + return __InternalCxxFrameHandler(pExcept, pRN, pContext, pDC, pFuncInfo, CatchDepth, pMarkerRN, recursive); + } +} + +//////////////////////////////////////////////////////////////////////////////// +// +// __InternalCxxFrameHandler - the frame handler for all functions with C++ EH +// information. +// +// If exception is handled, this doesn't return; otherwise, it returns +// ExceptionContinueSearch. +// +// Note that this is called three ways: +// From __CxxFrameHandler: primary usage, called to inspect whole function. +// CatchDepth == 0, pMarkerRN == nullptr +// From CatchGuardHandler: If an exception occurred within a catch, this is +// called to check for try blocks within that catch only, and does not +// handle unwinds. +// From TranslatorGuardHandler: Called to handle the translation of a +// non-C++ EH exception. Context considered is that of parent. + +template +EXCEPTION_DISPOSITION __InternalCxxFrameHandler( + EHExceptionRecord *pExcept, // Information for this exception + EHRegistrationNode *pRN, // Dynamic information for this frame + CONTEXT *pContext, // Context info + DispatcherContext *pDC, // Context within subject frame + typename T::FuncInfo *pFuncInfo, // Static information for this frame + int CatchDepth, // How deeply nested are we? + EHRegistrationNode *pMarkerRN, // Marker node for when checking inside catch block + BOOLEAN recursive // Are we handling a translation? +) { + +#if defined(_M_HYBRID_X86_ARM64) && !defined(_CHPE_X86_ARM64_EH_) + _HybridGenerateThunks(__InternalCxxFrameHandler, 1); +#endif + + EHTRACE_FMT2("%s, pRN = 0x%p", + IS_UNWINDING(PER_FLAGS(pExcept)) ? "Unwinding" : "Searching", + pRN); + + __except_validate_context_record(pContext); + + if ((cxxReThrow == false) && (PER_CODE(pExcept) != EH_EXCEPTION_NUMBER) && +#if defined(_M_X64) || defined(_M_ARM) || defined(_M_ARM64) || defined(_M_HYBRID) + /* On the 64 bit/ARM platforms, ExceptionCode maybe set to STATUS_UNWIND_CONSOLIDATE + when called from _UnwindNestedFrames during Logical Unwind. _UnwindNestedFrames + will also set EH_MAGIC_NUMBER1 in the 8 element */ + (!((PER_CODE(pExcept) == STATUS_UNWIND_CONSOLIDATE) && (PER_NPARAMS(pExcept) == 15) && (PER_EXCEPTINFO(pExcept)[8] == EH_MAGIC_NUMBER1))) && +#endif + (PER_CODE(pExcept) != STATUS_LONGJUMP) && + (T::getMagicNum(pFuncInfo) >= EH_MAGIC_NUMBER3) && + (T::isEHs(pFuncInfo))) + { + /* + * This function was compiled /EHs so we don't need to do anything in + * this handler. + */ + return ExceptionContinueSearch; + } + + if (IS_UNWINDING(PER_FLAGS(pExcept))) + { + // We're at the unwinding stage of things. Don't care about the + // exception itself. (Check this first because it's easier) + + if (T::GetMaxState(pDC, pFuncInfo) != 0 && CatchDepth == 0) + { + // Only unwind if there's something to unwind + // AND we're being called through the primary RN. + +#if _EH_RELATIVE_FUNCINFO + if (IS_TARGET_UNWIND(PER_FLAGS(pExcept)) && PER_CODE(pExcept) == STATUS_LONGJUMP) { + __ehstate_t target_state = T::StateFromIp( + pFuncInfo, + pDC, +#if defined(_M_X64) + pDC->TargetIp +#elif defined(_M_ARM) || defined(_M_ARM64) || defined(_CHPE_X86_ARM64_EH_) + pDC->TargetPc +#endif + ); + + _VCRT_VERIFY(target_state >= EH_EMPTY_STATE && target_state < T::GetMaxState(pDC, pFuncInfo)); + T::FrameUnwindToState(pRN, pDC, pFuncInfo, target_state); + EHTRACE_HANDLER_EXIT(ExceptionContinueSearch); + return ExceptionContinueSearch; + } + + if(IS_TARGET_UNWIND(PER_FLAGS(pExcept)) && PER_CODE(pExcept) == STATUS_UNWIND_CONSOLIDATE) + { + PEXCEPTION_RECORD pSehExcept = (PEXCEPTION_RECORD)pExcept; + __ehstate_t target_state = (__ehstate_t)pSehExcept->ExceptionInformation[3]; + + _VCRT_VERIFY(target_state >= EH_EMPTY_STATE && target_state < T::GetMaxState(pDC, pFuncInfo)); + T::FrameUnwindToState((EHRegistrationNode *)pSehExcept->ExceptionInformation[1], + pDC, + pFuncInfo, + target_state); + EHTRACE_HANDLER_EXIT(ExceptionContinueSearch); + return ExceptionContinueSearch; + } +#endif // _EH_RELATIVE_FUNCINFO + T::FrameUnwindToEmptyState(pRN, pDC, pFuncInfo); + } + EHTRACE_HANDLER_EXIT(ExceptionContinueSearch); + return ExceptionContinueSearch; // I don't think this value matters + } + +#if _EH_RELATIVE_FUNCINFO + auto tryBlockMap = T::TryBlockMap(pFuncInfo, pDC->ImageBase); +#else + auto tryBlockMap = T::TryBlockMap(pFuncInfo, 0); +#endif + if (tryBlockMap.getNumTryBlocks() != 0 + // + // If the function has no try block, we still want to call the + // frame handler if there is an exception specification + // + || (T::getMagicNum(pFuncInfo) >= EH_MAGIC_NUMBER2 && (T::getESTypes(pFuncInfo))) + || (T::getMagicNum(pFuncInfo) >= EH_MAGIC_NUMBER3 && (T::isNoExcept(pFuncInfo) != 0))) + { + + // NT is looking for handlers. We've got handlers. + // Let's check this puppy out. Do we recognize it? + + if (PER_CODE(pExcept) == EH_EXCEPTION_NUMBER + && PER_NPARAMS(pExcept) >= 3 + && PER_MAGICNUM(pExcept) > EH_MAGIC_NUMBER3) + { + const auto pfn = THROW_FORWARDCOMPAT(*PER_PTHROW(pExcept)); + if (pfn) { + // Forward compatibility: The thrown object appears to have been + // created by a newer version of our compiler. Let that version's + // frame handler do the work (if one was specified). + + EXCEPTION_DISPOSITION result = (EXCEPTION_DISPOSITION)pfn(pExcept, pRN, pContext, pDC, pFuncInfo, + CatchDepth, pMarkerRN, recursive); + EHTRACE_HANDLER_EXIT(result); + return result; + } + } + + // Anything else: we'll handle it here. + FindHandler(pExcept, pRN, pContext, pDC, pFuncInfo, recursive, CatchDepth, pMarkerRN); + } + + // We had nothing to do with it or it was rethrown. Keep searching. + EHTRACE_HANDLER_EXIT(ExceptionContinueSearch); + return ExceptionContinueSearch; + +} // __InternalCxxFrameHandler + +template EXCEPTION_DISPOSITION __InternalCxxFrameHandlerWrapper( + EHExceptionRecord *pExcept, + EHRegistrationNode *pRN, + CONTEXT *pContext, + DispatcherContext *pDC, + RENAME_EH_EXTERN(__FrameHandler3)::FuncInfo *pFuncInfo, + int CatchDepth, + EHRegistrationNode *pMarkerRN, + BOOLEAN recursive + ); + +#if _VCRT_BUILD_FH4 +template EXCEPTION_DISPOSITION __InternalCxxFrameHandlerWrapper( + EHExceptionRecord *pExcept, + EHRegistrationNode *pRN, + CONTEXT *pContext, + DispatcherContext *pDC, + RENAME_EH_EXTERN(__FrameHandler4)::FuncInfo *pFuncInfo, + int CatchDepth, + EHRegistrationNode *pMarkerRN, + BOOLEAN recursive + ); +#endif // _VCRT_BUILD_FH4 + +/* +* Here We find what is the actual State of current function. The way we +* do this is first get State from ControlPc. +* +* Remember we have __GetUnwindTryBlock to remember the last State for which +* Exception was handled and __GetCurrentState for retrieving the current +* state of the function. Please Note that __GetCurrentState is used +* primarily for unwinding purpose. +* +* Also remember that all the catch blocks act as funclets. This means that +* ControlPc for all the catch blocks are different from ControlPc of parent +* catch block or function. +* +* take a look at this example +* try { +* // STATE1 = 1 +* try { +* // STATE2 +* // THROW +* } catch (...) { // CatchB1 +* // STATE3 +* // RETHROW OR NEW THROW +* } +* } catch (...) { // CatchB2 +* } +* +* If we have an exception coming from STATE3, the FindHandler will be +* called for CatchB1, at this point we do the test which State is our +* real state, curState from ControlPc or state from __GetUnwindTryBlock. +* Since curState from ControlPc is greater, we know that real State is +* curState from ControlPc and thus we update the UnwindTryBlockState. +* +* On further examination, we found out that there is no handler within +* this catch block, we return without handling the exception. For more +* info on how we determine if we have handler, have a look at +* GetRangeOfTrysToCheck. +* +* Now FindHandler will again be called for parent function. Here again +* we test which is real State, state from ControlPc or State from +* __GetUnwindTryBlock. This time state from __GetUnwindTryBlock is correct. +* +* Also look at code in __CxxCallCatchBlock, you will see that as soon as we get +* out of last catch block, we reset __GetUnwindTryBlock state to -1. +*/ + +#if _EH_RELATIVE_FUNCINFO +inline __ehstate_t RENAME_EH_EXTERN(__FrameHandler3)::GetHandlerSearchState( + EHRegistrationNode *pRN, + DispatcherContext *pDC, + FuncInfo *pFuncInfo + ) +{ + __ehstate_t curState = StateFromControlPc(pFuncInfo, pDC); + EHRegistrationNode EstablisherFrame; + GetEstablisherFrame(pRN, pDC, pFuncInfo, &EstablisherFrame); + if (curState > GetUnwindTryBlock(pRN, pDC, pFuncInfo)) { + SetState(&EstablisherFrame, pFuncInfo, curState); + SetUnwindTryBlock(pRN, pDC, pFuncInfo, /*curTry*/ curState); + } else { + curState = GetUnwindTryBlock(pRN, pDC, pFuncInfo); + } + + return curState; +} + +#if _VCRT_BUILD_FH4 +inline __ehstate_t RENAME_EH_EXTERN(__FrameHandler4)::GetHandlerSearchState( + EHRegistrationNode* /*pRN*/, + DispatcherContext *pDC, + FuncInfo *pFuncInfo +) +{ + __ehstate_t curState = StateFromControlPc(pFuncInfo, pDC); + + if (pDC->ScopeIndex != 0) + { + // ScopeIndex state from collided unwinds take precedence-there should also + // be no _CatchStateInParent to use at all + _VCRT_VERIFY(CatchStateInParent == INVALID_CATCH_SPECIFIC_STATE); + curState = (__ehstate_t)pDC->ScopeIndex - SCOPE_INDEX_SHIFT_VALUE; + } + else if (CatchStateInParent != INVALID_CATCH_SPECIFIC_STATE) + { + curState = CatchStateInParent; + CatchStateInParent = INVALID_CATCH_SPECIFIC_STATE; + } + + return curState; +} +#endif // _VCRT_BUILD_FH4 +#endif // _EH_RELATIVE_FUNCINFO + +template +static void FindHandler( + EHExceptionRecord *pExcept, // Information for this (logical) + // exception + EHRegistrationNode *pRN, // Dynamic information for subject frame + CONTEXT *pContext, // Context info + DispatcherContext *pDC, // Context within subject frame + typename T::FuncInfo *pFuncInfo, // Static information for subject frame + BOOLEAN recursive, // TRUE if we're handling the + // translation + int CatchDepth, // Level of nested catch that is being + // checked + EHRegistrationNode *pMarkerRN // Extra marker RN for nested catch + // handling +) +{ + +#if defined(_M_HYBRID_X86_ARM64) && !defined(_CHPE_X86_ARM64_EH_) + _HybridGenerateThunks(FindHandler, 1); +#endif + + BOOLEAN IsRethrow = FALSE; + + // Get the current state (machine-dependent) + __ehstate_t curState = EH_EMPTY_STATE; +#if _EH_RELATIVE_FUNCINFO + curState = T::GetHandlerSearchState(pRN, pDC, pFuncInfo); +#else + curState = T::GetCurrentState(pRN, pDC, pFuncInfo); +#endif + _VCRT_VERIFY(curState >= EH_EMPTY_STATE && curState < T::GetMaxState(pDC, pFuncInfo)); + + // Check if it's a re-throw. Use the exception we stashed away if it is. + if (PER_IS_MSVC_EH(pExcept) && PER_PTHROW(pExcept) == nullptr) { + + if (_pCurrentException == nullptr) { + // Oops! User re-threw a non-existent exception! Let it propagate. + return; + } + + pExcept = _pCurrentException; + pContext = _pCurrentExContext; + IsRethrow = TRUE; +#if _EH_RELATIVE_TYPEINFO + _SetThrowImageBase((ptrdiff_t)pExcept->params.pThrowImageBase); +#endif + + _VCRT_VERIFY(pExcept && (!PER_IS_MSVC_EH(pExcept) || PER_PTHROW(pExcept))); + + // + // We know it is a rethrow -- did we come here as a result of an + // exception re-thrown from CallUnexpected() ? + // + if (_pCurrentFuncInfo) + { + ESTypeList* pCurrentFuncInfo = _pCurrentFuncInfo; // remember it in a local variable + _pCurrentFuncInfo = nullptr; // and reset it immediately -- so we don't forget to do it later + + // Does the exception thrown by CallUnexpected belong to the exception specification? + + if (IsInExceptionSpec(pExcept, pCurrentFuncInfo)) + { + // Yes it does -- so "continue the search for another handler at the call of the function + // whose exception-specification was violated" + ; + } + else + { + // Nope, it does not. Is std::bad_exception allowed by the spec? + + if (Is_bad_exception_allowed(pCurrentFuncInfo)) + { + // yup -- so according to the standard, we need to replace the thrown + // exception by an implementation-defined object of the type std::bad_exception + // and continue the search for another handler at the call of the function + // whose exception-specification was violated. + + // Just throw bad_exception -- we will then come into FindHandler for the third time -- + // but make sure we will not get here again + + __DestructExceptionObject(pExcept, TRUE); // destroy the original object + + throw std::bad_exception(); + } + else + { + terminate(); + } + } + } + } + +#if _EH_RELATIVE_FUNCINFO + auto tryBlockMap = T::TryBlockMap(pFuncInfo, pDC->ImageBase); +#else + auto tryBlockMap = T::TryBlockMap(pFuncInfo, 0); +#endif + + if (PER_IS_MSVC_EH(pExcept)) { + // Looks like it's ours. Let's see if we have a match: + // + // First, determine range of try blocks to consider: + // Only try blocks which are at the current catch depth are of interest. + + if (tryBlockMap.getNumTryBlocks() > 0) + { + auto startStop = T::GetRangeOfTrysToCheck(tryBlockMap, curState, pDC, pFuncInfo, CatchDepth); + // Scan the try blocks in the function: + for (auto iter = startStop.first; iter < startStop.second; ++iter) { + auto tryBlock = *iter; + +#if _EH_RELATIVE_TYPEINFO + __int32 const *ppCatchable; +#else + CatchableType * const *ppCatchable; +#endif + CatchableType *pCatchable; + + if (tryBlock.tryLow > curState || curState > tryBlock.tryHigh) { + continue; + } + + // Try block was in scope for current state. Scan catches for this + // try: +#if _EH_RELATIVE_FUNCINFO + auto handlerMap = T::HandlerMap(&tryBlock, pDC->ImageBase, pDC->FunctionEntry->BeginAddress); +#else + auto handlerMap = T::HandlerMap(&tryBlock, 0, 0); +#endif + for (auto handler : handlerMap) + { + // Scan all types that thrown object can be converted to: + ppCatchable = THROW_CTLIST(*PER_PTHROW(pExcept)); + for (int catchables = THROW_COUNT(*PER_PTHROW(pExcept)); + catchables > 0; catchables--, ppCatchable++) { + +#if _EH_RELATIVE_TYPEINFO + pCatchable = (CatchableType *)(_GetThrowImageBase() + *ppCatchable); +#else + pCatchable = *ppCatchable; +#endif + + if (!T::TypeMatch(&handler, pCatchable, PER_PTHROW(pExcept))) { + continue; + } + + // OK. We finally found a match. Activate the catch. If + // control gets back here, the catch did a re-throw, so + // keep searching. + CatchIt(pExcept, + pRN, + pContext, + pDC, + pFuncInfo, + &handler, + pCatchable, + &tryBlock, + CatchDepth, + pMarkerRN, + IsRethrow, + recursive + ); + goto NextTryBlock; + + } // Scan possible conversions + } // Scan catch clauses + NextTryBlock: ; + } // Scan try blocks + } // if FUNC_NTRYBLOCKS( pFuncInfo ) > 0 +#if defined(_DEBUG) + else + { + // + // This can only happen if the function has an exception specification + // but no try/catch blocks + // + _VCRT_VERIFY(T::getMagicNum(pFuncInfo) >= EH_MAGIC_NUMBER2 + && (T::isNoExcept(pFuncInfo) || T::getESTypes(pFuncInfo))); + } +#endif + +#if defined(_M_IX86) && !defined(_CHPE_X86_ARM64_EH_) + if (recursive) { + // + // A translation was provided, but this frame didn't catch it. + // Destruct the translated object before returning; if destruction + // raises an exception, terminate. + // + // This is not done for Win64 platforms. On those, the translated + // object is destructed in __CxxCallCatchBlock. + // + __DestructExceptionObject(pExcept, TRUE); + } +#endif + + // We did not find a handler in this function. Or, we found a handler and that + // handler re-threw the exception, so we returned from CatchIt and no other handler + // was found in this function to handle the re-thrown exception. Note: this only + // happens for true re-throw (throw;) and not a nested exception where the catch + // handler throws some entirely new exception. + // + // Since we didn't find a handler here, we will be returning to the caller to + // allow it to search the current function's callers for a handler. Before we leave + // we need to check for a noexcept violation and possibly terminate. + + // FH4 doesn't support Exception Specifications aside from NoExcept + if constexpr (std::is_same_v) + { + if (T::isNoExcept(pFuncInfo) && +#if defined(_M_IX86) && !defined(_CHPE_X86_ARM64_EH_) + CatchDepth == 0 +#else + !T::ExecutionInCatch(pDC, pFuncInfo) +#endif + ) + { + _pCurrentException = pExcept; + _pCurrentExContext = pContext; + terminate(); + } + } + else + { + // + // We haven't found the match -- let's look at the exception spec and see if our try + // matches one of the listed types. + // + // This block also handles noexcept termination if the current function is noexcept and + // we are not handling a nested throw or re-throw. e.g.: + // + // try { + // try { throw 1; } (1) + // catch(int) { throw; /* or throw ; */ } (2) + // } catch(int) {} (3) + // + // During the initial search for a handler when throwing the original exception (1) + // we find and execute catch handler (2). This throws, which re-enters this function + // while in the context of a catch, but which cannot find a handler. We cannot terminate here, + // we're in a recursive context. Just let it go, and we'll return back to the original search + // from (1) and find (3). If we fail to find a handler, e.g. (3) didn't match, we would + // then terminate at this point as we are not in a catch block. + // + // Catch block detection uses CatchDepth on X86, or _ExecutionInCatch on other platforms. On + // these platforms CatchDepth is always 0 - we don't maintain a stack of entered try/catch + // states. + if (FUNC_MAGICNUM(*pFuncInfo) >= EH_MAGIC_HAS_ES && + (T::getESTypes(pFuncInfo) || (T::isNoExcept(pFuncInfo) && +#if defined(_M_IX86) && !defined(_CHPE_X86_ARM64_EH_) + CatchDepth == 0 +#else + !T::ExecutionInCatch(pDC, pFuncInfo) +#endif + ))) + { + // Are we noexcept? + if (T::isNoExcept(pFuncInfo)) + { + _pCurrentException = pExcept; + _pCurrentExContext = pContext; + terminate(); + } + + if (!IsInExceptionSpec(pExcept, T::getESTypes(pFuncInfo))) + { + // Nope, it does not. Call unexpected + + // + // We must unwind the stack before calling unexpected -- this makes it work + // as if it were inside catch(...) clause + // +#if _EH_RELATIVE_FUNCINFO + EHRegistrationNode *pEstablisher = pRN; + EHRegistrationNode EstablisherFramePointers; + pEstablisher = T::GetEstablisherFrame(pRN, pDC, pFuncInfo, &EstablisherFramePointers); + T::UnwindNestedFrames(pRN, + pExcept, + pContext, + pEstablisher, + nullptr, + pFuncInfo, + EH_EMPTY_STATE, + EH_EMPTY_STATE, + nullptr, + pDC, + recursive + ); +#else + + _pCurrentException = pExcept; + _pCurrentExContext = pContext; + + if (pMarkerRN == nullptr) { + RENAME_EH_EXTERN(_UnwindNestedFrames)(pRN, pExcept); + } + else { + RENAME_EH_EXTERN(_UnwindNestedFrames)(pMarkerRN, pExcept); + } + T::FrameUnwindToEmptyState(pRN, pDC, pFuncInfo); + + CallUnexpected(T::getESTypes(pFuncInfo)); + _pCurrentException = pExcept; + _pCurrentExContext = pContext; +#endif + } + } + } + } // It was a C++ EH exception + else + { + // Not ours. But maybe someone told us how to make it ours. + if (tryBlockMap.getNumTryBlocks() > 0) + { + if (recursive) { + // We're recursive, and the exception wasn't a C++ EH! + // Translator threw something unintelligible. + + // Two choices here: we could let the new exception take over, or we could abort. We abort. + abort(); + } + + FindHandlerForForeignException(pExcept, pRN, pContext, pDC, pFuncInfo, curState, CatchDepth, pMarkerRN); + } + } // It wasn't our exception + + _VCRT_VERIFY(_pCurrentFuncInfo == nullptr); // never leave it initialized with something +} + +//////////////////////////////////////////////////////////////////////////////// +// +// FindHandlerForForeignException - We've got an exception which wasn't ours. +// Try to translate it into C++ EH, and also check for match with ellipsis. +// +// Description: +// If an SE-to-EH translator has been installed, call it. The translator +// must throw the appropriate typed exception or return. If the translator +// throws, we invoke FindHandler again as the exception filter. +// +// Returns: +// Returns if exception was not fully handled. +// No return value. +// +// Assumptions: +// Only called if there are handlers in this function. + +template +static void FindHandlerForForeignException( + EHExceptionRecord *pExcept, // Information for this (logical) + // exception + EHRegistrationNode *pRN, // Dynamic information for subject frame + CONTEXT *pContext, // Context info + DispatcherContext *pDC, // Context within subject frame + typename T::FuncInfo *pFuncInfo, // Static information for subject frame + __ehstate_t curState, // Current state + int catchDepth, // Level of nested catch that is being + // checked + EHRegistrationNode *pMarkerRN // Extra marker RN for nested catch + // handling + ) +{ +#if defined(_M_HYBRID_X86_ARM64) && !defined(_CHPE_X86_ARM64_EH_) + _HybridGenerateThunks(FindHandlerForForeignException, 1); +#endif + + // We don't want to touch BreakPoint generated Exception. + if (PER_CODE(pExcept) == STATUS_BREAKPOINT) { + return; + } + + if (__pSETranslator && __pSETranslator != __vcrt_EncodePointer(nullptr) && + pExcept->ExceptionCode != MANAGED_EXCEPTION_CODE && + pExcept->ExceptionCode != MANAGED_EXCEPTION_CODE_V4) { + + // Call the translator. If the translator knows what to + // make of it, it will throw an appropriate C++ exception. + // We intercept it and use it (recursively) for this + // frame. Don't recurse more than once. + +#if _EH_RELATIVE_FUNCINFO + if (_CallSETranslator(pExcept, pRN, pContext, pDC, pFuncInfo, + catchDepth, pMarkerRN, curState)) { +#else + if (_CallSETranslator(pExcept, pRN, pContext, pDC, pFuncInfo, + catchDepth, pMarkerRN)) { +#endif + return; + } + } + +#if _EH_RELATIVE_FUNCINFO + auto tryBlockMap = T::TryBlockMap(pFuncInfo, pDC->ImageBase); +#else + auto tryBlockMap = T::TryBlockMap(pFuncInfo, 0); +#endif + + _VCRT_VERIFY(tryBlockMap.getNumTryBlocks() > 0); + + if (tryBlockMap.getNumTryBlocks() > 0) + { + // Didn't have a translator, or the translator returned normally (i.e. + // didn't translate it). Still need to check for match with ellipsis: + auto startStop = T::GetRangeOfTrysToCheck(tryBlockMap, curState, pDC, pFuncInfo, catchDepth); + + // Scan the try blocks in the function: + for (auto iter = startStop.first; iter < startStop.second; ++iter) + { + auto tryBlock = *iter; + + // If the try-block was in scope... + if (tryBlock.tryLow > curState || curState > tryBlock.tryHigh) { + continue; + } + + // *and* the last catch in that try is an ellipsis (no other can be) +#if _EH_RELATIVE_FUNCINFO + auto handlerMap = T::HandlerMap(&tryBlock, pDC->ImageBase, pDC->FunctionEntry->BeginAddress); +#else + auto handlerMap = T::HandlerMap(&tryBlock, 0, 0); +#endif + auto handler = handlerMap.getLastEntry(); + if (!(HT_IS_TYPE_ELLIPSIS(*handler) && !HT_IS_STD_DOTDOT(*handler))) { + continue; + } + + // Found an ellipsis. Handle exception. + CatchIt(pExcept, + pRN, + pContext, + pDC, + pFuncInfo, + handler, + nullptr, + &tryBlock, + catchDepth, + pMarkerRN, + TRUE, + FALSE + ); + } + + // If it returns, handler re-threw. Keep searching. + + } // Search for try + + // If we got here, that means we didn't have anything to do with the + // exception. Continue search. +} + +template +int TypeMatchHelper( + typename T::HandlerType *pCatch, // Type of the 'catch' clause + CatchableType *pCatchable, // Type conversion under consideration + ThrowInfo *pThrow // General information about the thrown + // type. +) { + // First, check for match with ellipsis: + if (HT_IS_TYPE_ELLIPSIS(*pCatch)) { + return TRUE; + } + + if (HT_ISBADALLOCCOMPAT(*pCatch) && CT_ISSTDBADALLOC(*pCatchable)) + { + return true; + } + + // Not ellipsis; the basic types match if it's the same record *or* the + // names are identical. + if (HT_PTD(*pCatch) != CT_PTD(*pCatchable) + && strcmp(HT_NAME(*pCatch), CT_NAME(*pCatchable)) != 0) { + return FALSE; + } + + // Basic types match. The actual conversion is valid if: + // caught by ref if ref required *and* + // the qualifiers are compatible *and* + // the alignments match *and* + // the volatility matches + + return (!CT_BYREFONLY(*pCatchable) || HT_ISREFERENCE(*pCatch)) + && (!THROW_ISCONST(*pThrow) || HT_ISCONST(*pCatch)) +#if _EH_RELATIVE_FUNCINFO + && (!THROW_ISUNALIGNED(*pThrow) || HT_ISUNALIGNED(*pCatch)) +#endif + && (!THROW_ISVOLATILE(*pThrow) || HT_ISVOLATILE(*pCatch)); +} + +//////////////////////////////////////////////////////////////////////////////// +// +// __TypeMatch - Check if the catch type matches the given throw conversion. +// +// Returns: +// TRUE if the catch can catch using this throw conversion, FALSE otherwise. +extern "C" _VCRTIMP int __cdecl RENAME_EH_EXTERN(__TypeMatch)( + HandlerType *pCatch, // Type of the 'catch' clause + CatchableType *pCatchable, // Type conversion under consideration + ThrowInfo *pThrow // General information about the thrown + // type. + ) +{ + return TypeMatchHelper(pCatch, pCatchable, pThrow); +} + +int RENAME_EH_EXTERN(__FrameHandler3)::TypeMatch( + HandlerType *pCatch, + CatchableType *pCatchable, + ThrowInfo *pThrow +) +{ + return TypeMatchHelper(pCatch, pCatchable, pThrow); +}; + +#if _VCRT_BUILD_FH4 +int RENAME_EH_EXTERN(__FrameHandler4)::TypeMatch( + HandlerType *pCatch, + CatchableType *pCatchable, + ThrowInfo *pThrow +) +{ + return TypeMatchHelper(pCatch, pCatchable, pThrow); +}; +#endif // _VCRT_BUILD_FH4 + +//////////////////////////////////////////////////////////////////////////////// +// +// FrameUnwindToState - Unwind this frame until specified state is reached. +// +// Returns: +// No return value. +// +// Side Effects: +// All objects on frame which go out of scope as a result of the unwind are +// destructed. +// Registration node is updated to reflect new state. +// +// Usage: +// This function is called both to do full-frame unwind during the unwind +// phase (targetState = -1), and to do partial unwinding when the current +// frame has an appropriate catch. + +#if _VCRT_BUILD_FH4 +void RENAME_EH_EXTERN(__FrameHandler4)::FrameUnwindToState( + EHRegistrationNode *pRN, // Registration node for subject + // function + DispatcherContext *pDC, // Context within subject frame + FuncInfo *pFuncInfo, // Static information for subject + // function + __ehstate_t targetState // State to unwind to + ) +{ + UNREFERENCED_PARAMETER(pDC); // This parameter is not used in some compilations +#if _EH_RELATIVE_FUNCINFO + ptrdiff_t unwindImageBase = _GetImageBase(); + + __ehstate_t curState = GetHandlerSearchState(pRN, pDC, pFuncInfo); +#else // ^^^ _EH_RELATIVE_FUNCINFO // !_EH_RELATIVE_FUNCINFO vvv + #error Not yet implemented. +#endif // _EH_RELATIVE_FUNCINFO + __ProcessingThrow++; + + // Find starting and ending indexes in the decompressed map + auto unwindMap = UWMap(pFuncInfo, pDC->ImageBase); + + UWMap::iterator start = unwindMap.begin(); + UWMap::iterator end = unwindMap.begin(); + + _VCRT_VERIFY(start >= end); + unwindMap.getStartStop(curState, targetState, start, end); + + __try + { + while (start >= unwindMap.begin() && start > end) + { + UnwindMapEntry4 UWEntry = *start; + auto prevIter = start; + + start.WalkBack(); + + __ehstate_t prevState = curState; + curState = UWMap::getStateFromIterators(end, targetState, prevIter, prevState, start); + + // default values taken if UnwindMapEntry4::Type::NoUW + unsigned dispAction = 0; + + if (UWEntry.type != UnwindMapEntry4::Type::NoUW) + { + dispAction = UWEntry.action; + } + + if (dispAction != 0) { + // Before calling unwind action, adjust state as if it were + // already completed: +#if _EH_RELATIVE_FUNCINFO + pDC->ScopeIndex = (DWORD)(curState + SCOPE_INDEX_SHIFT_VALUE); +#else // ^^^ _EH_RELATIVE_FUNCINFO // !_EH_RELATIVE_FUNCINFO vvv + #error Not yet implemented. + //SetState(pRN, pDC, pFuncInfo, start - unwindMap.begin()); +#endif // _EH_RELATIVE_FUNCINFO + + EHTRACE_FMT2("Unwind from state %d to state %d\n", prevState, curState); + __try { + // Call the unwind action (if one exists): + if ((UWEntry.type == UnwindMapEntry4::Type::DtorWithObj) || (UWEntry.type == UnwindMapEntry4::Type::DtorWithPtrToObj)) + { + VOID * objectAddr; + if (UWEntry.type == UnwindMapEntry4::Type::DtorWithPtrToObj) { + objectAddr = (void*)(*(uintptr_t *)OffsetToAddress(UWEntry.object, *pRN)); + } + else { + objectAddr = OffsetToAddress(UWEntry.object, *pRN); + } + + RENAME_EH_EXTERN(_CallSettingFrameEncoded)((void*)__RVAtoRealOffset(pDC, dispAction), + *pRN, + objectAddr, +#if defined(_M_ARM_NT) || defined(_M_ARM64) || defined(_CHPE_X86_ARM64_EH_) + (PULONG)pDC->NonVolatileRegisters, +#endif // defined(_M_ARM_NT) || defined(_M_ARM64) || defined(_CHPE_X86_ARM64_EH_) + 0x103); + } + else + { // TODO: this is currently hardcoded for non-x86, as x86 seems to encode + // its RVAs as non-image relative, will require fix for that + RENAME_EH_EXTERN(_CallSettingFrame)((void*)__RVAtoRealOffset(pDC, dispAction), pRN, +#if defined(_M_ARM_NT) || defined(_M_ARM64) || defined(_CHPE_X86_ARM64_EH_) + (PULONG)pDC->NonVolatileRegisters, +#endif // defined(_M_ARM_NT) || defined(_M_ARM64) || defined(_CHPE_X86_ARM64_EH_) + 0x103); + } + +#if _EH_RELATIVE_FUNCINFO + _SetImageBase(unwindImageBase); +#endif // _EH_RELATIVE_FUNCINFO + + } + __except (__FrameUnwindFilter(exception_info())) { + ; // Deliberately do nothing + } + } + } + } + __finally { + if (__ProcessingThrow > 0) { + __ProcessingThrow--; + } + } + + EHTRACE_FMT2("Moved from state %d to state %d", curState, targetState); +} +#endif // _VCRT_BUILD_FH4 + +void RENAME_EH_EXTERN(__FrameHandler3)::FrameUnwindToState( + EHRegistrationNode *pRN, // Registration node for subject + // function + DispatcherContext *pDC, // Context within subject frame + FuncInfo *pFuncInfo, // Static information for subject + // function + __ehstate_t targetState // State to unwind to + ) +{ + UNREFERENCED_PARAMETER(pDC); // This parameter is not used in some compilations + +#if _EH_RELATIVE_FUNCINFO + ptrdiff_t unwindImageBase = _GetImageBase(); +#endif + + __ehstate_t curState = GetCurrentState(pRN, pDC, pFuncInfo); + __ProcessingThrow++; + __try { +#if _EH_RELATIVE_FUNCINFO + while (curState != EH_EMPTY_STATE && curState > targetState) +#else + while (curState != targetState) +#endif + { + _VCRT_VERIFY(curState > EH_EMPTY_STATE && curState < FUNC_MAXSTATE(*pFuncInfo)); + + // Get state after next unwind action + __ehstate_t nxtState = UWE_TOSTATE(FUNC_UNWIND(*pFuncInfo, curState)); + + __try { + // Call the unwind action (if one exists): + + if (UWE_ACTION(FUNC_UNWIND(*pFuncInfo, curState))) { + + // Before calling unwind action, adjust state as if it were + // already completed: + SetState(pRN, pFuncInfo, nxtState); + + EHTRACE_FMT2("Unwind from state %d to state %d", curState, nxtState); + +#if defined(_M_ARM64EC) + if (RtlIsEcCode((ULONG64)UWE_ACTION(FUNC_UNWIND(*pFuncInfo, curState)))) { + RENAME_EH_EXTERN(_CallSettingFrameArm64Ec)(UWE_ACTION(FUNC_UNWIND(*pFuncInfo, curState)), + pRN, + (PULONG)(((PDISPATCHER_CONTEXT_ARM64EC)pDC)->NonVolatileRegisters), + 0x103); + } else { + RENAME_EH_EXTERN(_CallSettingFrame)(UWE_ACTION(FUNC_UNWIND(*pFuncInfo, curState)), pRN, + 0x103); + } +#else + + RENAME_EH_EXTERN(_CallSettingFrame)(UWE_ACTION(FUNC_UNWIND(*pFuncInfo, curState)), pRN, +#if defined(_M_ARM_NT) || defined(_M_ARM64) || defined(_CHPE_X86_ARM64_EH_) + (PULONG)pDC->NonVolatileRegisters, +#endif + 0x103); + +#endif + +#if _EH_RELATIVE_FUNCINFO + _SetImageBase(unwindImageBase); +#endif + } + + } __except(__FrameUnwindFilter(exception_info())) { + ; // Deliberately do nothing + } + + curState = nxtState; + } + } __finally { + if (__ProcessingThrow > 0) { + __ProcessingThrow--; + } + } + + + // Now that we're done, set the frame to reflect the final state. + +#if _EH_RELATIVE_FUNCINFO + _VCRT_VERIFY(curState == EH_EMPTY_STATE || curState <= targetState); +#else + _VCRT_VERIFY(curState == targetState); +#endif + + EHTRACE_FMT2("Move from state %d to state %d", GetCurrentState(pRN, pDC, pFuncInfo), curState); + + SetState(pRN, pFuncInfo, curState); +} + +//////////////////////////////////////////////////////////////////////////////// +// +// CatchIt - A handler has been found for the thrown type. Do the work to +// transfer control. +// +// Description: +// Builds the catch object +// Unwinds the stack to the point of the try +// Calls the address of the handler (funclet) with the frame set up for that +// function but without resetting the stack. +// Handler funclet returns address to continue execution, or nullptr if the +// handler re-threw ("throw;" lexically in handler) +// If the handler throws an EH exception whose exception info is nullptr, then +// it's a re-throw from a dynamically enclosed scope. +// +// It is an open question whether the catch object is built before or after the local unwind. +// +// Returns: +// No return value. Returns iff handler re-throws. +template +static void CatchIt( + EHExceptionRecord *pExcept, // The exception thrown + EHRegistrationNode *pRN, // Dynamic info of function with catch + CONTEXT *pContext, // Context info + DispatcherContext *pDC, // Context within subject frame + typename T::FuncInfo *pFuncInfo, // Static info of function with catch + typename T::HandlerType *pCatch, // The catch clause selected + CatchableType *pConv, // The rules for making the conversion + typename T::TryBlockMapEntry *pEntry, // Description of the try block + int CatchDepth, // How many catches are we nested in? + EHRegistrationNode *pMarkerRN, // Special node if nested in catch + BOOLEAN IsRethrow, // Is this a rethrow ? + BOOLEAN recursive // Is this from a translated exception ? +) { + + // These parameters are not used in some compilations + UNREFERENCED_PARAMETER(CatchDepth); + UNREFERENCED_PARAMETER(pMarkerRN); + UNREFERENCED_PARAMETER(IsRethrow); + UNREFERENCED_PARAMETER(recursive); + + EHTRACE_FMT1("Catching object @ 0x%p", PER_PEXCEPTOBJ(pExcept)); + + EHRegistrationNode *pEstablisher = pRN; + +#if _EH_RELATIVE_FUNCINFO + EHRegistrationNode EstablisherFramePointers; + pEstablisher = T::GetEstablisherFrame(pRN, pDC, pFuncInfo, &EstablisherFramePointers); +#else + void *continuationAddress; +#endif // defined(_POWERPC) + + // Copy the thrown object into a buffer in the handler's stack frame, + // unless the catch was by ellipsis (no conversion) OR the catch was by + // type without an actual 'catch object'. + + if (pConv) { + T::BuildCatchObject(pExcept, pEstablisher, pCatch, pConv); + } + + // Unwind stack objects to the entry of the try that caught this exception. + +#if _EH_RELATIVE_FUNCINFO + // This call will never return. This call will end up calling CxxCallCatchBlock + // through RtlUnwind (STATUS_CONSOLIDATE_FRAMES) mechanism. + T::UnwindNestedFrames( + pRN, + pExcept, + pContext, + pEstablisher, + HT_HANDLER(*pCatch), + pFuncInfo, + pEntry->tryLow, + pEntry->catchHigh, + pCatch, + pDC, + recursive + ); + +#else + + static_assert(!std::is_same_v, "Not yet implemented."); + if (pMarkerRN == nullptr) { + RENAME_EH_EXTERN(_UnwindNestedFrames)(pRN, pExcept); + } + else { + RENAME_EH_EXTERN(_UnwindNestedFrames)(pMarkerRN, pExcept); + } + + + T::FrameUnwindToState(pEstablisher, pDC, pFuncInfo, TBME_LOW(*pEntry)); + + // Call the catch. Separated out because it introduces a new registration + // node. + EHTRACE_FMT2("Move from state %d to state %d", T::GetCurrentState(pRN, pDC, pFuncInfo), TBME_HIGH(*pEntry) + 1); + T::SetState(pRN, pFuncInfo, TBME_HIGH(*pEntry) + 1); + + continuationAddress = CallCatchBlock(pExcept, + pEstablisher, + pContext, + pFuncInfo, + HT_HANDLER(*pCatch), + CatchDepth, + 0x100); + + // Transfer control to the continuation address. If no continuation then + // it's a re-throw, so return. + + if (continuationAddress) { + _JumpToContinuation(continuationAddress, pRN); + // No return. + } +#endif +} + +#if _EH_RELATIVE_FUNCINFO /* { { */ + +static void __RethrowException(EHExceptionRecord *pThisException) +{ + RaiseException( pThisException->ExceptionCode, + pThisException->ExceptionFlags, + pThisException->NumberParameters, + (PULONG_PTR)&(pThisException->params) ); +} + +#if _VCRT_BUILD_FH4 +void * RENAME_EH_EXTERN(__FrameHandler4)::CxxCallCatchBlock( + EXCEPTION_RECORD *pExcept + ) +{ + int rethrow = 0, TranslatedCatch = 0; + void *handlerAddress; + void *continuationAddress = nullptr; + FRAMEINFO FrameInfo; + CONTEXT *pContext, *pSaveContext; + EHRegistrationNode *pEstablisherFrame; + EHExceptionRecord *pThisException, *pSaveException, *pForeignException = nullptr; + void *continuationAddresses[MAX_CONT_ADDRESSES]; + memset(continuationAddresses, 0, sizeof(continuationAddresses)); + FuncInfo FuncInfo; + + pSaveContext = _pCurrentExContext; + pSaveException = _pCurrentException; + + // Copy Necessary Information which is passed from UnwindNestedFrames. + pThisException = (EHExceptionRecord *)pExcept->ExceptionInformation[6]; + pContext = (CONTEXT *)pExcept->ExceptionInformation[4]; + handlerAddress = (void *)pExcept->ExceptionInformation[2]; + pEstablisherFrame = (EHRegistrationNode *)pExcept->ExceptionInformation[1]; + + continuationAddresses[0] = (PBYTE)pExcept->ExceptionInformation[5]; + continuationAddresses[1] = (PBYTE)pExcept->ExceptionInformation[9]; + + // State used if an exception inside the called catch needs to be handled in the parent + __ehstate_t HandlerSearchState = (__ehstate_t) pExcept->ExceptionInformation[11]; + // State used during unwinding to bypass already unwound states in the parent + __ehstate_t UnwindTryState = (__ehstate_t)pExcept->ExceptionInformation[3]; + + __except_validate_context_record(pContext); + + _pCurrentException = pThisException; + _pCurrentExContext = pContext; + FRAMEINFO *pFrameInfo = RENAME_EH_EXTERN(_CreateFrameInfo)(&FrameInfo, + (void *)PER_PEXCEPTOBJ(_pCurrentException)); + + if (pExcept->ExceptionInformation[7]) { + // Stuff for SehTranslation book keeping + // This Exception Object is Translation of Foreign Exception And should + // be destroyed in any case. If there is rethrow, throw ForeignException. + // IMPORTANT: No one else can rethrow this Exception Object. + TranslatedCatch = 1; + pForeignException = _pForeignExcept; + // End Translation Stuff + } + + __try { + __try { +#if defined(_M_X64) + continuationAddress = RENAME_EH_EXTERN(_CallSettingFrame_LookupContinuationIndex)( +#else + #error Not yet implemented. + // continuationAddress = RENAME_EH_EXTERN(_CallSettingFrame)( +#endif + handlerAddress, + pEstablisherFrame, +#if defined(_M_ARM_NT) || defined(_M_ARM64) || defined(_CHPE_X86_ARM64_EH_) + (PULONG)pExcept->ExceptionInformation[10], +#endif + 0x100); + + intptr_t continuationIndex = reinterpret_cast(continuationAddress); + if (continuationIndex < MAX_CONT_ADDRESSES) + { + _VCRT_VERIFY(continuationAddresses[continuationIndex] != 0); + continuationAddress = continuationAddresses[continuationIndex]; + } +#if defined(_M_X64) + RENAME_EH_EXTERN(_CallSettingFrame_NotifyContinuationAddr)(continuationAddress, pEstablisherFrame); +#else + #error Not yet implemented. + // FH4 is only implemented for amd64 +#endif + } + // Filter will be invoked in pass 1 looking for an exception, this lets us set up the correct _CatchStateInParent that should + // be used when looking for a handler in the parent of a catch funclet inside ExFilterRethrowFH4. + // Note: in case of rethrow we unwind through the catch handler back to this filter in order to rethrow. + // In that case, the _CatchStateInParent should not be set until we get into the except. + __except (ExFilterRethrowFH4(exception_info(), pThisException, HandlerSearchState, &rethrow)) + { + rethrow = 1; + cxxReThrow = false; + CatchStateInParent = HandlerSearchState; + if (TranslatedCatch) { + // Note in case of rethrow, no one else can convert rethrow to + // pThisException. This means only this except will deal with conversion + // of rethrow to pThisException. Instead of pThisException, we + // will throw original Foreign Exception. Also we will need to + // destroy Exception Object before Raising Foreign Exception. + __DestructExceptionObject(pThisException, TRUE); + __RethrowException(pForeignException); + } + else + { + __RethrowException(pThisException); + } + } + } + __finally { + RENAME_EH_EXTERN(_FindAndUnlinkFrame)(pFrameInfo); + if (!rethrow && + PER_IS_MSVC_EH(pThisException) && + _IsExceptionObjectToBeDestroyed(PER_PEXCEPTOBJ(pThisException))) + { + __DestructExceptionObject(pThisException, TRUE); + } + _pCurrentException = pSaveException; + _pCurrentExContext = pSaveContext; + + // Finally is invoked in pass 2, letting us set the correct state to unwind from when back in the parent frame + CatchStateInParent = UnwindTryState; + } +#if _EH_RELATIVE_FUNCINFO + // exception caught successfully, reset this value + CatchStateInParent = INVALID_CATCH_SPECIFIC_STATE; +#endif + return continuationAddress; +} +#endif // _VCRT_BUILD_FH4 + +void * RENAME_EH_EXTERN(__FrameHandler3)::CxxCallCatchBlock( + EXCEPTION_RECORD *pExcept + ) +{ + int rethrow = 0, TranslatedCatch = 0; + void *handlerAddress; + void *continuationAddress = nullptr; + FuncInfo *pFuncInfo; + FRAMEINFO FrameInfo; + CONTEXT *pContext, *pSaveContext; + EHRegistrationNode *pEstablisherFrame; + EHExceptionRecord *pThisException, *pSaveException, *pForeignException = nullptr; + + pSaveContext = _pCurrentExContext; + pSaveException = _pCurrentException; + + // Copy Necessary Information which is passed from UnwindNestedFrames. + pThisException = (EHExceptionRecord *) pExcept->ExceptionInformation[6]; + pFuncInfo = (FuncInfo *) pExcept->ExceptionInformation[5]; + pContext = (CONTEXT *) pExcept->ExceptionInformation[4]; + handlerAddress = (void *) pExcept->ExceptionInformation[2]; + pEstablisherFrame = (EHRegistrationNode *)pExcept->ExceptionInformation[1]; + + __except_validate_context_record(pContext); + + _pCurrentException = pThisException; + _pCurrentExContext = pContext; + FRAMEINFO *pFrameInfo = RENAME_EH_EXTERN(_CreateFrameInfo)(&FrameInfo, + (void *)PER_PEXCEPTOBJ(_pCurrentException)); + + if (pExcept->ExceptionInformation[7]) { + // Stuff for SehTranslation book keeping + // This Exception Object is Translation of Foreign Exception And should + // be destroyed in any case. If there is rethrow, throw ForeignException. + // IMPORTANT: No one else can rethrow this Exception Object. + TranslatedCatch = 1; + pForeignException = _pForeignExcept; + // End Translation Stuff + } + + __try { + __try{ +#if defined(_M_ARM64EC) + + if (RtlIsEcCode((ULONG64)handlerAddress)) { + continuationAddress = RENAME_EH_EXTERN(_CallSettingFrameArm64Ec) (handlerAddress, + pEstablisherFrame, + (PULONG)pExcept->ExceptionInformation[10], + 0x100); + + } else { + continuationAddress = RENAME_EH_EXTERN(_CallSettingFrame) (handlerAddress, + pEstablisherFrame, + 0x100); + } + +#else + continuationAddress = RENAME_EH_EXTERN(_CallSettingFrame)(handlerAddress, + pEstablisherFrame, +#if defined(_M_ARM_NT) || defined(_M_ARM64) || defined(_CHPE_X86_ARM64_EH_) + (PULONG)pExcept->ExceptionInformation[10], +#endif + 0x100); +#endif + } __except(ExFilterRethrow(exception_info(), + pThisException, + &rethrow)) { + rethrow = 1; + cxxReThrow = false; + if (TranslatedCatch) { + // Note in case of rethrow, no one else can convert rethrow to + // pThisException. This means only this except will deal with conversion + // of rethrow to pThisException. Instead of pThisException, we + // will throw original Foreign Exception. Also we will need to + // destroy Exception Object before Raising Foreign Exception. + __DestructExceptionObject(pThisException, TRUE); + __RethrowException(pForeignException); + } else { + __RethrowException(pThisException); + } + } + } __finally { + RENAME_EH_EXTERN(_FindAndUnlinkFrame)(pFrameInfo); + if ( !rethrow && + PER_IS_MSVC_EH(pThisException) && + _IsExceptionObjectToBeDestroyed(PER_PEXCEPTOBJ(pThisException))) + { + __DestructExceptionObject(pThisException, TRUE); + } + _pCurrentException = pSaveException; + _pCurrentExContext = pSaveContext; + } +#if _EH_RELATIVE_FUNCINFO + UNWINDHELP(*pEstablisherFrame, FUNC_DISPUNWINDHELP(*pFuncInfo)) = -2; +#endif + return continuationAddress; +} + +//////////////////////////////////////////////////////////////////////////////// +// +// ExFilterRethrow - Exception filter for re-throw exceptions. +// +// Returns: +// EXCEPTION_EXECUTE_HANDLER - exception was a re-throw +// EXCEPTION_CONTINUE_SEARCH - anything else +// +// Side-effects: sets rethrow = TRUE if exception objects of the two Exception matches + +static __declspec(guard(ignore)) int ExFilterRethrow( + EXCEPTION_POINTERS *pExPtrs, + EHExceptionRecord *pOldExcept, + int *rethrow +) { + // Get the exception record thrown (don't care about other info) + EHExceptionRecord *pExcept = (EHExceptionRecord *)pExPtrs->ExceptionRecord; + *rethrow = 0; + if (PER_IS_MSVC_EH(pExcept) && PER_PEXCEPTOBJ(pExcept) == PER_PEXCEPTOBJ(pOldExcept)) + *rethrow = 1; + // Check if it's ours and it's has no exception information. + if (PER_IS_MSVC_EH(pExcept) && PER_PTHROW(pExcept) == nullptr) { + // In a rethrow, ExceptionCode isn't set to EH_EXCEPTION_NUMBER even for a + // C++ Exception. Hence we use cxxReThrow in __InternalCxxFrameHandler + // to check for a C++ Exception + cxxReThrow = true; + *rethrow = 1; + return EXCEPTION_EXECUTE_HANDLER; + } + return EXCEPTION_CONTINUE_SEARCH; +} + +#if _VCRT_BUILD_FH4 +// Wraps around ExFilterRethrow to set _CatchStateInParent if this isn't a rethrow. +static __declspec(guard(ignore)) int ExFilterRethrowFH4( + EXCEPTION_POINTERS *pExPtrs, + EHExceptionRecord *pOldExcept, + __ehstate_t HandlerSearchState, + int *rethrow +) +{ + int exceptionCode = ExFilterRethrow(pExPtrs, pOldExcept, rethrow); + if (exceptionCode == EXCEPTION_CONTINUE_SEARCH) + { + // Set correct parent state to be used + CatchStateInParent = HandlerSearchState; + } + + return exceptionCode; +} +#endif + +#elif defined(_M_IX86) + +//////////////////////////////////////////////////////////////////////////////// +// +// CallCatchBlock - continuation of CatchIt. +// +// This is separated from CatchIt because it needs to introduce an SEH/EH frame +// in case the catch block throws. This frame cannot be added until unwind of +// nested frames has been completed (otherwise this frame would be the first +// to go). + +static __declspec(guard(ignore)) void *CallCatchBlock( + EHExceptionRecord *pExcept, // The exception thrown + EHRegistrationNode *pRN, // Dynamic info of function with catch + CONTEXT *pContext, // Context info + FuncInfo *pFuncInfo, // Static info of function with catch + void *handlerAddress, // Code address of handler + int CatchDepth, // How deeply nested in catch blocks + // are we? + unsigned long NLGCode // NLG destination code +) { + // Address where execution resumes after exception handling completed. + // Initialized to non-nullptr (value doesn't matter) to distinguish from + // re-throw in __finally. + void *continuationAddress = handlerAddress; + + BOOL ExceptionObjectDestroyed = FALSE; + + // The stack pointer at entry to the try must be saved, in case there is + // another try inside this catch. We'll restore it on our way out. + void *saveESP = PRN_STACK(pRN); + + // Push this catch block's frame info on a linked list + FRAMEINFO FrameInfo; + FRAMEINFO *pFrameInfo = RENAME_EH_EXTERN(_CreateFrameInfo)(&FrameInfo, PER_PEXCEPTOBJ(pExcept)); + + // Save the current exception in case of a rethrow. Save the previous value + // on the stack, to be restored when the catch exits. + EHExceptionRecord *pSaveException = _pCurrentException; + CONTEXT *pSaveExContext = _pCurrentExContext; + + _pCurrentException = pExcept; + _pCurrentExContext = pContext; + + __try { + __try { + // Execute the handler as a funclet, whose return value is the + // address to resume execution. + continuationAddress = _CallCatchBlock2(pRN, pFuncInfo, + handlerAddress, CatchDepth, NLGCode); + } __except(ExFilterRethrow(exception_info())) { + cxxReThrow=false; + // Here we are exiting the catch block on rethrow out of this + // catch block. To keep the order of destruction and construction + // same when the the rethrow was from function or was inline, here + // we unwind to the parent state for this catch. + UnwindMapEntry *pUnwindMap = pFuncInfo->pUnwindMap; + int cState = RENAME_EH_EXTERN(__FrameHandler3)::GetCurrentState(pRN, handlerAddress, pFuncInfo); + TryBlockMapEntry *pTryBlockMap = pFuncInfo->pTryBlockMap; + unsigned int i; + for (i = 0; i < pFuncInfo->nTryBlocks; i++) { + if (cState > pTryBlockMap[i].tryHigh && + cState <= pTryBlockMap[i].catchHigh) { + cState = pTryBlockMap[i].tryHigh +1; + cState = pUnwindMap[cState].toState; + break; + } + } + RENAME_EH_EXTERN(__FrameHandler3)::FrameUnwindToState(pRN, nullptr, pFuncInfo, cState); + // If the handler threw a typed exception without exception info or + // exception object, then it's a re-throw, so return. Otherwise + // it's a new exception, which takes precedence over this one. + continuationAddress = nullptr; + } + } __finally { + EHTRACE_FMT1("Executing __finally, %snormal termination", _abnormal_termination() ? "ab" : ""); + // Restore the saved stack pointer, so the stack can be reset when + // we're done. + PRN_STACK(pRN) = saveESP; + + // Pop this catch block's frame info + RENAME_EH_EXTERN(_FindAndUnlinkFrame)(pFrameInfo); + + // Restore the 'current exception' for a possibly enclosing catch + _pCurrentException = pSaveException; + _pCurrentExContext = pSaveExContext; + + // Destroy the original exception object if we're not exiting on a + // re-throw and the object isn't also in use by a more deeply nested + // catch. Note that the catch handles destruction of its parameter. + + if (PER_IS_MSVC_EH(pExcept) && !ExceptionObjectDestroyed + && continuationAddress + && _IsExceptionObjectToBeDestroyed(PER_PEXCEPTOBJ(pExcept))) + { + __DestructExceptionObject(pExcept, abnormal_termination() != FALSE); + } + } + + return continuationAddress; +} + + +//////////////////////////////////////////////////////////////////////////////// +// +// ExFilterRethrow - Exception filter for re-throw exceptions. +// +// Returns: +// EXCEPTION_EXECUTE_HANDLER - exception was a re-throw +// EXCEPTION_CONTINUE_SEARCH - anything else +// +// Side-effects: NONE. + +static int ExFilterRethrow( + EXCEPTION_POINTERS *pExPtrs +) { + // Get the exception record thrown (don't care about other info) + EHExceptionRecord *pExcept = (EHExceptionRecord *)pExPtrs->ExceptionRecord; + + // Check if it's ours and it's has no exception information. + if (PER_IS_MSVC_EH(pExcept) && PER_PTHROW(pExcept) == nullptr) { + // In a rethrow, ExceptionCode isn't set to EH_EXCEPTION_NUMBER even for a + // C++ Exception. Hence we use cxxReThrow in __InternalCxxFrameHandler + // to check for a C++ Exception + cxxReThrow = true; + return EXCEPTION_EXECUTE_HANDLER; + } else { + return EXCEPTION_CONTINUE_SEARCH; + } +} + +#endif /* } } */ + +//////////////////////////////////////////////////////////////////////////////// +// +// BuildCatchObjectHelper - Copy or construct the catch object from the object thrown. +// +// Returns: +// 0 if nothing to be done for constructing object from caller side +// 1 if single parameter constructor is to be called. +// 2 if two parameter constructor is to be called. +// +// Side-effects: +// A buffer in the subject function's frame is initialized. +// +// Open issues: +// What happens if the constructor throws? (or faults?) + +#pragma warning(push) +#pragma warning(disable:4191) + +template +static int BuildCatchObjectHelperInternal( + EHExceptionRecord *pExcept, // Original exception thrown + void *pRN, // This is a pointer to the object + // that we want to build while doing + // COM+ eh. If we are in our own eh, + // then this is a Registration node of + // catching function + typename T::HandlerType *pCatch, // The catch clause that got it + CatchableType *pConv // The conversion to use + ) +{ + int retval = 0; + + // If the catch is by ellipsis, then there is no object to construct. + // If the catch is by type(No Catch Object), then leave too! + if (HT_IS_TYPE_ELLIPSIS(*pCatch) || + (!HT_DISPCATCH(*pCatch) && !HT_ISCOMPLUSEH(*pCatch))) { + return 0; + } + + void **pCatchBuffer; + if (HT_ISCOMPLUSEH(*pCatch)) + { + pCatchBuffer = (void **)pRN; + } + else + { +#if _EH_RELATIVE_FUNCINFO + pCatchBuffer = (void **)OffsetToAddress( + HT_DISPCATCH(*pCatch), + *((EHRegistrationNode *)pRN) + ); +#else // ^^^ _EH_RELATIVE_FUNCINFO // !_EH_RELATIVE_FUNCINFO vvv + pCatchBuffer = (void **)OffsetToAddress( + HT_DISPCATCH(*pCatch), + (EHRegistrationNode *)pRN + ); +#endif // _EH_RELATIVE_FUNCINFO + } + __try { + if (HT_ISBADALLOCCOMPAT(*pCatch) && CT_ISSTDBADALLOC(*pConv) && __WinRTOutOfMemoryExceptionCallback) + { + void* pException = __WinRTOutOfMemoryExceptionCallback(); + + _VCRT_VERIFY(pException && pCatchBuffer); + *pCatchBuffer = pException; + *pCatchBuffer = __AdjustPointer(*pCatchBuffer, CT_THISDISP(*pConv)); + } + else if (HT_ISREFERENCE(*pCatch)) { + + // The catch is of form 'reference to T'. At the throw point we + // treat both 'T' and 'reference to T' the same, i.e. + // pExceptionObject is a (machine) pointer to T. Adjust as + // required. + _VCRT_VERIFY(PER_PEXCEPTOBJ(pExcept) && pCatchBuffer); + *pCatchBuffer = PER_PEXCEPTOBJ(pExcept); + *pCatchBuffer = __AdjustPointer(*pCatchBuffer, CT_THISDISP(*pConv)); + } + else if (CT_ISSIMPLETYPE(*pConv)) { + + // Object thrown is of simple type (this including pointers) copy + // specified number of bytes. Adjust the pointer as required. If + // the thing is not a pointer, then this should be safe since all + // the entries in the THISDISP are 0. + _VCRT_VERIFY(PER_PEXCEPTOBJ(pExcept) && pCatchBuffer); + memmove(pCatchBuffer, PER_PEXCEPTOBJ(pExcept), CT_SIZE(*pConv)); + if (CT_SIZE(*pConv) == sizeof(void*) && *pCatchBuffer) { + *pCatchBuffer = __AdjustPointer(*pCatchBuffer, CT_THISDISP(*pConv)); + } + } + else { + // Object thrown is UDT. + if (CT_COPYFUNC(*pConv) == nullptr) { + // The UDT had a simple ctor. Adjust in the thrown object, + // then copy n bytes. + _VCRT_VERIFY(PER_PEXCEPTOBJ(pExcept) && pCatchBuffer); + memmove(pCatchBuffer, __AdjustPointer(PER_PEXCEPTOBJ(pExcept), CT_THISDISP(*pConv)), CT_SIZE(*pConv)); + } + else { + // It's a UDT: make a copy using copy ctor + _VCRT_VERIFY(PER_PEXCEPTOBJ(pExcept) && pCatchBuffer && CT_COPYFUNC(*pConv)); + if (CT_HASVB(*pConv)) { + retval = 2; + } else { + retval = 1; + } + } + } + } __except(EXCEPTION_EXECUTE_HANDLER) { + // Something went wrong when building the catch object. + abort(); + } + + return retval; +} + +#pragma warning(pop) + +extern "C" _VCRTIMP int __cdecl RENAME_EH_EXTERN(__BuildCatchObjectHelper)( + EHExceptionRecord *pExcept, // Original exception thrown + void *pRN, // This is a pointer to the object + // that we want to build while doing + // COM+ eh. If we are in our own eh, + // then this is a Registration node of + // catching function + HandlerType *pCatch, // The catch clause that got it + CatchableType *pConv // The conversion to use + ) +{ + return BuildCatchObjectHelperInternal(pExcept, pRN, pCatch, pConv); +} + +int RENAME_EH_EXTERN(__FrameHandler3)::BuildCatchObjectHelper( + EHExceptionRecord *pExcept, + void *pRN, + HandlerType *pCatch, + CatchableType *pConv + ) +{ + return BuildCatchObjectHelperInternal(pExcept, pRN, pCatch, pConv); +} + +#if _VCRT_BUILD_FH4 +int RENAME_EH_EXTERN(__FrameHandler4)::BuildCatchObjectHelper( + EHExceptionRecord *pExcept, + void *pRN, + HandlerType *pCatch, + CatchableType *pConv + ) +{ + return BuildCatchObjectHelperInternal(pExcept, pRN, pCatch, pConv); +} +#endif // _VCRT_BUILD_FH4 + +//////////////////////////////////////////////////////////////////////////////// +// +// BuildCatchObjectInternal - Copy or construct the catch object from the object thrown. +// +// Returns: +// nothing. +// +// Side-effects: +// A buffer in the subject function's frame is initialized. +// +// Open issues: +// What happens if the constructor throws? (or faults?) + +template +static void BuildCatchObjectInternal( + EHExceptionRecord *pExcept, // Original exception thrown + void *pRN, // This is a pointer to the object + // that we want to build while doing + // COM+ eh. If we are in our own eh, + // then this is a Registration node of + // catching function + typename T::HandlerType *pCatch, // The catch clause that got it + CatchableType *pConv // The conversion to use + ) +{ + void **pCatchBuffer; + if ( HT_ISCOMPLUSEH(*pCatch)) + { + pCatchBuffer = (void **)pRN; + } + else + { +#if _EH_RELATIVE_FUNCINFO + pCatchBuffer = (void **)OffsetToAddress( + HT_DISPCATCH(*pCatch), + *((EHRegistrationNode *)pRN) + ); +#else + pCatchBuffer = (void **)OffsetToAddress( + HT_DISPCATCH(*pCatch), + (EHRegistrationNode *)pRN + ); +#endif + } + + __try { + switch(BuildCatchObjectHelperInternal(pExcept, pRN, pCatch, pConv)) + { + case 1: + _CallMemberFunction1((char *)pCatchBuffer, + CT_COPYFUNC(*pConv), + __AdjustPointer(PER_PEXCEPTOBJ(pExcept), + CT_THISDISP(*pConv))); + break; + case 2: + _CallMemberFunction2((char *)pCatchBuffer, + CT_COPYFUNC(*pConv), + __AdjustPointer(PER_PEXCEPTOBJ(pExcept), + CT_THISDISP(*pConv)), 1); + break; + case 0: + break; + default: + break; + } + } __except(EXCEPTION_EXECUTE_HANDLER) { + // Something went wrong when building the catch object. + abort(); + } +} + +extern "C" _VCRTIMP void __cdecl RENAME_EH_EXTERN(__BuildCatchObject)( + EHExceptionRecord *pExcept, // Original exception thrown + void *pRN, // This is a pointer to the object + // that we want to build while doing + // COM+ eh. If we are in our own eh, + // then this is a Registration node of + // catching function + HandlerType *pCatch, // The catch clause that got it + CatchableType *pConv // The conversion to use + ) +{ + BuildCatchObjectInternal(pExcept, pRN, pCatch, pConv); +} + +void RENAME_EH_EXTERN(__FrameHandler3)::BuildCatchObject( + EHExceptionRecord *pExcept, + void *pRN, + HandlerType *pCatch, + CatchableType *pConv + ) +{ + BuildCatchObjectInternal(pExcept, pRN, pCatch, pConv); +} + +#if _VCRT_BUILD_FH4 +void RENAME_EH_EXTERN(__FrameHandler4)::BuildCatchObject( + EHExceptionRecord *pExcept, + void *pRN, + HandlerType *pCatch, + CatchableType *pConv + ) +{ + BuildCatchObjectInternal(pExcept, pRN, pCatch, pConv); +} +#endif // _VCRT_BUILD_FH4 + +////////////////////////////////////////////////////////////////////////////////// +// IsInExceptionSpec - Checks if the exception matches the exception specification +// list. Returns TRUE if it does, otherwise FALSE +// +static BOOLEAN IsInExceptionSpec( + EHExceptionRecord *pExcept, // Information for this (logical) exception + ESTypeList *pESTypeList // Static information for subject frame +) +{ + _VCRT_VERIFY(pESTypeList); + BOOLEAN bFoundMatchingTypeInES = FALSE; + +#if _EH_RELATIVE_TYPEINFO + __int32 const *ppCatchable; +#elif defined(_WIN64) + CatchableType * UNALIGNED const *ppCatchable; +#else + CatchableType * const *ppCatchable; +#endif + CatchableType *pCatchable; + int catchables; + + // for every type in the exception spec... + for (int i=0; i 0; catchables--, ppCatchable++) { + +#if _EH_RELATIVE_TYPEINFO + pCatchable = (CatchableType *)(_GetThrowImageBase() + *ppCatchable); +#else + pCatchable = *ppCatchable; +#endif + if (RENAME_EH_EXTERN(__TypeMatch)(EST_ARRAY(pESTypeList,i), pCatchable, PER_PTHROW(pExcept))) + { + bFoundMatchingTypeInES = TRUE; + break; + } + } + } + + return bFoundMatchingTypeInES; +} + +////////////////////////////////////////////////////////////////////////////////// +// CallUnexpected - Calls unexpected and handles all exceptions +// thrown by it +// +// The unexpected() function shall not return, but it can throw (or re-throw) an +// exception. +// +// If it throws a new exception which is allowed by the exception +// specification which previously was violated, then +// { +// the search for another handler will continue at the call of the function +// whose exception specification was violated. +// } +// else /* If it throws or rethrows an exception that the exception-specification does not +// allow */ then the following happens: +// { +// If the exception-specification does not include the class std::bad_exception +// (lib.bad.exception) then +// { +// the function terminate() is called, +// } +// otherwise +// { +// the thrown exception is replaced by an implementation-defined +// object of the type std::bad_exception and the search for another handler +// will continue at the call of the function whose exception-specification +// was violated. +// } +// } +// +// Simple, isn't it? +// +static void CallUnexpected( ESTypeList* pESTypeList ) +{ + _VCRT_VERIFY(_pCurrentFuncInfo == nullptr); + + try + { + unexpected(); + } + catch(...) + { + _pCurrentFuncInfo = pESTypeList; + + throw; // rethrow -- we will catch it in the FrameHandler + } + terminate(); +} + +////////////////////////////////////////////////////////////////////////////////// +// Is_bad_exception_allowed - checks if std::bad_exception belongs to the list +// +static BOOLEAN Is_bad_exception_allowed(ESTypeList *pESTypeList) +{ + for (int i=0; i + + + +#define STATUS_SECURITY_CHECK_FAILURE STATUS_STACK_BUFFER_OVERRUN + +// Check if __fastfail is known to be available or if it should be checked. +// Simplifies subsequent ifdefs. +#if defined _CRT_APP || defined _M_ARM || defined _M_ARM64 || defined _SCRT_ENCLAVE_BUILD + +#define PROCESSOR_FAST_FAIL_AVAILABLE + +#elif defined _M_IX86 || defined _M_X64 + +// No extra define, lack of define from above signals this path. + +#else + +#error Unsupported architecture + +#endif + + +extern UINT_PTR __security_cookie; +extern UINT_PTR __security_cookie_complement; + + + +// Use global memory for the exception and context records, and any other local +// state needed by __report_gsfailure and __report_securityfailure. We're not +// worried about multithread issues here - we're going to die anyway, and it +// saves us from consuming a good chunk of stack, as well as potentially +// overwriting useful data in the stack memory dump. +static EXCEPTION_RECORD GS_ExceptionRecord; +static CONTEXT GS_ContextRecord; +static EXCEPTION_POINTERS const GS_ExceptionPointers = +{ + &GS_ExceptionRecord, + &GS_ContextRecord +}; + + + +#ifdef _VCRT_BUILD + static BOOL DebuggerWasPresent; +#endif + + + +#if !defined PROCESSOR_FAST_FAIL_AVAILABLE && defined _M_X64 + + static void __cdecl capture_current_context(CONTEXT* pContextRecord) + { + ULONG64 ControlPc; + ULONG64 EstablisherFrame; + ULONG64 ImageBase; + PRUNTIME_FUNCTION FunctionEntry; + PVOID HandlerData; + + RtlCaptureContext(pContextRecord); + + ControlPc = pContextRecord->Rip; + FunctionEntry = RtlLookupFunctionEntry(ControlPc, &ImageBase, NULL); + + if (FunctionEntry != NULL) + { + RtlVirtualUnwind( + UNW_FLAG_NHANDLER, + ImageBase, + ControlPc, + FunctionEntry, + pContextRecord, + &HandlerData, + &EstablisherFrame, + NULL); + } + } + + static void __cdecl capture_previous_context(CONTEXT* pContextRecord) + { + ULONG64 ControlPc; + ULONG64 EstablisherFrame; + ULONG64 ImageBase; + PRUNTIME_FUNCTION FunctionEntry; + PVOID HandlerData; + INT frames; + + RtlCaptureContext(pContextRecord); + + ControlPc = pContextRecord->Rip; + + // Unwind "twice" to get the context of the caller to the "previous" caller: + for (frames = 0; frames < 2; ++frames) + { + FunctionEntry = RtlLookupFunctionEntry(ControlPc, &ImageBase, NULL); + + if (FunctionEntry != NULL) + { + RtlVirtualUnwind( + UNW_FLAG_NHANDLER, + ImageBase, + ControlPc, + FunctionEntry, + pContextRecord, + &HandlerData, + &EstablisherFrame, + NULL); + } + else + { + break; + } + } + } + +#endif // !defined PROCESSOR_FAST_FAIL_AVAILABLE && defined _M_X64 + + + +// __raise_securityfailure() - Raises a security failure and terminates the process. +// +// Invokes the unhandled exception filter using the provided exception pointers and +// then terminates the process. +#if !defined PROCESSOR_FAST_FAIL_AVAILABLE + +#if _CONTROL_FLOW_GUARD_SHADOW_STACK_SUPPORTED + __declspec(guard(nosspro)) __declspec(guard(nossepi)) +#endif + __declspec(noreturn) void __cdecl __raise_securityfailure( + PEXCEPTION_POINTERS const exception_pointers + ) + { + #ifdef _VCRT_BUILD + DebuggerWasPresent = IsDebuggerPresent(); + _CRT_DEBUGGER_HOOK(_CRT_DEBUGGER_GSFAILURE); + #endif // _VCRT_BUILD + + SetUnhandledExceptionFilter(NULL); + UnhandledExceptionFilter(exception_pointers); + + #ifdef _VCRT_BUILD + // If we make it back from Watson, then the user may have asked to debug + // the app. If we weren't under a debugger before invoking Watson, + // re-signal the VS CRT debugger hook, so a newly attached debugger gets + // a chance to break into the process. + if (!DebuggerWasPresent) + { + _CRT_DEBUGGER_HOOK(_CRT_DEBUGGER_GSFAILURE); + } + #endif // _VCRT_BUILD + + TerminateProcess(GetCurrentProcess(), STATUS_SECURITY_CHECK_FAILURE); + } + +#endif // !defined PROCESSOR_FAST_FAIL_AVAILABLE + + + +// Force an EBP frame on x86; no stack packing. Forcing a frame applies to all +// of the functions below, including __report_gsfailure, __report_securityfailure, +// and __report_securityfailureEx +BEGIN_PRAGMA_OPTIMIZE_DISABLE("", DevDivVSO:162582, "Optimizations must be disabled to enable us to walk the stack") + + + +// __report_gsfailure() - Report security error. +// +// A /GS security error has been detected. We save the registers in a CONTEXT +// struct & call UnhandledExceptionFilter to display a message to the user +// (invoke Watson handling) and terminate the program. +// +// NOTE: __report_gsfailure should not be called directly. Instead, it should +// be entered due to a failure detected by __security_check_cookie. That's +// because __security_check_cookie may perform more checks than just a mismatch +// against the global security cookie, and because the context captured by +// __report_gsfailure is unwound assuming that __security_check_cookie was +// used to detect the failure. +// +// ULONGLONG StackCookie - the local cookie. On x86, the local cookie is not +// passed in and is instead available in ECX, but since __report_gsfailure isn't +// __fastcall, it isn't a true argument, and we must flush ECX to the context +// record quickly. +#if defined _M_IX86 + #define GSFAILURE_PARAMETER +#elif defined _M_X64 + #define GSFAILURE_PARAMETER _In_ ULONGLONG stack_cookie +#elif defined _M_ARM || defined _M_ARM64 + #define GSFAILURE_PARAMETER _In_ uintptr_t stack_cookie +#else + #error Unsupported architecture +#endif + +#if defined PROCESSOR_FAST_FAIL_AVAILABLE + + #pragma warning(push) + #pragma warning(disable: 4100) // unreferenced formal parameter + __declspec(noreturn) void __cdecl __report_gsfailure(GSFAILURE_PARAMETER) + { + __fastfail(FAST_FAIL_STACK_COOKIE_CHECK_FAILURE); + } + #pragma warning(pop) + +#else + +#if _CONTROL_FLOW_GUARD_SHADOW_STACK_SUPPORTED + __declspec(guard(nosspro)) __declspec(guard(nossepi)) +#endif + __declspec(noreturn) void __cdecl __report_gsfailure(GSFAILURE_PARAMETER) + { + if (IsProcessorFeaturePresent(PF_FASTFAIL_AVAILABLE)) + { + __fastfail(FAST_FAIL_STACK_COOKIE_CHECK_FAILURE); + } + + volatile UINT_PTR cookie[2]; + + // Set up a fake exception, and report it via UnhandledExceptionFilter. + // We can't raise a true exception because the stack (and therefore + // exception handling) can't be trusted after a buffer overrun. The + // exception should appear as if it originated after the call to + // __security_check_cookie, so it is attributed to the function where the + // buffer overrun was detected. + + #if defined _M_IX86 + // On x86, we reserve some extra stack which won't be used. That is to + // preserve as much of the call frame as possible when the function with + // the buffer overrun entered __security_check_cookie with a JMP instead of + // a CALL, after the calling frame has been released in the epilogue of + // that function. + ULONG volatile dw[(sizeof(CONTEXT) + sizeof(EXCEPTION_RECORD)) / sizeof(ULONG)]; + + // Save the state in the context record immediately. Hopefully, since + // opts are disabled, this will happen without modifying ECX, which has + // the local cookie which failed the check. + __asm + { + mov dword ptr [GS_ContextRecord.Eax ], eax + mov dword ptr [GS_ContextRecord.Ecx ], ecx + mov dword ptr [GS_ContextRecord.Edx ], edx + mov dword ptr [GS_ContextRecord.Ebx ], ebx + mov dword ptr [GS_ContextRecord.Esi ], esi + mov dword ptr [GS_ContextRecord.Edi ], edi + mov word ptr [GS_ContextRecord.SegSs], ss + mov word ptr [GS_ContextRecord.SegCs], cs + mov word ptr [GS_ContextRecord.SegDs], ds + mov word ptr [GS_ContextRecord.SegEs], es + mov word ptr [GS_ContextRecord.SegFs], fs + mov word ptr [GS_ContextRecord.SegGs], gs + pushfd + pop [GS_ContextRecord.EFlags] + + // Set the context EBP/EIP/ESP to the values which would be found + // in the caller to __security_check_cookie. + mov eax, [ebp] + mov dword ptr [GS_ContextRecord.Ebp], eax + mov eax, [ebp+4] + mov dword ptr [GS_ContextRecord.Eip], eax + lea eax, [ebp+8] + mov dword ptr [GS_ContextRecord.Esp], eax + + // Make sure the dummy stack space looks referenced. + mov eax, dword ptr dw + } + + GS_ContextRecord.ContextFlags = CONTEXT_CONTROL; + GS_ExceptionRecord.ExceptionAddress = (PVOID)(ULONG_PTR)GS_ContextRecord.Eip; + + #else // ^^^ _M_IX86 ^^^ // vvv _M_X64 vvv // + + capture_previous_context(&GS_ContextRecord); + GS_ContextRecord.Rip = (ULONGLONG)_ReturnAddress(); + GS_ContextRecord.Rsp = (ULONGLONG)_AddressOfReturnAddress()+8; + GS_ExceptionRecord.ExceptionAddress = (PVOID)GS_ContextRecord.Rip; + GS_ContextRecord.Rcx = stack_cookie; + + #endif // _M_X64 + + GS_ExceptionRecord.ExceptionCode = STATUS_SECURITY_CHECK_FAILURE; + GS_ExceptionRecord.ExceptionFlags = EXCEPTION_NONCONTINUABLE; + GS_ExceptionRecord.NumberParameters = 1; + GS_ExceptionRecord.ExceptionInformation[0] = FAST_FAIL_STACK_COOKIE_CHECK_FAILURE; + + // Save the global cookie and cookie complement locally - using an array + // to defeat any potential stack-packing. + cookie[0] = __security_cookie; + cookie[1] = __security_cookie_complement; + + // Raise the security failure by passing it to the unhandled exception + // filter and then terminate the process. + __raise_securityfailure((EXCEPTION_POINTERS*)&GS_ExceptionPointers); + } + +#endif + + + +// Reports a specific security failure condition +// +// Reports a specific security failure condition. The type of failure that +// occurred is embodied in the failure_code that is provided as a parameter. +// A specific failure condition can optionally specify additional parameters +// that should be recorded as part of the exception that is generated. +// +// NOTE: Unlike __report_gsfailure, __report_securityfailureEx assumes that +// it is called directly by the function in which the failure occurred. +#if defined PROCESSOR_FAST_FAIL_AVAILABLE + + __declspec(noreturn) void __cdecl __report_securityfailureEx( + _In_ ULONG failure_code, + _In_ ULONG parameter_count, + _In_reads_opt_(parameter_count) void** parameters + ) + { + UNREFERENCED_PARAMETER(parameter_count); + UNREFERENCED_PARAMETER(parameters); + + __fastfail(failure_code); + } + +#else + +#if _CONTROL_FLOW_GUARD_SHADOW_STACK_SUPPORTED + __declspec(guard(nosspro)) __declspec(guard(nossepi)) +#endif + __declspec(noreturn) void __cdecl __report_securityfailureEx( + _In_ ULONG failure_code, + _In_ ULONG parameter_count, + _In_reads_opt_(parameter_count) void** parameters + ) + { + if (IsProcessorFeaturePresent(PF_FASTFAIL_AVAILABLE)) + { + __fastfail(failure_code); + } + + // Set up a fake exception, and report it via UnhandledExceptionFilter. + // We can't raise a true exception because the stack (and therefore + // exception handling) can't be trusted. The exception should appear as + // if it originated after the call to __report_securityfailureEx, so it + // is attributed to the function where the violation occurred. + // + // We assume that the immediate caller of __report_securityfailureEx is + // the function where the security violation occurred. Note that the + // compiler may elect to emit a jump to this routine instead of a call, + // in which case we will not be able to blame the correct function. + #ifdef _M_IX86 + + // On x86, we reserve some extra stack which won't be used. That is to + // preserve as much of the call frame as possible when the function with + // the buffer overrun entered __security_check_cookie with a JMP instead + // of a CALL, after the calling frame has been released in the epilogue + // of that function. + ULONG volatile dw[(sizeof(CONTEXT) + sizeof(EXCEPTION_RECORD)) / sizeof(ULONG)]; + + // Save the state in the context record immediately. Hopefully, since + // opts are disabled, this will happen without modifying ECX, which has + // the local cookie which failed the check. + __asm + { + mov dword ptr [GS_ContextRecord.Eax ], eax + mov dword ptr [GS_ContextRecord.Ecx ], ecx + mov dword ptr [GS_ContextRecord.Edx ], edx + mov dword ptr [GS_ContextRecord.Ebx ], ebx + mov dword ptr [GS_ContextRecord.Esi ], esi + mov dword ptr [GS_ContextRecord.Edi ], edi + mov word ptr [GS_ContextRecord.SegSs], ss + mov word ptr [GS_ContextRecord.SegCs], cs + mov word ptr [GS_ContextRecord.SegDs], ds + mov word ptr [GS_ContextRecord.SegEs], es + mov word ptr [GS_ContextRecord.SegFs], fs + mov word ptr [GS_ContextRecord.SegGs], gs + pushfd + pop [GS_ContextRecord.EFlags] + + // Set the context EBP/EIP/ESP to the values which would be found + // in the caller to __security_check_cookie. + mov eax, [ebp] + mov dword ptr [GS_ContextRecord.Ebp], eax + mov eax, [ebp + 4] + mov dword ptr [GS_ContextRecord.Eip], eax + lea eax, [ebp + 8] + mov dword ptr [GS_ContextRecord.Esp], eax + + // Make sure the dummy stack space looks referenced. + mov eax, dword ptr dw + } + + GS_ExceptionRecord.ExceptionAddress = (PVOID)GS_ContextRecord.Eip; + + #else // ^^^ _M_IX86 ^^^ // vvv _M_X64 vvv // + + capture_current_context(&GS_ContextRecord); + GS_ContextRecord.Rip = (ULONGLONG) _ReturnAddress(); + GS_ContextRecord.Rsp = (ULONGLONG) _AddressOfReturnAddress()+8; + GS_ExceptionRecord.ExceptionAddress = (PVOID)GS_ContextRecord.Rip; + + #endif // _M_X64 + + GS_ExceptionRecord.ExceptionCode = STATUS_SECURITY_CHECK_FAILURE; + GS_ExceptionRecord.ExceptionFlags = EXCEPTION_NONCONTINUABLE; + + if (parameter_count > 0 && parameters == NULL) + { + parameter_count = 0; + } + + if (parameter_count > EXCEPTION_MAXIMUM_PARAMETERS - 1) + { + parameter_count--; + } + + GS_ExceptionRecord.NumberParameters = parameter_count + 1; + GS_ExceptionRecord.ExceptionInformation[0] = failure_code; + + for (ULONG i = 0; i < parameter_count; i++) + { + GS_ExceptionRecord.ExceptionInformation[i + 1] = (ULONG_PTR)parameters[i]; + } + + // Raise the security failure by passing it to the unhandled exception + // filter and then terminate the process. + __raise_securityfailure((EXCEPTION_POINTERS*)&GS_ExceptionPointers); + } + +#endif + + + +// Reports a specific security failure condition. The type of failure that +// occurred is embodied in the failure_code that is provided as a parameter. +// If a failure condition needs to specify additional parameters then it +// should call __report_securityfailureEx instead. +// +// NOTE: Unlike __report_gsfailure, __report_securityfailure assumes that it is +// called directly by the function in which the failure occurred. This also +// means that __security_reportfailure doesn't simply call +// +// __report_securityfailureEx(failure_code, 0, 0); +// +// as that would alter the call stack. +#if defined PROCESSOR_FAST_FAIL_AVAILABLE + + __declspec(noinline) void __cdecl __report_securityfailure(ULONG failure_code) + { + __fastfail(failure_code); + } + +#else + +#if _CONTROL_FLOW_GUARD_SHADOW_STACK_SUPPORTED + __declspec(guard(nosspro)) __declspec(guard(nossepi)) +#endif + __declspec(noinline) void __cdecl __report_securityfailure(ULONG failure_code) + { + if (IsProcessorFeaturePresent(PF_FASTFAIL_AVAILABLE)) + { + __fastfail(failure_code); + } + + // Set up a fake exception, and report it via UnhandledExceptionFilter. + // We can't raise a true exception because the stack (and therefore + // exception handling) can't be trusted. The exception should appear as + // if it originated after the call to __report_securityfailure, so it + // is attributed to the function where the violation occurred. + // + // We assume that the immediate caller of __report_securityfailure is + // the function where the security violation occurred. Note that the + // compiler may elect to emit a jump to this routine instead of a call, + // in which case we will not be able to blame the correct function. + #if defined _M_IX86 + + // On x86, we reserve some extra stack which won't be used. That is to + // preserve as much of the call frame as possible when the function with + // the buffer overrun entered __security_check_cookie with a JMP instead + // of a CALL, after the calling frame has been released in the epilogue + // of that function. + volatile ULONG dw[(sizeof(CONTEXT) + sizeof(EXCEPTION_RECORD))/sizeof(ULONG)]; + + // Save the state in the context record immediately. Hopefully, since + // opts are disabled, this will happen without modifying ECX, which has + // the local cookie which failed the check. + __asm + { + mov dword ptr [GS_ContextRecord.Eax ], eax + mov dword ptr [GS_ContextRecord.Ecx ], ecx + mov dword ptr [GS_ContextRecord.Edx ], edx + mov dword ptr [GS_ContextRecord.Ebx ], ebx + mov dword ptr [GS_ContextRecord.Esi ], esi + mov dword ptr [GS_ContextRecord.Edi ], edi + mov word ptr [GS_ContextRecord.SegSs], ss + mov word ptr [GS_ContextRecord.SegCs], cs + mov word ptr [GS_ContextRecord.SegDs], ds + mov word ptr [GS_ContextRecord.SegEs], es + mov word ptr [GS_ContextRecord.SegFs], fs + mov word ptr [GS_ContextRecord.SegGs], gs + pushfd + pop [GS_ContextRecord.EFlags] + + // Set the context EBP/EIP/ESP to the values which would be found + // in the caller to __security_check_cookie. + mov eax, [ebp] + mov dword ptr [GS_ContextRecord.Ebp], eax + mov eax, [ebp + 4] + mov dword ptr [GS_ContextRecord.Eip], eax + lea eax, [ebp + 8] + mov dword ptr [GS_ContextRecord.Esp], eax + + // Make sure the dummy stack space looks referenced. + mov eax, dword ptr dw + } + + GS_ExceptionRecord.ExceptionAddress = (PVOID)GS_ContextRecord.Eip; + + #else // ^^^ _M_IX86 ^^^ // vvv _M_X64 vvv // + + capture_current_context(&GS_ContextRecord); + GS_ContextRecord.Rip = (ULONGLONG) _ReturnAddress(); + GS_ContextRecord.Rsp = (ULONGLONG) _AddressOfReturnAddress()+8; + GS_ExceptionRecord.ExceptionAddress = (PVOID)GS_ContextRecord.Rip; + + #endif // _M_X64 + + GS_ExceptionRecord.ExceptionCode = STATUS_SECURITY_CHECK_FAILURE; + GS_ExceptionRecord.ExceptionFlags = EXCEPTION_NONCONTINUABLE; + + GS_ExceptionRecord.NumberParameters = 1; + GS_ExceptionRecord.ExceptionInformation[0] = failure_code; + + /* + * Raise the security failure by passing it to the unhandled exception + * filter and then terminate the process. + */ + + __raise_securityfailure((EXCEPTION_POINTERS*)&GS_ExceptionPointers); + } + +#endif + + + +// Declare stub for rangecheckfailure, since these occur often enough that the +// code bloat of setting up the parameters hurts performance +#if _CONTROL_FLOW_GUARD_SHADOW_STACK_SUPPORTED +__declspec(guard(nosspro)) __declspec(guard(nossepi)) +#endif +__declspec(noreturn) void __cdecl __report_rangecheckfailure() +{ + __report_securityfailure(FAST_FAIL_RANGE_CHECK_FAILURE); +} diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/gs_support.c b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/gs_support.c new file mode 100644 index 0000000000000000000000000000000000000000..045f0342e948ad64c97993ddfffc4cf6488801b4 --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/gs_support.c @@ -0,0 +1,205 @@ +/*** +*gs_support.c - initialize the global buffer overrun security cookie +* +* Copyright (c) Microsoft Corporation. All rights reserved. +* +*Purpose: +* Define __security_init_cookie, which is called at startup to initialize +* the global buffer overrun security cookie used by the /GS compile flag. +* +*******************************************************************************/ + +#include + +#if defined (_M_IX86) && defined (_CRTBLD) && defined (_DEBUG) +/* + * __security_init_cookie must be called before any exception handlers using + * the cookie are registered. We do a spot check for this condition in the + * debug version of the x86 CRT. + */ + +#define CHECK_FOR_LATE_COOKIE_INIT + +#define EXCEPTION_CHAIN_END ((struct _EXCEPTION_REGISTRATION_RECORD * POINTER_32)-1) + +EXCEPTION_DISPOSITION __cdecl +_except_handler4( + IN struct _EXCEPTION_RECORD *ExceptionRecord, + IN PVOID EstablisherFrame, + IN OUT struct _CONTEXT *ContextRecord, + IN OUT PVOID DispatcherContext + ); + +#endif /* defined (_M_IX86) && defined (_CRTBLD) && defined (_DEBUG) */ + +/* + * Default value used for the global /GS security cookie, defined here and + * in gs_cookie.c (since standalone SDK build can't use CRT's internal.h). + */ + +#ifdef _WIN64 +#define DEFAULT_SECURITY_COOKIE 0x00002B992DDFA232 +#else /* _WIN64 */ +#define DEFAULT_SECURITY_COOKIE 0xBB40E64E +#endif /* _WIN64 */ + +/* + * The global security cookie. This name is known to the compiler. + */ +extern UINT_PTR __security_cookie; +extern UINT_PTR __security_cookie_complement; + +/* + * Union to facilitate converting from FILETIME to unsigned __int64 + */ +typedef union { + unsigned __int64 ft_scalar; + FILETIME ft_struct; +} FT; + +/*** +*__get_entropy() - retrieve entropy from the underlying OS. +* +*Purpose: +* Static helper to encapsulate entropy extraction from the OS. +* Combine a number of sources of randomness. +* +*Entry: +* +*Exit: +* +*Exceptions: +* +*******************************************************************************/ + +/* +* Enclaves initialize the stack cookie in the loader (similar to all +* modern platforms), but do not expose entropy. No attempt should be made +* to reinitialize the cookie by harvesting new entropy. +*/ +#if defined (_SCRT_ENCLAVE_BUILD) + +static UINT_PTR __get_entropy(void) +{ + return DEFAULT_SECURITY_COOKIE; +} + +#else + +static UINT_PTR __get_entropy(void) +{ + UINT_PTR cookie; + FT systime = { 0 }; + LARGE_INTEGER perfctr; + + GetSystemTimeAsFileTime(&systime.ft_struct); +#if defined (_WIN64) + cookie = systime.ft_scalar; +#else /* defined (_WIN64) */ + cookie = systime.ft_struct.dwLowDateTime; + cookie ^= systime.ft_struct.dwHighDateTime; +#endif /* defined (_WIN64) */ + + cookie ^= GetCurrentThreadId(); + cookie ^= GetCurrentProcessId(); + +#if _CRT_NTDDI_MIN >= NTDDI_VISTA +#if defined (_WIN64) + cookie ^= (((UINT_PTR)GetTickCount64()) << 56); +#endif /* defined (_WIN64) */ + cookie ^= (UINT_PTR)GetTickCount64(); +#endif /* _CRT_NTDDI_MIN >= NTDDI_VISTA */ + + QueryPerformanceCounter(&perfctr); +#if defined (_WIN64) + cookie ^= (((UINT_PTR)perfctr.LowPart << 32) ^ perfctr.QuadPart); +#else /* defined (_WIN64) */ + cookie ^= perfctr.LowPart; + cookie ^= perfctr.HighPart; +#endif /* defined (_WIN64) */ + + /* + * Increase entropy using ASLR relocation + */ + cookie ^= (UINT_PTR)&cookie; + +#if defined (_WIN64) + /* + * On Win64, generate a cookie with the most significant word set to zero, + * as a defense against buffer overruns involving null-terminated strings. + * Don't do so on Win32, as it's more important to keep 32 bits of cookie. + */ + cookie &= 0x0000FFFFffffFFFFi64; +#endif /* defined (_WIN64) */ + + return cookie; +} + +#endif + +/*** +*__security_init_cookie() - init buffer overrun security cookie. +* +*Purpose: +* Initialize the global buffer overrun security cookie which is used by +* the /GS compile switch to detect overwrites to local array variables +* that potentially corrupt the return address. This routine is called +* at EXE/DLL startup. +* +*Entry: +* +*Exit: +* +*Exceptions: +* +*******************************************************************************/ + +void __cdecl __security_init_cookie(void) +{ + UINT_PTR cookie; + + /* + * Do nothing if the global cookie has already been initialized. On x86, + * reinitialize the cookie if it has been previously initialized to a + * value with the high word 0x0000. Some versions of Windows will init + * the cookie in the loader, but using an older mechanism which forced the + * high word to zero. + */ + + if (__security_cookie != DEFAULT_SECURITY_COOKIE +#if defined (_M_IX86) + && (__security_cookie & 0xFFFF0000) != 0 +#endif /* defined (_M_IX86) */ + ) + { + __security_cookie_complement = ~__security_cookie; + return; + } + + + /* + * Initialize the global cookie with an unpredictable value which is + * different for each module in a process. + */ + cookie = __get_entropy(); + + /* + * Make sure the cookie is initialized to a value that will prevent us from + * reinitializing it if this routine is ever called twice. + */ + + if (cookie == DEFAULT_SECURITY_COOKIE) + { + cookie = DEFAULT_SECURITY_COOKIE + 1; + } +#if defined (_M_IX86) + else if ((cookie & 0xFFFF0000) == 0) + { + cookie |= ( (cookie|0x4711) << 16); + } +#endif /* defined (_M_IX86) */ + + __security_cookie = cookie; + __security_cookie_complement = ~cookie; + +} diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/guard_support.c b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/guard_support.c new file mode 100644 index 0000000000000000000000000000000000000000..dc14f906c9990c8f503a618240d8b4a8344cc1f3 --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/guard_support.c @@ -0,0 +1,479 @@ +/*** +*guard_support.c - logic and globals to support the Guard security feature +* +* Copyright (c) Microsoft Corporation. All rights reserved. +* +*Purpose: +* Define the globals and default check routine for the Guard security +* feature. +* +* N.B. Code and data declared by this module must be in the form of +* selectany COMDATs, so that duplicate definitions between the +* CRT and no_cfg_support are permitted for the restricted use +* cases of the no_cfg_support module. +* +*******************************************************************************/ + +#include +#include +#include + +#ifndef FAST_FAIL_CAST_GUARD +#define FAST_FAIL_CAST_GUARD 65 +#endif + +typedef +void +(__fastcall *GUARDCF_CHECK_ROUTINE) ( + uintptr_t Target + ); + +#if defined(_AMD64_) || defined(_ARM64_) + +// +// Deliberately misdeclared as data and not code so that the free branch +// instruction is not itself considered a valid call target. +// + +extern const unsigned char _guard_dispatch_icall_nop; + +#endif + +#if defined(_AMD64_) + +// +// Deliberately misdeclared as data and not code so that the free branch +// instruction is not itself considered a valid call target. +// + +extern const unsigned char _guard_xfg_dispatch_icall_nop; + +#endif + +// +// The CHPE version of the _guard_check_icall_nop function does not preserve +// ECX, as is required by the custom CFG calling convention on x86. Force the +// guest version of this function to be chosen instead. +// + +#if defined(_M_HYBRID_X86_ARM64) + +__declspec(hybrid_guest) +void +__fastcall +_guard_check_icall_nop ( + _In_ uintptr_t Target + ); + +#else + +extern +__inline +void +__fastcall +_guard_check_icall_nop ( + _In_ uintptr_t Target + ) + +/*++ + +Routine Description: + + This function performs a no-op check when invoked by the compiler to check + the integrity of a function pointer for Control Flow Guard (/guard). + +Arguments: + + Target - Supplies the function pointer to check. + +Return Value: + + None. + +--*/ + +{ + + UNREFERENCED_PARAMETER(Target); + return; +} + +#endif + +#pragma section(".00cfg", read) + +// Devdiv:1093613 - __guard_icall_check_fptr is only modified by the loader and +// so it appears to be read-only during compilation. We mark it volatile to +// ensure uses of it are not optimized away. +__declspec(allocate(".00cfg")) +DECLSPEC_SELECTANY +volatile PVOID __guard_check_icall_fptr = (PVOID)_guard_check_icall_nop; + +__declspec(allocate(".00cfg")) +DECLSPEC_SELECTANY +volatile PVOID __guard_xfg_check_icall_fptr = (PVOID)_guard_check_icall_nop; + +#if defined(_AMD64_) || defined(_ARM64_) + +__declspec(allocate(".00cfg")) +DECLSPEC_SELECTANY +volatile PVOID __guard_dispatch_icall_fptr = (PVOID)&_guard_dispatch_icall_nop; + +#endif + +#if defined(_AMD64_) + +__declspec(allocate(".00cfg")) +DECLSPEC_SELECTANY +volatile PVOID __guard_xfg_dispatch_icall_fptr = (PVOID)&_guard_xfg_dispatch_icall_nop; + +__declspec(allocate(".00cfg")) +DECLSPEC_SELECTANY +volatile PVOID __guard_xfg_table_dispatch_icall_fptr = (PVOID)&_guard_xfg_dispatch_icall_nop; + +#endif + +__declspec(allocate(".00cfg")) +DECLSPEC_SELECTANY +VOID (* volatile __castguard_check_failure_os_handled_fptr)(PVOID rhsVftablePtr) = NULL; + +DECLSPEC_SELECTANY +volatile __check_guard_fp __castguard_check_failure_user_handled_fptr = NULL; + +extern +__inline +int +_guard_icall_checks_enforced ( + VOID + ) + +/*++ + +Routine Description: + + This function determines whether Control Flow Guard is enforced for the + current module. + +Arguments: + + None. + +Return Value: + + A nonzero value is returned as the function value if Control Flow Guard + is enforced for the current module. + +--*/ + +{ + + return (ReadPointerNoFence(&__guard_check_icall_fptr) != (PVOID)_guard_check_icall_nop); +} + + +#if defined(_AMD64_) +extern +__inline +int +__cdecl +_guard_rf_checks_enforced ( + VOID + ) + +/*++ + +Routine Description: + + This function determines whether Return Flow Guard is enforced for the + current module. + +Arguments: + + None. + +Return Value: + + A nonzero value is returned as the function value if Return Flow Guard + is enforced for the current module. + +--*/ + +{ + return 0; +} + +#endif + +#pragma section(".rdata$CastGuardVftablesA", read) +#pragma section(".rdata$CastGuardVftablesC", read) + +// +// Count (in number of pointers) of the alignment of the CastGuard region. +// This translates to 128-byte alignment on 64-bit platforms and 64-bytes +// on 32-bit platforms. +// + +#define CAST_GUARD_SECTION_ALIGNMENT_IN_PTRS 16 + +#if defined(_WIN64) +#define CAST_GUARD_SECTION_ALIGNMENT 128 +#else +#define CAST_GUARD_SECTION_ALIGNMENT 64 +#endif + +static_assert(CAST_GUARD_SECTION_ALIGNMENT_IN_PTRS * sizeof(void*) == CAST_GUARD_SECTION_ALIGNMENT, "Invalid alignment"); + +// +// CastGuard checks lowered by the compiler, for efficiency, have an assumption that vftables laid out +// by CastGuard start at a 128-byte alignment for 64-bit and 64-byte alignment for 32-bit. The section these +// vftables are placed have this alignment specified by the compiler. +// +// __CastGuardVftableStart is a very special symbol. In order to do AppCompat checks correctly, +// we need to know the precise distance of __CastGuardVftablesStart variable from the first +// vftable laid out by CastGuard. The CastGuardVftablesB section (created by the compiler) +// is aligned by 16*sizeof(void*). The start variable therefore must have the exact same +// alignment as the section such that there's always 16*sizeof(void*) bytes between the address +// of this variable and the address of the first vftable. +// +// If no vftables are laid out, __CastGuardVftablesStart will be 64/128 bytes away from the +// __CastGuardVftablesEnd global variable. The code in __castguard_compat_check explicitly +// adds this 64/128 bytes to the __CastGuardVftablesStart, so it's important to ensure that the +// alignment is always respected. +// + +struct __declspec(align(CAST_GUARD_SECTION_ALIGNMENT)) CastGuardVftables { + char padding[CAST_GUARD_SECTION_ALIGNMENT]; +}; + +__declspec(allocate(".rdata$CastGuardVftablesA")) +DECLSPEC_SELECTANY +volatile struct CastGuardVftables __CastGuardVftablesStart; + +__declspec(allocate(".rdata$CastGuardVftablesC")) +DECLSPEC_SELECTANY +volatile struct CastGuardVftables __CastGuardVftablesEnd; + +static +inline +BOOL +__cdecl __castguard_compat_check(PVOID rhsVftablePtr) +{ + ULONG_PTR realVftableRangeStart = (ULONG_PTR)&__CastGuardVftablesStart + sizeof(struct CastGuardVftables); + ULONG_PTR realVftableRangeEnd = (ULONG_PTR)&__CastGuardVftablesEnd; + ULONG_PTR vftableRangeSize = realVftableRangeEnd - realVftableRangeStart; + + return (ULONG_PTR)rhsVftablePtr - realVftableRangeStart <= vftableRangeSize; +} + +extern +inline +__check_guard_fp +__cdecl __castguard_set_user_handler(__check_guard_fp new_handler) +{ + // We are doing an atomic operation to set the new value and get the old value. + // Therefore, we're using the InterlockedExchangePointer to make it synchronized. + + __check_guard_fp old_handler; + old_handler = (__check_guard_fp) InterlockedExchangePointer((PVOID volatile*) &__castguard_check_failure_user_handled_fptr, + (PVOID) new_handler); + + return old_handler; +} + + +static +inline +void +__declspec(guard(nocf)) +__cdecl __castguard_check_failure_os_handled_wrapper( + PVOID rhsVftablePtr + ) +{ + + // + // This function is opted out of CFG because the os handled function pointer + // is allocated within ".00cfg" section. This section benefits from the same + // level of protection as a CFG pointer would. + // + + __check_guard_fp castguard_os_handled_fptr = (__check_guard_fp) ReadPointerNoFence((PVOID volatile*) &__castguard_check_failure_os_handled_fptr); + + if (castguard_os_handled_fptr != NULL) + { + castguard_os_handled_fptr(rhsVftablePtr); + } + + return; +} + +static +inline +void +__cdecl __castguard_check_failure_user_handled_wrapper( + PVOID rhsVftablePtr + ) +{ + __check_guard_fp castguard_user_handled_fptr = (__check_guard_fp) ReadPointerNoFence((PVOID volatile*) &__castguard_check_failure_user_handled_fptr); + + if (castguard_user_handled_fptr != NULL) + { + castguard_user_handled_fptr(rhsVftablePtr); + } + + return; +} + +extern +inline +void __cdecl __castguard_check_failure_nop(PVOID rhsVftablePtr) +{ + (void)rhsVftablePtr; + // + // Don't bother with the compat check, we'll do nothing either way. + // + return; +} + +extern +inline +void __cdecl __castguard_check_failure_debugbreak(PVOID rhsVftablePtr) +{ + if (__castguard_compat_check(rhsVftablePtr)) + { + __debugbreak(); + } + + // + // Fail open if vftable is not in the CastGuard vftable range. + // + return; +} + +extern +inline +void __cdecl __castguard_check_failure_fastfail(PVOID rhsVftablePtr) +{ + if (__castguard_compat_check(rhsVftablePtr)) + { + __fastfail(FAST_FAIL_CAST_GUARD); + } + + // + // Fail open if vftable is not in the CastGuard vftable range. + // + return; +} + +extern +inline +void __cdecl __castguard_check_failure_os_handled(PVOID rhsVftablePtr) +{ + if (__castguard_compat_check(rhsVftablePtr)) + { + __castguard_check_failure_os_handled_wrapper(rhsVftablePtr); + } + + // + // Fail open if vftable is not in the CastGuard vftable range or the OS handler returned. + // + return; +} + +extern +inline +void __cdecl __castguard_check_failure_user_handled(PVOID rhsVftablePtr) +{ + if (__castguard_compat_check(rhsVftablePtr)) + { + __castguard_check_failure_user_handled_wrapper(rhsVftablePtr); + } + + // + // Fail open if vftable is not in the CastGuard vftable range or the user handler returned. + // + return; +} + +static +inline +BOOL +__cdecl __castguard_slow_path_compat_check(PVOID rhsVftablePtr, SIZE_T compareVftableOffset, SIZE_T maxIndex) +{ + ULONG_PTR realVftableRangeStart = (ULONG_PTR)&__CastGuardVftablesStart + sizeof(struct CastGuardVftables); + ULONG_PTR compareBase = realVftableRangeStart + compareVftableOffset; + + return ((ULONG_PTR)rhsVftablePtr - compareBase) > maxIndex; +} + +extern +inline +void __cdecl __castguard_slow_path_check_debugbreak(PVOID rhsVftablePtr, SIZE_T compareVftableOffset, SIZE_T maxIndex) +{ + if (__castguard_slow_path_compat_check(rhsVftablePtr, compareVftableOffset, maxIndex) && __castguard_compat_check(rhsVftablePtr)) { + __debugbreak(); + } + + // + // Fail open if vftable is not in the CastGuard vftable range. + // + return; +} + +extern +inline +void __cdecl __castguard_slow_path_check_fastfail(PVOID rhsVftablePtr, SIZE_T compareVftableOffset, SIZE_T maxIndex) +{ + if (__castguard_slow_path_compat_check(rhsVftablePtr, compareVftableOffset, maxIndex) && __castguard_compat_check(rhsVftablePtr)) { + __fastfail(FAST_FAIL_CAST_GUARD); + } + + // + // Fail open if vftable is not in the CastGuard vftable range. + // + return; +} + +extern +inline +void __cdecl __castguard_slow_path_check_nop(PVOID rhsVftablePtr, SIZE_T compareVftableOffset, SIZE_T maxIndex) +{ + UNREFERENCED_PARAMETER(rhsVftablePtr); + UNREFERENCED_PARAMETER(compareVftableOffset); + UNREFERENCED_PARAMETER(maxIndex); + // + // Don't bother with the compat check, we'll do nothing either way. + // + return; +} + +extern +inline +void __cdecl __castguard_slow_path_check_os_handled(PVOID rhsVftablePtr, SIZE_T compareVftableOffset, SIZE_T maxIndex) +{ + if (__castguard_slow_path_compat_check(rhsVftablePtr, compareVftableOffset, maxIndex) && + __castguard_compat_check(rhsVftablePtr)) + { + __castguard_check_failure_os_handled_wrapper(rhsVftablePtr); + } + + // + // Fail open if vftable is not in the CastGuard vftable range or the OS handler returned. + // + return; +} + +extern +inline +void __cdecl __castguard_slow_path_check_user_handled(PVOID rhsVftablePtr, SIZE_T compareVftableOffset, SIZE_T maxIndex) +{ + if (__castguard_slow_path_compat_check(rhsVftablePtr, compareVftableOffset, maxIndex) && + __castguard_compat_check(rhsVftablePtr)) + { + __castguard_check_failure_user_handled_wrapper(rhsVftablePtr); + } + + // + // Fail open if vftable is not in the CastGuard vftable range or the user handler returned. + // + return; +} \ No newline at end of file diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/huge.c b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/huge.c new file mode 100644 index 0000000000000000000000000000000000000000..d5d15a8873a237ed2e73406b3133287a14dd1f41 --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/huge.c @@ -0,0 +1,7 @@ +// +// huge.c +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// + +extern unsigned int const _HUGE[2] = { 0x00000000, 0x7ff00000 }; diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/initialization.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/initialization.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f30bffecb7189672c6b606a4dd817c4afd214114 --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/initialization.cpp @@ -0,0 +1,168 @@ +// +// initialization.cpp +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// This file defines the main initialization and uninitialization routines for +// the VCRuntime, shared by both the static and dynamic VCRuntime libraries. In +// the dynamic VCRuntime library, these are called by DllMain. In the static +// VCRuntime library, these are called by the initialization code. +// +#include + +extern "C" { + +#if !defined(_CRT_WINDOWS) + +#if defined(_M_ARM) +#define INIT_STRING_FUNCTIONS 1 + + // These functions are used to set the default behaviour of memcpy operations + // on ARM. If an external cache is available, memcpy() uses the *_integer + // functions. Otherwise, memcpy() will keep the defaults, which are the + // *_neon functions. + typedef void * _memcpy_t(void *, const void *, size_t); + + extern _memcpy_t * __memcpy_forward_large_func; + extern _memcpy_t * __memcpy_reverse_large_func; + extern _memcpy_t __memcpy_forward_large_integer; + extern _memcpy_t __memcpy_reverse_large_integer; + + // Update memcpy function pointers: + static void __cdecl init_string_functions() + { + if (IsProcessorFeaturePresent(PF_ARM_EXTERNAL_CACHE_AVAILABLE)) + { + /* + * Set memcpy() to use the integer functions; overriding + * the defaults, which are the NEON functions. + */ + __memcpy_forward_large_func = &__memcpy_forward_large_integer; + __memcpy_reverse_large_func = &__memcpy_reverse_large_integer; + } + } + +#elif (defined(_M_ARM64) || defined(_M_ARM64EC) || defined(_M_HYBRID_X86_ARM64)) && \ + !defined(_CRT_APP) && !defined(_CRT_ONECORE) && !defined(_CRT_ENCLAVE) + +#define INIT_STRING_FUNCTIONS 1 + + int __arm64_safe_unaligned_memory_access; + + static + VERSIONHELPERAPI + __IsWindowsVersionOrGreaterEx(WORD wMajorVersion, WORD wMinorVersion, WORD wServicePackMajor, WORD wBuildNumber) + { + OSVERSIONINFOEXW osvi = { sizeof(osvi) }; + DWORDLONG const dwlConditionMask = VerSetConditionMask( + VerSetConditionMask( + VerSetConditionMask( + VerSetConditionMask( + 0, VER_MAJORVERSION, VER_GREATER_EQUAL), + VER_MINORVERSION, VER_GREATER_EQUAL), + VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL), + VER_BUILDNUMBER, VER_GREATER_EQUAL); + + osvi.dwMajorVersion = wMajorVersion; + osvi.dwMinorVersion = wMinorVersion; + osvi.wServicePackMajor = wServicePackMajor; + osvi.dwBuildNumber = wBuildNumber; + + return VerifyVersionInfoW(&osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_SERVICEPACKMAJOR | VER_BUILDNUMBER, dwlConditionMask) != FALSE; + } + + static + VERSIONHELPERAPI + __IsWindows1122H2OrGreater() + { + const WORD WIN11_22H2_BUILD_NUM = 22621; + return __IsWindowsVersionOrGreaterEx(HIBYTE(_WIN32_WINNT_WINTHRESHOLD), LOBYTE(_WIN32_WINNT_WINTHRESHOLD), 0, WIN11_22H2_BUILD_NUM); + } + + static void __cdecl init_string_functions() + { + if (__IsWindows1122H2OrGreater()) + { + __arm64_safe_unaligned_memory_access = 1; + } + } + +#endif +#endif + +#if !defined(INIT_STRING_FUNCTIONS) + + static void __cdecl init_string_functions() + { + // No-op on non-ARM platforms + } + +#endif + + + +bool __cdecl __vcrt_initialize() +{ + #if defined CRTDLL + __isa_available_init(); + #endif + + init_string_functions(); + + if (!__vcrt_initialize_locks()) + { + return false; + } + + if (!__vcrt_initialize_ptd()) + { + __vcrt_uninitialize_locks(); + return false; + } + + return true; +} + +bool __cdecl __vcrt_uninitialize(_In_ bool const terminating) +{ + UNREFERENCED_PARAMETER(terminating); + + // If the process is terminating, there's no point in cleaning up, except + // in debug builds. + #ifndef _DEBUG + if (!terminating) + #endif + { + __vcrt_uninitialize_ptd(); + __vcrt_uninitialize_locks(); + } + + return true; +} + +bool __cdecl __vcrt_uninitialize_critical() +{ + __vcrt_uninitialize_ptd(); + + return true; +} + +bool __cdecl __vcrt_thread_attach() +{ + // Create a per-thread data structure for this thread (getptd will attempt + // to create a new per-thread data structure if one does not already exist + // for this thread): + if (__vcrt_getptd_noexit() == nullptr) + return false; + + return true; +} + +bool __cdecl __vcrt_thread_detach() +{ + // Free the per-thread data structure for this thread: + __vcrt_freeptd_for_this_thread(); + return true; +} + +} diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/initializers.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/initializers.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e56cb452969cb52063c63ab95c0707b2ed64436f --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/initializers.cpp @@ -0,0 +1,139 @@ +// +// initializers.cpp +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// Data used in C and C++ initialization and termination. Because this object +// is linked into every module that uses the CRT, we also use this module to +// pass flags to the linker to link with libraries upon which the CRT depends. +// +#include +#include + + + +extern "C" _CRTALLOC(".CRT$XIA") _PIFV __xi_a[] = { nullptr }; // C initializers (first) +extern "C" _CRTALLOC(".CRT$XIZ") _PIFV __xi_z[] = { nullptr }; // C initializers (last) +extern "C" _CRTALLOC(".CRT$XCA") _PVFV __xc_a[] = { nullptr }; // C++ initializers (first) +extern "C" _CRTALLOC(".CRT$XCZ") _PVFV __xc_z[] = { nullptr }; // C++ initializers (last) +extern "C" _CRTALLOC(".CRT$XPA") _PVFV __xp_a[] = { nullptr }; // C pre-terminators (first) +extern "C" _CRTALLOC(".CRT$XPZ") _PVFV __xp_z[] = { nullptr }; // C pre-terminators (last) +extern "C" _CRTALLOC(".CRT$XTA") _PVFV __xt_a[] = { nullptr }; // C terminators (first) +extern "C" _CRTALLOC(".CRT$XTZ") _PVFV __xt_z[] = { nullptr }; // C terminators (last) + +#pragma comment(linker, "/merge:.CRT=.rdata") + + + +// When we link statically to the Universal CRT and the VCRuntime, we have to use +// these functions to initialize and terminate the statically-linked CRT code. +// When we link to the Universal CRT DLL or the VCRuntime DLL, these functions do +// not exist (they are internal implementation details of their respective DLLs +// and they are not exported, so the symbols simply do not exist). +// +// In order to support linking with both the static libraries and the DLLs, we +// provide stub alternatives for each of these functions. When we link statically +// to the Universal CRT and the VCRuntime, we'll get the real definitions. When +// we link to the DLLs, the linker will fail to find the real definitions and +// will instead use these alternative stubs. +_VCRT_DECLARE_ALTERNATE_NAME(__acrt_initialize, __scrt_stub_for_acrt_initialize ) +_VCRT_DECLARE_ALTERNATE_NAME(__acrt_uninitialize, __scrt_stub_for_acrt_uninitialize ) +_VCRT_DECLARE_ALTERNATE_NAME(__acrt_uninitialize_critical, __scrt_stub_for_acrt_uninitialize_critical) +_VCRT_DECLARE_ALTERNATE_NAME(__acrt_thread_attach, __scrt_stub_for_acrt_thread_attach ) +_VCRT_DECLARE_ALTERNATE_NAME(__acrt_thread_detach, __scrt_stub_for_acrt_thread_detach ) +_VCRT_DECLARE_ALTERNATE_NAME(_is_c_termination_complete, __scrt_stub_for_is_c_termination_complete ) + +_VCRT_DECLARE_ALTERNATE_NAME(__vcrt_initialize, __scrt_stub_for_acrt_initialize ) +_VCRT_DECLARE_ALTERNATE_NAME(__vcrt_uninitialize, __scrt_stub_for_acrt_uninitialize ) +_VCRT_DECLARE_ALTERNATE_NAME(__vcrt_uninitialize_critical, __scrt_stub_for_acrt_uninitialize_critical) +_VCRT_DECLARE_ALTERNATE_NAME(__vcrt_thread_attach, __scrt_stub_for_acrt_thread_attach ) +_VCRT_DECLARE_ALTERNATE_NAME(__vcrt_thread_detach, __scrt_stub_for_acrt_thread_detach ) + + + +#if defined _CRT_APP + // Link no platform libraries by default for Windows Store +#elif defined _ONECORE + // Link with the APISet umbrella library for OneCore + #pragma comment(linker, "/defaultlib:onecore.lib") +#else + // Link with the legacy kernel32.lib for the "normal" libraries + #pragma comment(linker, "/defaultlib:kernel32.lib") + #if _VCRT_WIN32_WINNT >= _WIN32_WINNT_WIN8 + // Also link with the WinRT library when building for Windows 8 and above + #pragma comment(linker, "/defaultlib:runtimeobject.lib") + #endif +#endif + + + + +// Generate /defaultlib and /disallowlib options to drag the other parts of the +// CRT (the VCRuntime and the Universal CRT) into the link and prevent mismatching +// libraries from being linked. +#define EXPAND_LINKER_OPTION_MD(...) __VA_ARGS__ +#define EXPAND_LINKER_OPTION_XMD(...) __VA_ARGS__ +#define EXPAND_LINKER_OPTION_MT(...) __VA_ARGS__ +#define EXPAND_LINKER_OPTION_XMT(...) __VA_ARGS__ + +#define LINKER_OPTION_MD "/disallowlib" +#define LINKER_OPTION_XMD "/disallowlib" +#define LINKER_OPTION_MT "/disallowlib" +#define LINKER_OPTION_XMT "/disallowlib" + +#ifdef CRTDLL + #ifdef _DEBUG + #undef LINKER_OPTION_XMD + #define LINKER_OPTION_XMD "/defaultlib" + #else + #undef LINKER_OPTION_MD + #define LINKER_OPTION_MD "/defaultlib" + #endif +#else // ^^^ CRTDLL ^^^ // vvv !CRTDLL vvv // + #ifdef _DEBUG + #undef LINKER_OPTION_XMT + #define LINKER_OPTION_XMT "/defaultlib" + #else + #undef LINKER_OPTION_MT + #define LINKER_OPTION_MT "/defaultlib" + #endif +#endif // !CRTDLL + +#ifdef _MSVCRT_WINDOWS + // In all cases where the Windows libraries are used, /nodefaultlib is + // also used, so suppress pragma generation for the Windows libraries. + #define GENERATE_LINKER_OPTION(model, library) +#else + #define GENERATE_LINKER_OPTION(model, library) \ + _CRT_CONCATENATE(EXPAND_LINKER_OPTION_, model)( \ + __pragma(comment(linker, _CRT_CONCATENATE(LINKER_OPTION_, model) ":" library)) \ + ) +#endif + +GENERATE_LINKER_OPTION(MD, "msvcrt.lib" ) +GENERATE_LINKER_OPTION(XMD, "msvcrtd.lib") +GENERATE_LINKER_OPTION(MT, "libcmt.lib" ) +GENERATE_LINKER_OPTION(XMT, "libcmtd.lib") + +GENERATE_LINKER_OPTION(MD, "vcruntime.lib" ) +GENERATE_LINKER_OPTION(XMD, "vcruntimed.lib" ) +GENERATE_LINKER_OPTION(MT, "libvcruntime.lib" ) +GENERATE_LINKER_OPTION(XMT, "libvcruntimed.lib") + +// Suppress /disallowlib directives to allow use of both the static and DLL +// Universal CRT with the static Visual C++ libraries (we still prohibit mixing +// and matching of any debug libraries with any retail libraries). +#ifndef CRTDLL + #ifdef _DEBUG + #undef EXPAND_LINKER_OPTION_XMD + #define EXPAND_LINKER_OPTION_XMD(...) + #else + #undef EXPAND_LINKER_OPTION_MD + #define EXPAND_LINKER_OPTION_MD(...) + #endif +#endif + +GENERATE_LINKER_OPTION(MD, "ucrt.lib" ) +GENERATE_LINKER_OPTION(XMD, "ucrtd.lib" ) +GENERATE_LINKER_OPTION(MT, "libucrt.lib" ) +GENERATE_LINKER_OPTION(XMT, "libucrtd.lib") diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/internal_shared.h b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/internal_shared.h new file mode 100644 index 0000000000000000000000000000000000000000..aeb0fa0b8714e4c3e6240209e3953375039a0b38 --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/internal_shared.h @@ -0,0 +1,778 @@ +// +// internal_shared.h +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// Header-only utilities used by both the VCRuntime and the CoreCRT. +// +#pragma once + +#include +#include +#include +#include +#include +#include + +_CRT_BEGIN_C_HEADER + + + +extern IMAGE_DOS_HEADER __ImageBase; + + + +//-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +// +// Preprocessor Utilities and Awesome Macros +// +//-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +// Attributes for managed declarations in the CRT +#ifdef _M_CEE + #define _CRT_INTEROPSERVICES_DLLIMPORT(_DllName , _EntryPoint , _CallingConvention) \ + [System::Runtime::InteropServices::DllImport( \ + _DllName , EntryPoint = _EntryPoint, CallingConvention = _CallingConvention)] + #define _CRT_SUPPRESS_UNMANAGED_CODE_SECURITY [System::Security::SuppressUnmanagedCodeSecurity] + #define _CRT_CALLING_CONVENTION_CDECL System::Runtime::InteropServices::CallingConvention::Cdecl + #define _CRT_CALLING_CONVENTION_WINAPI System::Runtime::InteropServices::CallingConvention::Winapi + #define _CRT_RELIABILITY_CONTRACT \ + [System::Runtime::ConstrainedExecution::ReliabilityContract( \ + System::Runtime::ConstrainedExecution::Consistency::WillNotCorruptState, \ + System::Runtime::ConstrainedExecution::Cer::Success)] + #define _CRT_ASSERT_UNMANAGED_CODE_ATTRIBUTE \ + [System::Security::Permissions::SecurityPermissionAttribute( \ + System::Security::Permissions::SecurityAction::Assert, UnmanagedCode = true)] + #define _CRT_SECURITYCRITICAL_ATTRIBUTE [System::Security::SecurityCritical] + #define _CRT_SECURITYSAFECRITICAL_ATTRIBUTE [System::Security::SecuritySafeCritical] +#else + #define _CRT_INTEROPSERVICES_DLLIMPORT(_DllName , _EntryPoint , _CallingConvention) + #define _CRT_SUPPRESS_UNMANAGED_CODE_SECURITY + #define _CRT_CALLING_CONVENTION_CDECL + #define _CRT_CALLING_CONVENTION_WINAPI + #define _CRT_RELIABILITY_CONTRACT + #define _CRT_ASSERT_UNMANAGED_CODE_ATTRIBUTE + #define _CRT_SECURITYCRITICAL_ATTRIBUTE + #define _CRT_SECURITYSAFECRITICAL_ATTRIBUTE +#endif + + + +// The pointer-width interlocked exchange and compare-exchange operations are +// not defined for x86. We declare them ourselves so that we can use the same +// macros consistently across all architectures: +#ifdef _M_IX86 + + #undef _InterlockedExchangePointer + #undef _InterlockedCompareExchangePointer + + #define _InterlockedExchangePointer(target, value) \ + ((void*)_InterlockedExchange((long volatile*)(target), (long)(value))) + + #define _InterlockedCompareExchangePointer(target, exchange, comparand) \ + ((void*)_InterlockedCompareExchange((long volatile*)(target), (long)(exchange), (long)(comparand))) + +#endif + + + +#define _BEGIN_SECURE_CRT_DEPRECATION_DISABLE \ + __pragma(warning(push)) \ + __pragma(warning(disable:4996)) \ + __pragma(warning(disable:25025)) \ + __pragma(warning(disable:28719)) + +#define _END_SECURE_CRT_DEPRECATION_DISABLE \ + __pragma(warning(pop)) + + + +#define CRT_WARNING_DISABLE_PUSH(x,y) \ + __pragma(warning(push)) \ + __pragma(warning(disable: x)) + +#define CRT_WARNING_POP \ + __pragma(warning(pop)) + + + +//-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +// +// Section Attributes +// +//-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +#pragma section(".CRT$XCA", long, read) // First C++ Initializer +#pragma section(".CRT$XCAA", long, read) // Startup C++ Initializer +#pragma section(".CRT$XCZ", long, read) // Last C++ Initializer + +#pragma section(".CRT$XDA", long, read) // First Dynamic TLS Initializer +#pragma section(".CRT$XDZ", long, read) // Last Dynamic TLS Initializer + +#pragma section(".CRT$XIA", long, read) // First C Initializer +#pragma section(".CRT$XIAA", long, read) // Startup C Initializer +#pragma section(".CRT$XIAB", long, read) // PGO C Initializer +#pragma section(".CRT$XIAC", long, read) // Post-PGO C Initializer +#pragma section(".CRT$XIC", long, read) // CRT C Initializers +#pragma section(".CRT$XIYA", long, read) // VCCorLib Threading Model Initializer +#pragma section(".CRT$XIYAA", long, read) // XAML Designer Threading Model Override Initializer +#pragma section(".CRT$XIYB", long, read) // VCCorLib Main Initializer +#pragma section(".CRT$XIZ", long, read) // Last C Initializer + +#pragma section(".CRT$XLA", long, read) // First Loader TLS Callback +#pragma section(".CRT$XLC", long, read) // CRT TLS Constructor +#pragma section(".CRT$XLD", long, read) // CRT TLS Terminator +#pragma section(".CRT$XLZ", long, read) // Last Loader TLS Callback + +#pragma section(".CRT$XPA", long, read) // First Pre-Terminator +#pragma section(".CRT$XPB", long, read) // CRT ConcRT Pre-Terminator +#pragma section(".CRT$XPX", long, read) // CRT Pre-Terminators +#pragma section(".CRT$XPXA", long, read) // CRT stdio Pre-Terminator +#pragma section(".CRT$XPZ", long, read) // Last Pre-Terminator + +#pragma section(".CRT$XTA", long, read) // First Terminator +#pragma section(".CRT$XTZ", long, read) // Last Terminator + +#pragma section(".CRTMA$XCA", long, read) // First Managed C++ Initializer +#pragma section(".CRTMA$XCZ", long, read) // Last Managed C++ Initializer + +#pragma section(".CRTVT$XCA", long, read) // First Managed VTable Initializer +#pragma section(".CRTVT$XCZ", long, read) // Last Managed VTable Initializer + +#pragma section(".rdata$T", long, read) + +#pragma section(".rtc$IAA", long, read) // First RTC Initializer +#pragma section(".rtc$IZZ", long, read) // Last RTC Initializer + +#pragma section(".rtc$TAA", long, read) // First RTC Terminator +#pragma section(".rtc$TZZ", long, read) // Last RTC Terminator + +#define _CRTALLOC(x) __declspec(allocate(x)) + + + +//-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +// +// "Special" Data +// +//-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +#ifndef _M_CEE + typedef void (__cdecl* _PVFV)(void); + typedef int (__cdecl* _PIFV)(void); + + extern _CRTALLOC(".CRT$XIA") _PIFV __xi_a[]; // First C Initializer + extern _CRTALLOC(".CRT$XIZ") _PIFV __xi_z[]; // Last C Initializer + extern _CRTALLOC(".CRT$XCA") _PVFV __xc_a[]; // First C++ Initializer + extern _CRTALLOC(".CRT$XCZ") _PVFV __xc_z[]; // Last C++ Initializer + extern _CRTALLOC(".CRT$XPA") _PVFV __xp_a[]; // First Pre-Terminator + extern _CRTALLOC(".CRT$XPZ") _PVFV __xp_z[]; // Last Pre-Terminator + extern _CRTALLOC(".CRT$XTA") _PVFV __xt_a[]; // First Terminator + extern _CRTALLOC(".CRT$XTZ") _PVFV __xt_z[]; // Last Terminator +#endif + + + +//-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +// +// SEH Encapsulation +// +//-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +// Whenever we acquire locks in the CRT, we use SEH __try/__finally blocks to +// ensure that we release the lock under all circumstances, even if an unwind +// operation unwinds through the CRT frames. (Unexpected unwinding through the +// CRT is not a supported scenario, but we protect ourselves against this +// possibility anyway as a matter of policy.) +// +// These wrappers make it easier to mix SEH handling with RAII types in the CRT. +// The 'action' is called under a __try, and the 'cleanup' executes in the +// __finally block. Note that we expect the return type of the 'action callable +// to be either 'void' or some trivial type. At a minimum, the type must be +// value initializable. +#ifdef __cplusplus +extern "C++" +{ + template + struct __crt_seh_guarded_call + { + template + auto operator()(Setup&& setup, Action&& action, Cleanup&& cleanup) + -> decltype(action()) + { + decltype(action()) result{}; + + setup(); + __try + { + result = action(); + } + __finally + { + cleanup(); + } + + return result; + } + }; + + template <> + struct __crt_seh_guarded_call + { + template + void operator()(Setup&& setup, Action&& action, Cleanup&& cleanup) + { + setup(); + __try + { + action(); + } + __finally + { + cleanup(); + } + } + }; + + template + auto __crt_call_and_cleanup(Action&& action, Cleanup&& cleanup) + -> decltype(action()) + { + return __crt_seh_guarded_call()([](){}, action, cleanup); + } +} +#endif // __cplusplus + + + +//-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +// +// CRT Memory Allocation and Management +// +//-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +#ifdef _DEBUG + + // These must match the definitions in the CoreCRT's debug header. They + // are defined separately here to avoid unwanted CRT header dependencies. + #define _NORMAL_BLOCK 1 + #define _CRT_BLOCK 2 + + #define _calloc_crt(c, s) (_calloc_dbg ( c, s, _CRT_BLOCK, __FILE__, __LINE__)) + #define _free_crt(p) (_free_dbg (p, _CRT_BLOCK )) + #define _malloc_crt(s) (_malloc_dbg ( s, _CRT_BLOCK, __FILE__, __LINE__)) + #define _msize_crt(p) (_msize_dbg (p, _CRT_BLOCK )) + #define _recalloc_crt(p, c, s) (_recalloc_dbg(p, c, s, _CRT_BLOCK, __FILE__, __LINE__)) + #define _realloc_crt(p, s) (_realloc_dbg (p, s, _CRT_BLOCK, __FILE__, __LINE__)) + + // C6386: see below + #define _malloca_crt(size) \ + __pragma(warning(suppress: 6255 6386)) \ + (_MallocaComputeSize(size) != 0 \ + ? _MarkAllocaS(_malloc_crt(_MallocaComputeSize(size)), _ALLOCA_S_HEAP_MARKER) \ + : NULL) + +#else // ^^^ _DEBUG ^^^ // vvv !_DEBUG vvv + + // The *_crt macros call the allocation function that vcruntime should use for + // internal allocations. It changes based off of where it is being built. + + #ifdef _CRT_WINDOWS + // When building for the UCRT, we want to use the internal allocation functions. + // We need to ensure that users hooking the public allocation functions do not + // interfere with the UCRT's allocations. + #define _calloc_crt _calloc_base + #define _free_crt _free_base + #define _malloc_crt _malloc_base + #define _realloc_crt _realloc_base + #define _msize_crt _msize_base + #define _recalloc_crt _recalloc_base + #else + // When building for vcruntime*.dll, we are not a part of the UCRT or OS so we + // should use the public allocation functions exported by the UCRT. + #define _calloc_crt calloc + #define _free_crt free + #define _malloc_crt malloc + #define _realloc_crt realloc + #define _msize_crt _msize + #define _recalloc_crt _recalloc + #endif + + // C6386 is suppressed because __crt_typefix(unsigned int*) annotation on + // _MarkAllocaS denotes that an unsigned int must fit at the returned value + // after it is adjusted for the alloca marker, but it is permitted to + // _malloca / _malloca_crt an array with a type smaller than unsigned int. + #define _malloca_crt(size) \ + __pragma(warning(suppress: 6255 6386)) \ + (_MallocaComputeSize(size) != 0 \ + ? ((_MallocaComputeSize(size) <= _ALLOCA_S_THRESHOLD) \ + ? _MarkAllocaS(_alloca(_MallocaComputeSize(size)), _ALLOCA_S_STACK_MARKER) \ + : _MarkAllocaS(_malloc_crt(_MallocaComputeSize(size)), _ALLOCA_S_HEAP_MARKER)) \ + : NULL) + +#endif // !_DEBUG + +#pragma warning(push) +#pragma warning(disable: 6014) +__inline void __CRTDECL _freea_crt(_Pre_maybenull_ _Post_invalid_ void* memory) +{ + if (memory) + { + unsigned int marker; + + memory = (char*)memory - _ALLOCA_S_MARKER_SIZE; + marker = *(unsigned int*)memory; + if (marker == _ALLOCA_S_HEAP_MARKER) + { + _free_crt(memory); + } + else if (marker != _ALLOCA_S_STACK_MARKER) + { + _ASSERTE(("Corrupted pointer passed to _freea", 0)); + } + } +} +#pragma warning(pop) + +#ifdef __cplusplus +extern "C++" { + + struct __crt_internal_free_policy + { + template + void operator()(T const* const p) const noexcept + { + _free_crt(const_cast(p)); + } + }; + + struct __crt_public_free_policy + { + template + void operator()(T const* const p) const noexcept + { + free(const_cast(p)); + } + }; + + template + class __crt_unique_heap_ptr + { + public: + + explicit __crt_unique_heap_ptr(T* const p = nullptr) noexcept + : _p(p) + { + } + + __crt_unique_heap_ptr(__crt_unique_heap_ptr const&) = delete; + __crt_unique_heap_ptr& operator=(__crt_unique_heap_ptr const&) = delete; + + __crt_unique_heap_ptr(__crt_unique_heap_ptr&& other) noexcept + : _p(other._p) + { + other._p = nullptr; + } + + ~__crt_unique_heap_ptr() noexcept + { + release(); + } + + __crt_unique_heap_ptr& operator=(__crt_unique_heap_ptr&& other) noexcept + { + release(); + _p = other._p; + other._p = nullptr; + return *this; + } + + T* detach() noexcept + { + T* const local_p{_p}; + _p = nullptr; + return local_p; + } + + void attach(T* const p) noexcept + { + release(); + _p = p; + } + + void release() noexcept + { + Free()(_p); + _p = nullptr; + } + + bool is_valid() const noexcept + { + return _p != nullptr; + } + + explicit operator bool() const noexcept + { + return is_valid(); + } + + T* get() const noexcept + { + return _p; + } + + T** get_address_of() noexcept + { + return &_p; + } + + T** release_and_get_address_of() noexcept + { + release(); + return &_p; + } + + private: + T* _p; + }; + + // An internal-use scoped smart pointer for memory allocated by _malloca_crt. + template + struct __crt_scoped_stack_ptr_tag + { + __crt_scoped_stack_ptr_tag(T* const p) noexcept + : _p(p) + { + } + + T* _p; + }; + + template + class __crt_scoped_stack_ptr + { + public: + + explicit __crt_scoped_stack_ptr(__crt_scoped_stack_ptr_tag const p) noexcept + : _p(p._p) + { + } + + __crt_scoped_stack_ptr(__crt_scoped_stack_ptr const&) = delete; + __crt_scoped_stack_ptr& operator=(__crt_scoped_stack_ptr const&) = delete; + + ~__crt_scoped_stack_ptr() noexcept + { + _freea_crt(_p); + } + + T* get() const noexcept { return _p; } + + // Note that we do not provide a release() because one would not be + // useful: a stack allocation is only useful in the scope in which it + // was allocated. + + explicit operator bool() const noexcept + { + return _p != nullptr; + } + + private: + T* const _p; + }; + + // Note that no overflow checks are necessary for the multiplications here, + // because each multiplication operation is an argument to a parameter that + // is decorated __declspec(guard(overflow)). + #define _calloc_crt_t(t, n) (__crt_unique_heap_ptr (static_cast(_calloc_crt ( (n), sizeof(t))))) + #define _malloc_crt_t(t, n) (__crt_unique_heap_ptr (static_cast(_malloc_crt ( (n) * sizeof(t))))) + #define _recalloc_crt_t(t, p, n) (__crt_unique_heap_ptr (static_cast(_recalloc_crt((p), (n), sizeof(t))))) + #define _malloca_crt_t(t, n) (__crt_scoped_stack_ptr_tag(static_cast(_malloca_crt ( (n) * sizeof(t))))) + + + + enum : int + { + __crt_maximum_pointer_shift = sizeof(uintptr_t) * 8 + }; + + inline unsigned int __crt_rotate_pointer_value(unsigned int const value, + int const shift) noexcept + { + return RotateRight32(value, shift); + } + + inline unsigned __int64 __crt_rotate_pointer_value(unsigned __int64 const value, + int const shift) noexcept + { + return RotateRight64(value, shift); + } + + // Fast alternatives to the encode/decode pointer functions that do not use + // the EncodePointer and DecodePointer functions. + template + T __crt_fast_decode_pointer(T const p) noexcept + { + return reinterpret_cast( + __crt_rotate_pointer_value( + reinterpret_cast(p) ^ __security_cookie, + __security_cookie % __crt_maximum_pointer_shift + ) + ); + } + + template + T __crt_fast_encode_pointer(T const p) noexcept + { + return reinterpret_cast( + __crt_rotate_pointer_value( + reinterpret_cast(p), + __crt_maximum_pointer_shift - (__security_cookie % __crt_maximum_pointer_shift) + ) ^ __security_cookie + ); + } + + // The primary __crt_fast_encode_pointer template does not work properly + // when it is called with the argument 'nullptr' because the encoded void* + // pointer is casted back to nullptr_t, and nullptr_t can only represent a + // single value: the real, unencoded null pointer. Therefore, we overload + // the function for nullptr_t, and defer the cast until we know the actual + // type that we need. + struct __crt_fast_encoded_nullptr_t + { + template + operator T*() const noexcept + { + return __crt_fast_encode_pointer(static_cast(nullptr)); + } + }; + + inline __crt_fast_encoded_nullptr_t __crt_fast_encode_pointer(decltype(nullptr)) noexcept + { + return __crt_fast_encoded_nullptr_t(); + } + + + + template + T __crt_get_proc_address(HMODULE const m, char const* const f) noexcept + { + return reinterpret_cast(::GetProcAddress(m, f)); + } + + template + T* __crt_interlocked_exchange_pointer(T* const volatile* target, V const value) noexcept + { + // This is required to silence a spurious unreferenced formal parameter + // warning. + UNREFERENCED_PARAMETER(value); + + return reinterpret_cast(_InterlockedExchangePointer((void**)target, (void*)value)); + } + + template + T __crt_interlocked_compare_exchange(T* const target, E const exchange, + C const comparand) noexcept + { + UNREFERENCED_PARAMETER(exchange); // These are required to silence spurious + UNREFERENCED_PARAMETER(comparand); // unreferenced formal parameter warnings. + + static_assert(sizeof(T) == sizeof(LONG), "Type being compared must be same size as a LONG."); + return static_cast(_InterlockedCompareExchange( + reinterpret_cast(target), (LONG)exchange, (LONG)comparand)); + } + + template + T* __crt_interlocked_compare_exchange_pointer(T* const volatile* target, E const exchange, + C const comparand) noexcept + { + UNREFERENCED_PARAMETER(exchange); // These are required to silence spurious + UNREFERENCED_PARAMETER(comparand); // unreferenced formal parameter warnings. + + return reinterpret_cast(_InterlockedCompareExchangePointer( + (void**)target, (void*)exchange, (void*)comparand)); + } + + #ifndef _M_CEE_PURE + + #if defined _M_ARM + #define __crt_interlocked_memory_barrier() (__dmb(_ARM_BARRIER_ISH)) + #elif defined _M_ARM64 + #define __crt_interlocked_memory_barrier() (__dmb(_ARM64_BARRIER_ISH)) + #endif + + inline __int32 __crt_interlocked_read_32(__int32 const volatile* target) noexcept + { + #if defined _M_ARM64 || defined _M_ARM64EC + __int32 const result = __load_acquire32(reinterpret_cast(target)); + return result; + #elif defined _M_IX86 || defined _M_X64 + __int32 const result = *target; + _ReadWriteBarrier(); + return result; + #elif defined _M_ARM + __int32 const result = __iso_volatile_load32(reinterpret_cast(target)); + __crt_interlocked_memory_barrier(); + return result; + #else + #error Unsupported architecture + #endif + } + + #if defined _WIN64 + inline __int64 __crt_interlocked_read_64(__int64 const volatile* target) noexcept + { + #if defined _M_ARM64 || defined _M_ARM64EC + __int64 const result = __load_acquire64(reinterpret_cast(target)); + return result; + #elif defined _M_X64 + __int64 const result = *target; + _ReadWriteBarrier(); + return result; + #else + #error Unsupported architecture + #endif + } + #endif // _WIN64 + + template + T __crt_interlocked_read(T const volatile* target) noexcept + { + static_assert(sizeof(T) == sizeof(__int32), "Type being read must be 32 bits in size."); + return (T)__crt_interlocked_read_32((__int32*)target); + } + + + template + T* __crt_interlocked_read_pointer(T* const volatile* target) noexcept + { + #ifdef _WIN64 + return (T*)__crt_interlocked_read_64((__int64*)target); + #else + return (T*)__crt_interlocked_read_32((__int32*)target); + #endif + } + + #endif // _M_CEE_PURE + +} // extern "C++" +#endif // __cplusplus + + + +#define _CRT_DEBUGGER_IGNORE -1 +#define _CRT_DEBUGGER_GSFAILURE 1 +#define _CRT_DEBUGGER_INVALIDPARAMETER 2 +#define _CRT_DEBUGGER_ABORT 3 + +// Note: These names are well-known to the debugger +#ifdef _M_IX86 + void __cdecl _crt_debugger_hook(int); + #define _CRT_DEBUGGER_HOOK _crt_debugger_hook +#else + void __cdecl __crt_debugger_hook(int); + #define _CRT_DEBUGGER_HOOK __crt_debugger_hook +#endif + + + +//-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +// +// Precondition Validation Macros +// +//-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +#ifdef _DEBUG + #define _INVALID_PARAMETER(expr) _invalid_parameter(expr, __FUNCTIONW__, __FILEW__, __LINE__, 0) +#else + #define _INVALID_PARAMETER(expr) _invalid_parameter_noinfo() +#endif + +#define _VALIDATE_CLEAR_OSSERR_RETURN(expr, errorcode, retexpr) \ + { \ + int _Expr_val=!!(expr); \ + _ASSERT_EXPR((_Expr_val), _CRT_WIDE(#expr)); \ + if (!(_Expr_val)) \ + { \ + _doserrno = 0L; \ + errno = errorcode; \ + _INVALID_PARAMETER(_CRT_WIDE(#expr)); \ + return retexpr; \ + } \ + } + +#define _VALIDATE_CLEAR_OSSERR_RETURN_ERRCODE(expr, errorcode) \ + { \ + int _Expr_val=!!(expr); \ + _ASSERT_EXPR((_Expr_val), _CRT_WIDE(#expr)); \ + if (!(_Expr_val)) \ + { \ + _doserrno = 0L; \ + errno = errorcode; \ + _INVALID_PARAMETER(_CRT_WIDE(#expr)); \ + return errorcode; \ + } \ + } + +#define _VALIDATE_RETURN(expr, errorcode, retexpr) \ + { \ + int _Expr_val=!!(expr); \ + _ASSERT_EXPR((_Expr_val), _CRT_WIDE(#expr)); \ + if (!(_Expr_val)) \ + { \ + errno = errorcode; \ + _INVALID_PARAMETER(_CRT_WIDE(#expr)); \ + return retexpr; \ + } \ + } + +#define _VALIDATE_RETURN_ERRCODE(expr, errorcode) \ + { \ + int _Expr_val=!!(expr); \ + _ASSERT_EXPR((_Expr_val), _CRT_WIDE(#expr)); \ + if (!(_Expr_val)) \ + { \ + errno = errorcode; \ + _INVALID_PARAMETER(_CRT_WIDE(#expr)); \ + return errorcode; \ + } \ + } + +#define _VALIDATE_RETURN_ERRCODE_NOEXC(expr, errorcode) \ + { \ + if (!(expr)) \ + { \ + errno = errorcode; \ + return errorcode; \ + } \ + } + +#define _VALIDATE_RETURN_NOERRNO(expr, retexpr) \ + { \ + int _Expr_val=!!(expr); \ + _ASSERT_EXPR((_Expr_val), _CRT_WIDE(#expr)); \ + if (!(_Expr_val)) \ + { \ + _INVALID_PARAMETER(_CRT_WIDE(#expr)); \ + return retexpr; \ + } \ + } + +#define _VALIDATE_RETURN_NOEXC(expr, errorcode, retexpr) \ + { \ + if (!(expr)) \ + { \ + errno = errorcode; \ + return retexpr; \ + } \ + } + +#define _VALIDATE_RETURN_VOID(expr, errorcode) \ + { \ + int _Expr_val=!!(expr); \ + _ASSERT_EXPR((_Expr_val), _CRT_WIDE(#expr)); \ + if (!(_Expr_val)) \ + { \ + errno = errorcode; \ + _INVALID_PARAMETER(_CRT_WIDE(#expr)); \ + return; \ + } \ + } + + + +_CRT_END_C_HEADER diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/invalid_parameter_handler.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/invalid_parameter_handler.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f99bdd34e7eed4d4fb33385b57fa5a22abfd8610 --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/invalid_parameter_handler.cpp @@ -0,0 +1,17 @@ +// +// invalid_parameter_handler.cpp +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// Initializes the invalid parameter to its default behavior, which terminates +// the process. This behavior is overridable at link-time by linking with one +// of the link options. +// +#include + + + +extern "C" void __CRTDECL _initialize_invalid_parameter_handler() +{ + // No-op +} diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/isa_availability.h b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/isa_availability.h new file mode 100644 index 0000000000000000000000000000000000000000..c42f640f8463355fd1a1de378b7e88c586f45fc2 --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/isa_availability.h @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +#ifndef __ISA_AVAILABILITY__H__ +#define __ISA_AVAILABILITY__H__ + +/* + * These are defines for the extern "__isa_available" defined in the CRT, + * which defines the latest instruction set available for use. The compiler + * backend reads this file to emit vector code for specific microarchitectures. + * + * Additional architectural features are defined for extern "__favor", + * these defines identify performance features that are enabled in the processor. + * The compiler backend can use these to enable processor specific optimizations. + */ + +enum ISA_AVAILABILITY +{ + __ISA_AVAILABLE_X86 = 0, + __ISA_AVAILABLE_SSE2 = 1, + __ISA_AVAILABLE_SSE42 = 2, + __ISA_AVAILABLE_AVX = 3, + __ISA_AVAILABLE_ENFSTRG = 4, + __ISA_AVAILABLE_AVX2 = 5, + __ISA_AVAILABLE_AVX512 = 6, + + __ISA_AVAILABLE_ARMNT = 0, // minimum Win8 ARM support (but w/o NEON) + __ISA_AVAILABLE_NEON = 1, // support for 128-bit NEON instructions + __ISA_AVAILABLE_NEON_ARM64 = 2,// support for 128-bit NEON instructions for ARM64. The distinction between ARM32 and + // ARM64 NEON is temporary. They may eventually be merged. +}; + +#if defined(_M_IX86) || defined(_M_X64) + +// Inverted ISA extension bits are defined by macros rather than enum so that types are correct +// The lowest byte has flags that should be especially useful for code that must run +// on legacy processors. +#define __IA_SUPPORT_VECTOR128 0x00000001 // Vector lengths up to 128 bits supported (SSE2 if __avx10_version = 0) +#define __IA_SUPPORT_VECTOR256 0x00000002 // Vector lengths up to 256 bits supported (AVX2 if __avx10_version = 0) +#define __IA_SUPPORT_VECTOR512 0x00000004 // Vector lengths up to 512 bits supported (AVX-512 if __avx10_version = 0) +#define __IA_SUPPORT_AVX10 0x00000008 // AVX10 support +#define __IA_SUPPORT_SSE42 0x00000010 // SSE4.2 support (scalar and 128-bit) +#define __IA_SUPPORT_SV128X 0x00000020 // AVX512 or AVX10.1 support (scalar and 128-bit) +#define __IA_SUPPORT_AVX10_2 0x00000040 // AVX10.2 128-bit support (scalar and 128-bit) +#define __IA_SUPPORT_APX 0x00000080 // APX support +#define __IA_SUPPORT_FP16 0x01000000 // FP16 support (scalar and vector) +#endif + +#if defined(_M_IX86) + +/* Defines for: "__favor" defined in the CRT */ +#define __FAVOR_ATOM 0 +#define __FAVOR_ENFSTRG 1 /* Enhanced Fast Strings rep movb/stob */ +/* #define reserved 2 */ + +#elif defined(_M_X64) + +/* Defines for: "__favor" defined in the CRT */ +#define __FAVOR_ATOM 0 +#define __FAVOR_ENFSTRG 1 /* Enhanced Fast Strings rep movb/stob */ +/* #define reserved 2 */ + +#endif + +#endif // __ISA_AVAILABILITY__H__ diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/jbcxrval.c b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/jbcxrval.c new file mode 100644 index 0000000000000000000000000000000000000000..0ea7f9b1927dbc414f66d924145590f2cdb871cf --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/jbcxrval.c @@ -0,0 +1,164 @@ +/*++ + +Copyright (c) Microsoft Corporation + +Module Name: + + jbcxrval.c + +Abstract: + + This module implements C support code for jump buffer and context record + validation. + +Environment: + + Kernel mode only. + +--*/ + +#include +#include + +#if !(defined(NTOS_KERNEL_RUNTIME) && defined(_AMD64_)) + +#include "../misc/cfg_support.inc" // To inline _guard_icall_checks_enforced() + +#if defined(_AMD64_) +#define JUMP_BUFFER_TO_STACK_POINTER(JumpBuffer) ((JumpBuffer)->Rsp) +#define JB_FRAME(jmpbuf) (((_JUMP_BUFFER*)jmpbuf)->Frame) + +#elif defined(_ARM_) +#define JUMP_BUFFER_TO_STACK_POINTER(JumpBuffer) ((JumpBuffer)->Sp) +#define JB_FRAME(jmpbuf) (((_JUMP_BUFFER*)jmpbuf)->Frame) + +#elif defined(_ARM64_) +#define JUMP_BUFFER_TO_STACK_POINTER(JumpBuffer) ((JumpBuffer)->Sp) +#define JB_FRAME(jmpbuf) (((_JUMP_BUFFER*)jmpbuf)->Frame) + +#elif defined(_X86_) +#define JUMP_BUFFER_TO_STACK_POINTER(JumpBuffer) ((JumpBuffer)->Esp) +#else +#error Unsupported architecture. +#endif + +#define CONTEXT_TO_STACK_POINTER(Context) JUMP_BUFFER_TO_STACK_POINTER(Context) + +void +__except_validate_context_record ( + _In_ PCONTEXT ContextRecord + ) + +/*++ + +Routine Description: + + This function validates a context record for exception handling support. + +Arguments: + + ContextRecord - Supplies a pointer to the context record to validate. + +Return Value: + + None. If the context record was not valid, a fast fail event is raised if + CFG was enforced. + +--*/ + +{ + PVOID StackPointer; + PNT_TIB Tib; + + // + // If guard ICall checks are enforced, then validate the stack extents of + // the context record and raise a fast fail exception if the extents are + // invalid. If checks are not enforced or the jump buffer was valid, then + // return. + // + if (_guard_icall_checks_enforced()) { + Tib = (PNT_TIB)NtCurrentTeb(); + + // + // HYB-TODO: Validate both chpe and guest context. + // + + StackPointer = (PVOID)CONTEXT_TO_STACK_POINTER(ContextRecord); + if ((StackPointer < Tib->StackLimit) || + (StackPointer > Tib->StackBase)) { + + __fastfail(FAST_FAIL_INVALID_SET_OF_CONTEXT); + } + } +} + +__forceinline +void +__except_validate_jump_buffer_common ( + _In_reads_(_JBLEN) jmp_buf JumpBuffer, + _In_ PVOID (*ExceptGetJbSpRoutine)(jmp_buf) + ) + +/*++ + +Routine Description: + + This function validates a jump buffer for exception handling support. + +Arguments: + + JumpBuffer - Supplies a pointer to the jump buffer to validate. + +Return Value: + + None. If the jump buffer was not valid, a fast fail event is raised if + CFG was enforced. + +--*/ + +{ + + PVOID StackPointer; + PNT_TIB Tib; + + // + // If guard ICall checks are enforced, then validate the stack extents of + // the jump buffer and raise a fast fail exception if the extents are + // invalid. If checks are not enforced or the jump buffer was valid, then + // return. + // + + if (_guard_icall_checks_enforced()) { + Tib = (PNT_TIB)NtCurrentTeb(); + StackPointer = ExceptGetJbSpRoutine(JumpBuffer); + + if ((StackPointer < Tib->StackLimit) || + (StackPointer > Tib->StackBase)) { + + __fastfail(FAST_FAIL_INVALID_SET_OF_CONTEXT); + } + +#if defined(JB_FRAME) + if (JB_FRAME(JumpBuffer) == 0) { + + __fastfail(FAST_FAIL_INVALID_SET_OF_CONTEXT); + } +#endif + } +} + +__forceinline +static PVOID __except_get_jumpbuf_sp(_In_reads_(_JBLEN) jmp_buf JumpBuffer) +{ + return (PVOID)JUMP_BUFFER_TO_STACK_POINTER((_JUMP_BUFFER*)JumpBuffer); +} + +void +__except_validate_jump_buffer ( + _In_reads_(_JBLEN) jmp_buf JumpBuffer + ) +{ + __except_validate_jump_buffer_common(JumpBuffer, __except_get_jumpbuf_sp); +} + +#endif diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/lconv_unsigned_char.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/lconv_unsigned_char.cpp new file mode 100644 index 0000000000000000000000000000000000000000..230c949422ca33780e7a2b77e015c7e893becc97 --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/lconv_unsigned_char.cpp @@ -0,0 +1,22 @@ +// +// lconv_unsigned_char_static.cpp +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// lconv initialization used to support an unsigned 'char' type (enabled by the +// -J flag during compilation). See lconv_unsigned_char_initialization.cpp for +// an explanation of how this works. +// +// Note: this file is linked statically into user binaries. +// +#include + +extern "C" { + + int __do_unsigned_char_lconv_initialization = 255; + + int __cdecl __initialize_lconv_for_unsigned_char(); + + _CRTALLOC(".CRT$XIC") static _PIFV pinit = __initialize_lconv_for_unsigned_char; + +} // extern "C" diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/loadcfg.c b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/loadcfg.c new file mode 100644 index 0000000000000000000000000000000000000000..cd727ce4f9737810e0c9f3f99cb80c7d738d16e0 --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/loadcfg.c @@ -0,0 +1,313 @@ +/*** +*loadcfg.c +* +* Copyright (c) Microsoft Corporation. All rights reserved. +* +*Purpose: +* Defines the default load config struct linked into images. +* +*******************************************************************************/ + +#include + +extern UINT_PTR __security_cookie; /* /GS security cookie */ +extern PVOID __guard_check_icall_fptr; +#if defined(_AMD64_) || defined(_ARM64_) +extern PVOID __guard_dispatch_icall_fptr; +#endif +#if defined(_AMD64_) +extern PVOID __guard_xfg_check_icall_fptr; +extern PVOID __guard_xfg_dispatch_icall_fptr; +extern PVOID __guard_xfg_table_dispatch_icall_fptr; +#endif +extern volatile VOID (*__castguard_check_failure_os_handled_fptr)(PVOID rhsVftablePtr); + +#if defined(_M_IX86) || defined(_X86_) +/* + * The following two names are automatically created by the linker for any + * image that has the safe exception table present. + */ + +extern PVOID __safe_se_handler_table[]; /* base of safe handler entry table */ +extern BYTE __safe_se_handler_count; /* absolute symbol whose address is + the count of table entries */ +#endif +extern PVOID __guard_fids_table[]; +extern ULONG __guard_fids_count; +extern ULONG __guard_flags; +extern PVOID __guard_iat_table[]; +extern ULONG __guard_iat_count; +extern PVOID __guard_longjmp_table[]; +extern ULONG __guard_longjmp_count; +extern PVOID __dynamic_value_reloc_table; +extern PVOID __enclave_config; +extern PVOID __guard_eh_cont_table[]; +extern ULONG __guard_eh_cont_count; + +#if defined(_M_IX86) || defined(_X86_) +#pragma extern_absolute("___AbsoluteZero", "0") +#else +#pragma extern_absolute("__AbsoluteZero", "0") +#endif + +#if defined(_CRT_ENABLE_VOLATILE_METADATA) + +extern PVOID __volatile_metadata; + +#if defined(_M_IX86) || defined(_X86_) +#pragma comment(linker, "/alternatename:___volatile_metadata=___AbsoluteZero") +#else +#pragma comment(linker, "/alternatename:__volatile_metadata=__AbsoluteZero") +#endif + +#endif + +#if defined(_AMD64_) || defined(_ARM64_) +extern void* (__cdecl* volatile __guard_memcpy_fptr)(void* dst, void* src, size_t count); +#pragma comment(linker, "/alternatename:__guard_memcpy_fptr=__AbsoluteZero") +#endif + + +#if defined(_CRT_WINDOWS) +// Windows build has the up-to-date SDK and hence does not need this DevDiv workaround for their stale SDK. +#else // _CRT_WINDOWS +typedef struct _RS5_IMAGE_LOAD_CONFIG_DIRECTORY32 { + ULONG Size; + ULONG TimeDateStamp; + USHORT MajorVersion; + USHORT MinorVersion; + ULONG GlobalFlagsClear; + ULONG GlobalFlagsSet; + ULONG CriticalSectionDefaultTimeout; + ULONG DeCommitFreeBlockThreshold; + ULONG DeCommitTotalFreeThreshold; + ULONG LockPrefixTable; // VA + ULONG MaximumAllocationSize; + ULONG VirtualMemoryThreshold; + ULONG ProcessHeapFlags; + ULONG ProcessAffinityMask; + USHORT CSDVersion; + USHORT DependentLoadFlags; + ULONG EditList; // VA + ULONG SecurityCookie; // VA + ULONG SEHandlerTable; // VA + ULONG SEHandlerCount; + ULONG GuardCFCheckFunctionPointer; // VA + ULONG GuardCFDispatchFunctionPointer; // VA + ULONG GuardCFFunctionTable; // VA + ULONG GuardCFFunctionCount; + ULONG GuardFlags; + IMAGE_LOAD_CONFIG_CODE_INTEGRITY CodeIntegrity; + ULONG GuardAddressTakenIatEntryTable; // VA + ULONG GuardAddressTakenIatEntryCount; + ULONG GuardLongJumpTargetTable; // VA + ULONG GuardLongJumpTargetCount; + ULONG DynamicValueRelocTable; // VA + ULONG CHPEMetadataPointer; + ULONG GuardRFFailureRoutine; // VA + ULONG GuardRFFailureRoutineFunctionPointer; // VA + ULONG DynamicValueRelocTableOffset; + USHORT DynamicValueRelocTableSection; + USHORT Reserved2; + ULONG GuardRFVerifyStackPointerFunctionPointer; // VA + ULONG HotPatchTableOffset; + ULONG Reserved3; + ULONG EnclaveConfigurationPointer; // VA + ULONG VolatileMetadataPointer; // VA + ULONG GuardEHContinuationTable; // VA + ULONG GuardEHContinuationCount; + ULONG GuardXFGCheckFunctionPointer; // VA + ULONG GuardXFGDispatchFunctionPointer; // VA + ULONG GuardXFGTableDispatchFunctionPointer; // VA + ULONG CastGuardOsDeterminedFailureMode; // VA + ULONG GuardMemcpyFunctionPointer; // VA +} RS5_IMAGE_LOAD_CONFIG_DIRECTORY32, *PRS5_IMAGE_LOAD_CONFIG_DIRECTORY32; + +typedef struct _RS5_IMAGE_LOAD_CONFIG_DIRECTORY64 { + ULONG Size; + ULONG TimeDateStamp; + USHORT MajorVersion; + USHORT MinorVersion; + ULONG GlobalFlagsClear; + ULONG GlobalFlagsSet; + ULONG CriticalSectionDefaultTimeout; + ULONGLONG DeCommitFreeBlockThreshold; + ULONGLONG DeCommitTotalFreeThreshold; + ULONGLONG LockPrefixTable; // VA + ULONGLONG MaximumAllocationSize; + ULONGLONG VirtualMemoryThreshold; + ULONGLONG ProcessAffinityMask; + ULONG ProcessHeapFlags; + USHORT CSDVersion; + USHORT DependentLoadFlags; + ULONGLONG EditList; // VA + ULONGLONG SecurityCookie; // VA + ULONGLONG SEHandlerTable; // VA + ULONGLONG SEHandlerCount; + ULONGLONG GuardCFCheckFunctionPointer; // VA + ULONGLONG GuardCFDispatchFunctionPointer; // VA + ULONGLONG GuardCFFunctionTable; // VA + ULONGLONG GuardCFFunctionCount; + ULONG GuardFlags; + IMAGE_LOAD_CONFIG_CODE_INTEGRITY CodeIntegrity; + ULONGLONG GuardAddressTakenIatEntryTable; // VA + ULONGLONG GuardAddressTakenIatEntryCount; + ULONGLONG GuardLongJumpTargetTable; // VA + ULONGLONG GuardLongJumpTargetCount; + ULONGLONG DynamicValueRelocTable; // VA + ULONGLONG CHPEMetadataPointer; // VA + ULONGLONG GuardRFFailureRoutine; // VA + ULONGLONG GuardRFFailureRoutineFunctionPointer; // VA + ULONG DynamicValueRelocTableOffset; + USHORT DynamicValueRelocTableSection; + USHORT Reserved2; + ULONGLONG GuardRFVerifyStackPointerFunctionPointer; // VA + ULONG HotPatchTableOffset; + ULONG Reserved3; + ULONGLONG EnclaveConfigurationPointer; // VA + ULONGLONG VolatileMetadataPointer; // VA + ULONGLONG GuardEHContinuationTable; // VA + ULONGLONG GuardEHContinuationCount; + ULONGLONG GuardXFGCheckFunctionPointer; // VA + ULONGLONG GuardXFGDispatchFunctionPointer; // VA + ULONGLONG GuardXFGTableDispatchFunctionPointer; // VA + ULONGLONG CastGuardOsDeterminedFailureMode; // VA + ULONGLONG GuardMemcpyFunctionPointer; // VA +} RS5_IMAGE_LOAD_CONFIG_DIRECTORY64, *PRS5_IMAGE_LOAD_CONFIG_DIRECTORY64; + +#ifdef _WIN64 +typedef RS5_IMAGE_LOAD_CONFIG_DIRECTORY64 RS5_IMAGE_LOAD_CONFIG_DIRECTORY; +typedef PRS5_IMAGE_LOAD_CONFIG_DIRECTORY64 PRS5_IMAGE_LOAD_CONFIG_DIRECTORY; +#else +typedef RS5_IMAGE_LOAD_CONFIG_DIRECTORY32 RS5_IMAGE_LOAD_CONFIG_DIRECTORY; +typedef PRS5_IMAGE_LOAD_CONFIG_DIRECTORY32 PRS5_IMAGE_LOAD_CONFIG_DIRECTORY; +#endif + +#endif // _CRT_WINDOWS + +#if defined(_CHPE_X86_ARM64_) || defined(_ARM64EC_) + +extern const PVOID __chpe_metadata; + +#endif + +const +DECLSPEC_SELECTANY +#if defined(_CRT_WINDOWS) +IMAGE_LOAD_CONFIG_DIRECTORY +#else +RS5_IMAGE_LOAD_CONFIG_DIRECTORY +#endif +_load_config_used = { + sizeof(_load_config_used), + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + (SIZE_T)&__security_cookie, + +#if defined(_M_IX86) || defined(_X86_) + + (SIZE_T)__safe_se_handler_table, + (SIZE_T)&__safe_se_handler_count, + +#else + + 0, + 0, + +#endif + + (SIZE_T)&__guard_check_icall_fptr, + +#if defined(_AMD64_) || defined(_ARM64_) + + (SIZE_T)&__guard_dispatch_icall_fptr, + +#else + + 0, + +#endif + + (SIZE_T)&__guard_fids_table, + (SIZE_T)&__guard_fids_count, + + (ULONG)(SIZE_T)&__guard_flags, + + { 0, 0, 0, 0 }, + + (SIZE_T)&__guard_iat_table, + (SIZE_T)&__guard_iat_count, + + (SIZE_T)&__guard_longjmp_table, + (SIZE_T)&__guard_longjmp_count, + + 0, + +#if defined(_CHPE_X86_ARM64_) || defined(_ARM64EC_) + + (SIZE_T)&__chpe_metadata, + +#else + + 0, + +#endif + + 0, + 0, + + 0, // DynamicValueRelocTableOffset + 0, // DynamicValueRelocTableSection + 0, // Reserved2 + + 0, + + 0, // HotPatchTableOffset + 0, // Reserved3 + (SIZE_T)&__enclave_config, + +#if defined(_CRT_ENABLE_VOLATILE_METADATA) + + (SIZE_T)&__volatile_metadata, + +#else + + 0, // VolatileMetadataPointer + +#endif + + (SIZE_T)&__guard_eh_cont_table, + (SIZE_T)&__guard_eh_cont_count, + +#if defined(_AMD64_) + (SIZE_T) &__guard_xfg_check_icall_fptr, // VA + (SIZE_T) &__guard_xfg_dispatch_icall_fptr, + (SIZE_T) &__guard_xfg_table_dispatch_icall_fptr, +#else + 0, + 0, + 0, +#endif + + (SIZE_T) &__castguard_check_failure_os_handled_fptr, + +#if defined(_AMD64_) || defined(_ARM64_) + (SIZE_T) &__guard_memcpy_fptr, +#else + 0, +#endif +}; diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/locks.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/locks.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dd14bac14833fc19e37c9bea90c6ba1661fc1605 --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/locks.cpp @@ -0,0 +1,61 @@ +// +// locks.cpp +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// Critical sections used for synchronization in the VCRuntime. +// +#include + +extern "C" { + +// This table holds the locks used by the VCRuntime. It is indexed using the +// enumerators of the __vcrt_lock_id enumeration. +static CRITICAL_SECTION __vcrt_lock_table[__vcrt_lock_count]; + +// This variable stores the number of locks that have been successfully +// initialized. Locks are initialized in order and are destroyed in reverse +// order. The startup and exit code must ensure that initialization and +// destruction is synchronized: these functions should never be executed +// concurrently. +static unsigned __vcrt_locks_initialized; + + +bool __cdecl __vcrt_initialize_locks() +{ + for (unsigned i = 0; i < __vcrt_lock_count; ++i) + { + if (!__vcrt_InitializeCriticalSectionEx(&__vcrt_lock_table[i], _VCRT_SPINCOUNT, 0)) + { + __vcrt_uninitialize_locks(); + return false; + } + + ++__vcrt_locks_initialized; + } + + return true; +} + +bool __cdecl __vcrt_uninitialize_locks() +{ + for (unsigned i = __vcrt_locks_initialized; i > 0; --i) + { + DeleteCriticalSection(&__vcrt_lock_table[i - 1]); + --__vcrt_locks_initialized; + } + + return true; +} + +void __cdecl __vcrt_lock(_In_ __vcrt_lock_id _Lock) +{ + EnterCriticalSection(&__vcrt_lock_table[_Lock]); +} + +void __cdecl __vcrt_unlock(_In_ __vcrt_lock_id _Lock) +{ + LeaveCriticalSection(&__vcrt_lock_table[_Lock]); +} + +} // extern "C" diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/longjmpc.c b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/longjmpc.c new file mode 100644 index 0000000000000000000000000000000000000000..1af85cdc400435431d44eb5a44956933021d98a8 --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/longjmpc.c @@ -0,0 +1,99 @@ +/*++ + +Copyright (c) Microsoft Corporation + +Module Name: + + longjmpc.c + +Abstract: + + This module implements C support code for long jump. + +Environment: + + Kernel mode only. + +--*/ + +#ifndef _M_IX86 +#define longjmp __longjmp_crt +#endif + +#include +#include +#include + +#undef longjmp + +int +__longjmp_internal ( + _In_reads_(_JBLEN) jmp_buf JumpBuffer, + _In_ int ReturnValue + ); + +#if defined(NTOS_KERNEL_RUNTIME) && defined(_AMD64_) + +VOID +KeCheckStackAndTargetAddress ( + _In_ LONG64 Rip, + _In_ ULONG64 Rsp + ); + +#else + +void +__except_validate_jump_buffer ( + _In_reads_(_JBLEN) jmp_buf JumpBuffer + ); + +#endif + +DECLSPEC_GUARD_SUPPRESS +void +longjmp ( + _In_reads_(_JBLEN) jmp_buf JumpBuffer, + _In_ int ReturnValue + ) + +/*++ + +Routine Description: + + This function validates a jump buffer and performs a long jump to the + context specified by the jump buffer. + +Arguments: + + JumpBuffer - Supplies the address of a jump buffer. + + ReturnValue - Supplies the value that is to be returned to the caller of + set jump. + +Return Value: + + None (however the return value is loaded). + +--*/ + +{ + + // + // Validate the contents of the jump buffer and execute long jump. + // + +#if defined(NTOS_KERNEL_RUNTIME) && defined(_AMD64_) + + _JUMP_BUFFER *jmpBuf; + + jmpBuf = (_JUMP_BUFFER *)JumpBuffer; + KeCheckStackAndTargetAddress(jmpBuf->Rip, jmpBuf->Rsp); + +#else + + __except_validate_jump_buffer(JumpBuffer); + +#endif + + __longjmp_internal(JumpBuffer, ReturnValue); +} diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/managdeh.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/managdeh.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2f1a6f2701e029fdb2bdc7b3f99c23a3585312bd --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/managdeh.cpp @@ -0,0 +1,657 @@ +/*** +* managdeh.cpp - The frame handler and everything associated with it. +* +* Copyright (c) Microsoft Corporation. All rights reserved. +* +*Purpose: +* The frame handler and everything associated with it. +* +* Entry points: +* _CxxFrameHandler - the frame handler. +* +* Open issues: +* Handling re-throw from dynamically nested scope. +* Fault-tolerance (checking for data structure validity). +****/ + +#undef CRTDLL +#undef MRTDLL + +#ifndef _DLL +#define _DLL +#endif + +#include // User-visible routines for eh +#include // This project's versions of standard assert macros +#include // Declarations of all types used for EH +#include // Declarations of hook variables and callbacks +#include // Routines to handle transfer of control (trnsctrl.asm) + +#include + +#ifndef _M_CEE + #error This file is intended to be compiled for managed code only +#endif + +// Pre-V4 managed exception code +#define MANAGED_EXCEPTION_CODE 0XE0434F4D + +// V4 and later managed exception code +#define MANAGED_EXCEPTION_CODE_V4 0XE0434352 + +//////////////////////////////////////////////////////////////////////////////// +// +// Forward declaration of local functions: +// + +// The local unwinder must be external (see ___CxxLongjmpUnwind in trnsctrl.cpp) + +extern "C" _VCRTIMP int __cdecl __FrameUnwindFilter( + EXCEPTION_POINTERS * +); + +extern "C" _VCRTIMP void * __cdecl __AdjustPointer( + void *, + const PMD& +); + +#ifdef _M_CEE_PURE + +//////////////////////////////////////////////////////////////////////////////// +// +// __TypeMatch - Check if the catch type matches the given throw conversion. +// +// Returns: +// TRUE if the catch can catch using this throw conversion, FALSE otherwise. + +template +_CRT_RELIABILITY_CONTRACT +_CRT_ASSERT_UNMANAGED_CODE_ATTRIBUTE +_CRT_SECURITYSAFECRITICAL_ATTRIBUTE +static int TypeMatch( + HandlerType *pCatch, // Type of the 'catch' clause + CatchableType *pCatchable, // Type conversion under consideration + ThrowInfo *pThrow // General information about the thrown + // type. +) { + // First, check for match with ellipsis: + if (HT_IS_TYPE_ELLIPSIS(*pCatch)) { + return TRUE; + } + + // Not ellipsis; the basic types match if it's the same record *or* the + // names are identical. + if (HT_PTD(*pCatch) != CT_PTD(*pCatchable) + && strcmp(HT_NAME(*pCatch), CT_NAME(*pCatchable)) != 0) { + return FALSE; + } + + // Basic types match. The actual conversion is valid if: + // caught by ref if ref required *and* + // the qualifiers are compatible *and* + // the alignments match *and* + // the volatility matches + + return (!CT_BYREFONLY(*pCatchable) || HT_ISREFERENCE(*pCatch)) + && (!THROW_ISCONST(*pThrow) || HT_ISCONST(*pCatch)) +#if defined(_M_X64) || defined(_M_ARM64) + && (!THROW_ISUNALIGNED(*pThrow) || HT_ISUNALIGNED(*pCatch)) +#endif + && (!THROW_ISVOLATILE(*pThrow) || HT_ISVOLATILE(*pCatch)); +} + +//////////////////////////////////////////////////////////////////////////////// +// +// BuildCatchObjectHelper - Copy or construct the catch object from the object thrown. +// +// Returns: +// 0 if nothing to be done for constructing object from caller side +// 1 if single parameter constructor is to be called. +// 2 if two parameter constructor ist to be called. +// +// Side-effects: +// A buffer in the subject function's frame is initialized. +// +// Open issues: +// What happens if the constructor throws? (or faults?) + +template +_CRT_RELIABILITY_CONTRACT +_CRT_ASSERT_UNMANAGED_CODE_ATTRIBUTE +_CRT_SECURITYCRITICAL_ATTRIBUTE +static int BuildCatchObjectHelper( + EHExceptionRecord *pExcept, // Original exception thrown + void *pRN, // This is a pointer to the object + // that we want to build while doing + // COM+ eh. If we are in our own eh, + // then this is a Registration node of + // catching function + HandlerType *pCatch, // The catch clause that got it + CatchableType *pConv // The conversion to use +) { + int retval = 0; + + // If the catch is by ellipsis, then there is no object to construct. + // If the catch is by type(No Catch Object), then leave too! + if (HT_IS_TYPE_ELLIPSIS(*pCatch) || + (!HT_DISPCATCH(*pCatch) && !HT_ISCOMPLUSEH(*pCatch))) { + return 0; + } + + _VCRT_VERIFY(HT_ISCOMPLUSEH(*pCatch)); + void **pCatchBuffer = (void **)pRN; + __try { + if (HT_ISREFERENCE(*pCatch)) { + + // The catch is of form 'reference to T'. At the throw point we + // treat both 'T' and 'reference to T' the same, i.e. + // pExceptionObject is a (machine) pointer to T. Adjust as + // required. + _VCRT_VERIFY(PER_PEXCEPTOBJ(pExcept) && pCatchBuffer); + *pCatchBuffer = PER_PEXCEPTOBJ(pExcept); + *pCatchBuffer = __AdjustPointer(*pCatchBuffer, CT_THISDISP(*pConv)); + } else if (CT_ISSIMPLETYPE(*pConv)) { + + // Object thrown is of simple type (this including pointers) copy + // specified number of bytes. Adjust the pointer as required. If + // the thing is not a pointer, then this should be safe since all + // the entries in the THISDISP are 0. + _VCRT_VERIFY(PER_PEXCEPTOBJ(pExcept) && pCatchBuffer); + memmove(pCatchBuffer, PER_PEXCEPTOBJ(pExcept), CT_SIZE(*pConv)); + + if (CT_SIZE(*pConv) == sizeof(void*) && *pCatchBuffer != nullptr) { + *pCatchBuffer = __AdjustPointer(*pCatchBuffer, + CT_THISDISP(*pConv)); + } + } else { + // Object thrown is UDT. + if (CT_COPYFUNC(*pConv) == nullptr) { + // The UDT had a simple ctor. Adjust in the thrown object, + // then copy n bytes. + _VCRT_VERIFY(PER_PEXCEPTOBJ(pExcept) && pCatchBuffer); + memmove(pCatchBuffer, __AdjustPointer(PER_PEXCEPTOBJ(pExcept), CT_THISDISP(*pConv)), CT_SIZE(*pConv)); + } else { + // It's a UDT: make a copy using copy ctor + _VCRT_VERIFY(PER_PEXCEPTOBJ(pExcept) && pCatchBuffer && CT_COPYFUNC(*pConv)); + if (CT_HASVB(*pConv)) { + retval = 2; + } else { + retval = 1; + } + } + } + } __except(EXCEPTION_EXECUTE_HANDLER) { + // Something went wrong when building the catch object. + abort(); + } + + return retval; +} +//////////////////////////////////////////////////////////////////////////////// +// +// BuildCatchObject - Copy or construct the catch object from the object thrown. +// +// Returns: +// nothing. +// +// Side-effects: +// A buffer in the subject function's frame is initialized. +// +// Open issues: +// What happens if the constructor throws? (or faults?) + +template +_CRT_RELIABILITY_CONTRACT +_CRT_ASSERT_UNMANAGED_CODE_ATTRIBUTE +_CRT_SECURITYCRITICAL_ATTRIBUTE +static void BuildCatchObject( + EHExceptionRecord *pExcept, // Original exception thrown + void *pRN, // This is a pointer to the object + // that we want to build while doing + // COM+ eh. If we are in our own eh, + // then this is a Registration node of + // catching function + HandlerType *pCatch, // The catch clause that got it + CatchableType *pConv // The conversion to use +) { + void **pCatchBuffer = (void **)pRN; + + _VCRT_VERIFY(HT_ISCOMPLUSEH(*pCatch)); + + __try { + switch(BuildCatchObjectHelper(pExcept, pRN, pCatch, pConv)) + { + case 1: + { + void (__clrcall *pFunc)(void *, void *) = (void (__clrcall *)(void *, void *))(void *)CT_COPYFUNC(*pConv); + pFunc((void *)pCatchBuffer, __AdjustPointer(PER_PEXCEPTOBJ(pExcept), CT_THISDISP(*pConv))); + } + break; + case 2: + { + void (__clrcall *pFunc)(void *, void *, int) = (void (__clrcall *)(void *, void *, int))(void *)CT_COPYFUNC(*pConv); + pFunc((void *)pCatchBuffer, __AdjustPointer(PER_PEXCEPTOBJ(pExcept), CT_THISDISP(*pConv)), 1); + } + break; + case 0: + break; + default: + break; + } + } __except(EXCEPTION_EXECUTE_HANDLER) { + // Something went wrong when building the catch object. + abort(); + } +} + + + +//////////////////////////////////////////////////////////////////////////////// +// +// __DestructExceptionObject_m - Call the destructor (if any) of the original +// exception object. +// +// Returns: None. +// +// Side-effects: +// Original exception object is destructed. +// +// Notes: +// If destruction throws any exception, and we are destructing the exception +// object as a result of a new exception, we give up. If the destruction +// throws otherwise, we let it be. + +_CRT_RELIABILITY_CONTRACT +_CRT_ASSERT_UNMANAGED_CODE_ATTRIBUTE +_CRT_SECURITYCRITICAL_ATTRIBUTE +static void __DestructExceptionObject_m( + EHExceptionRecord *pExcept, // The original exception record + BOOLEAN fThrowNotAllowed // TRUE if destructor not allowed to + // throw +) { + EHTRACE_FMT1("Destroying object @ 0x%p", PER_PEXCEPTOBJ(pExcept)); + + if (pExcept != nullptr && THROW_UNWINDFUNC(*PER_PTHROW(pExcept)) != nullptr) { + + __try { + void (__clrcall * pDtor)(void*) = nullptr; + +#pragma warning(push) +#pragma warning(disable:4191) + pDtor = (void (__clrcall *)(void *))(THROW_UNWINDFUNC(*PER_PTHROW(pExcept))); + (*pDtor)(PER_PEXCEPTOBJ(pExcept)); +#pragma warning(pop) + + } __except(fThrowNotAllowed ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { + + // Can't have new exceptions when we're unwinding due to another + // exception. + terminate(); + } + } +} + +//////////////////////////////////////////////////////////////////////////////// +// Model of C++ eh in COM+ +// +// void func() +// { +// try { +// TryBody(); +// } catch (cpp_object o) +// { +// CatchOBody(); +// } catch (...) +// { +// CatchAllBody(); +// } +// } +// +// Turns into this: +// +// +// void func() +// { +// int rethrow; +// // One per try block +// int isCxxException; +// // One per catch(...) +// __try { +// TryBody(); +// } +// __except(___CxxExceptionFilter(exception, +// typeinfo(cpp_object), +// flags, +// &o)) +// // This is how it's done already +// { +// // Begin catch(object) prefix +// char *storage = _alloca(___CxxQueryExceptionSize()); +// rethrow = false; +// ___CxxRegisterExceptionObject(exception, +// storage); +// __try { +// __try { +// // End catch(object) prefix +// CatchOBody(); +// // Begin catch(object) suffix +// } __except(rethrow = ___CxxDetectRethrow(exception), +// EXCEPTION_CONTINUE_SEARCH) +// {} +// } +// __finally +// { +// ___CxxUnregisterExceptionObject(storage, +// rethrow); +// } +// // End catch(object) suffix +// } +// __except(1) +// { +// // Begin catch(...) prefix +// char *storage = _alloca(___CxxQueryExceptionSize()); +// rethrow = false; +// isCxxException = ___CxxRegisterExceptionObject(exception, +// storage); +// __try +// { +// __try +// { +// // End catch(...) prefix +// CatchAllBody(); +// // Begin catch(...) suffix +// } __except(rethrow = ___CxxDetectRethrow(exception), +// EXCEPTION_CONTINUE_SEARCH) +// {} +// } __finally +// { +// if (isCxxException) +// ___CxxUnregisterExceptionObject(storage, rethrow); +// } +// // End catch(...) suffix +// } +// } +// +//////////////////////////////////////////////////////////////////////////////// + +//////////////////////////////////////////////////////////////////////////////// +// +// ___CxxExceptionFilter() - Returns EXCEPTION_EXECUTE_HANDLER when the pType +// matches with the objects we can catch. Returns +// EXCEPTION_CONTINUE_SEARCH when pType is not one of +// the catchable type for the thrown object. This +// function is made for use with COM+ EH, where they +// attempt to do C++ EH as well. +// + +_CRT_RELIABILITY_CONTRACT +_CRT_SECURITYCRITICAL_ATTRIBUTE +int __clrcall ___CxxExceptionFilter( + void *ppExcept, // Information for this (logical) + // exception + void *pType, // Info about the datatype. + int adjectives, // Extra Info about the datatype. + void *pBuildObj // Pointer to datatype. + ) +{ + CatchableType * const _UNALIGNED *ppCatchable; + CatchableType *pCatchable; + int catchables; + EHExceptionRecord *pExcept; + + if (!ppExcept) { + return EXCEPTION_CONTINUE_SEARCH; + } + pExcept = *(EHExceptionRecord **)ppExcept; + // If catch all, always return EXCEPTION_EXECUTE_HANDLER + // Note that if the adjective has HT_IsStdDotDot flag on, we comply Std + // C++ eh behaviour, i.e. only catching C++ objects. + if ( TD_IS_TYPE_ELLIPSIS((TypeDescriptor *)pType) && + (pExcept->ExceptionCode == MANAGED_EXCEPTION_CODE || + pExcept->ExceptionCode == MANAGED_EXCEPTION_CODE_V4 || + !(adjectives & HT_IsStdDotDot))) + { + if (PER_IS_MSVC_EH(pExcept)) + { + if ( PER_PTHROW(pExcept) == nullptr) + { + if ( _pCurrentException == nullptr) { + return EXCEPTION_CONTINUE_SEARCH; + } + } + } + __ProcessingThrow++; + return EXCEPTION_EXECUTE_HANDLER; + } + + if (PER_IS_MSVC_EH(pExcept)) + { + if ( PER_PTHROW(pExcept) == nullptr) { + if (_pCurrentException == nullptr) + return EXCEPTION_CONTINUE_SEARCH; + pExcept = _pCurrentException; + } + + /* + * Note that we will only be using pType or dispType + * and adjective field of pCatch. + */ + struct _s_HandlerType HType; + HType.pType = (TypeDescriptor *)pType; + HType.adjectives = adjectives | HT_IsComplusEh; + + // Scan all types that thrown object can be converted to: + ppCatchable = THROW_CTLIST(*PER_PTHROW(pExcept)); + for (catchables = THROW_COUNT(*PER_PTHROW(pExcept)); + catchables > 0; catchables--, ppCatchable++) { + + pCatchable = *ppCatchable; + if (TypeMatch(&HType, pCatchable, PER_PTHROW(pExcept))) { + // Successful. Now build the object. + __ProcessingThrow++; + if (pBuildObj != nullptr) + BuildCatchObject(pExcept, pBuildObj, &HType, pCatchable); + return EXCEPTION_EXECUTE_HANDLER; + } + } // Scan possible conversions + } + return EXCEPTION_CONTINUE_SEARCH; +} + +//////////////////////////////////////////////////////////////////////////////// +// +// ___CxxRegisterExceptionObject() - Registers Exception Object and saves it to +// This is same as first part of +// CallCatchBlock. +// +_CRT_RELIABILITY_CONTRACT +_CRT_ASSERT_UNMANAGED_CODE_ATTRIBUTE +_CRT_SECURITYCRITICAL_ATTRIBUTE +int __clrcall ___CxxRegisterExceptionObject( + void *ppExcept, + void *pStorage +) +{ + // This function is only called for C++ EH. + EHExceptionRecord *pExcept = nullptr; + FRAMEINFO *pFrameInfo = (FRAMEINFO *)pStorage; + EHExceptionRecord **ppSaveException; + CONTEXT **ppSaveExContext; + ppSaveException = (EHExceptionRecord **)(&pFrameInfo[1]); + ppSaveExContext = (CONTEXT **)(&ppSaveException[1]); + if (ppExcept != nullptr && (*(void **)ppExcept) != nullptr) { + pExcept = *(EHExceptionRecord **)ppExcept; + if (PER_IS_MSVC_EH(pExcept)) { + if ( PER_PTHROW(pExcept) == nullptr) { + // was a rethrow + pExcept = _pCurrentException; + } + } + pFrameInfo = _CreateFrameInfo(pFrameInfo, PER_PEXCEPTOBJ(pExcept)); + *ppSaveException = _pCurrentException; + *ppSaveExContext = _pCurrentExContext; + _pCurrentException = pExcept; + } else { + *ppSaveException = (EHExceptionRecord *)-1; + *ppSaveExContext = (CONTEXT *)-1; + } + __ProcessingThrow--; + if ( __ProcessingThrow < 0) + __ProcessingThrow = 0; + return 1; +} + +//////////////////////////////////////////////////////////////////////////////// +// +// ___CxxDetectRethrow() - Looks at the Exception and returns true if rethrow, +// false if not a rethrow. This is then used for +// destructing the exception object in +// ___CxxUnregisterExceptionObject(). +// +_CRT_RELIABILITY_CONTRACT +_CRT_SECURITYCRITICAL_ATTRIBUTE +int __clrcall ___CxxDetectRethrow( + void *ppExcept +) +{ + EHExceptionRecord *pExcept; + if (!ppExcept) + return EXCEPTION_CONTINUE_SEARCH; + pExcept = *(EHExceptionRecord **)ppExcept; + if (PER_IS_MSVC_EH(pExcept) && PER_PTHROW(pExcept) == nullptr) { + __ProcessingThrow++; + return EXCEPTION_EXECUTE_HANDLER; + } + return EXCEPTION_CONTINUE_SEARCH; +} + +//////////////////////////////////////////////////////////////////////////////// +// +// ___CxxUnregisterExceptionObject - Destructs Exception Objects if rethrow == +// true. Also set __pCurrentException and +// __pCurrentExContext() to current value. +// +_CRT_RELIABILITY_CONTRACT +_CRT_ASSERT_UNMANAGED_CODE_ATTRIBUTE +_CRT_SECURITYCRITICAL_ATTRIBUTE +void __clrcall ___CxxUnregisterExceptionObject( + void *pStorage, + int rethrow +) +{ + FRAMEINFO *pFrameInfo = (FRAMEINFO *)pStorage; + EHExceptionRecord **ppSaveException; + CONTEXT **ppSaveExContext; + ppSaveException = (EHExceptionRecord **)(&pFrameInfo[1]); + ppSaveExContext = (CONTEXT **)(&ppSaveException[1]); + if (*ppSaveException != (void *)-1) { + _FindAndUnlinkFrame(pFrameInfo); + if ( !rethrow && PER_IS_MSVC_EH(_pCurrentException) && + _IsExceptionObjectToBeDestroyed(PER_PEXCEPTOBJ(_pCurrentException)) + ) { + __DestructExceptionObject_m(_pCurrentException, TRUE); + } + if (PER_IS_MSVC_EH(_pCurrentException) && rethrow) + __ProcessingThrow--; + _pCurrentException = *ppSaveException; + _pCurrentExContext = *ppSaveExContext; + } +} + +//////////////////////////////////////////////////////////////////////////////// +// +// ___CxxQueryExceptionSize - returns the value of Storage needed to save +// FrameInfo + two pointers. +// +_CRT_RELIABILITY_CONTRACT +int __clrcall ___CxxQueryExceptionSize( + void +) +{ + return sizeof(FRAMEINFO) + sizeof(void *) + sizeof(void *); +} + +#endif // defined(_M_CEE_PURE) + +//////////////////////////////////////////////////////////////////////////////// +// +// The following routines are available in both the pure and mixed CRTs +// (msvcurt and msvcmrt). They are wrappers around calls to dtors which +// call terminate() when those dtors throw an exception. +// +//////////////////////////////////////////////////////////////////////////////// + +//////////////////////////////////////////////////////////////////////////////// +// +// ___CxxCallUnwindDtor - Calls a destructor during unwind. For COM+, the dtor +// call needs to be wrapped inside a __try/__except to +// get correct terminate() behavior when an exception +// occurs during the dtor call. +// +_CRT_RELIABILITY_CONTRACT +_CRT_ASSERT_UNMANAGED_CODE_ATTRIBUTE +_CRT_SECURITYCRITICAL_ATTRIBUTE +extern "C" void __clrcall ___CxxCallUnwindDtor( + void (__clrcall * pDtor)(void *), + void *pThis +) +{ + __try + { + (*pDtor)(pThis); + } + __except(__FrameUnwindFilter(exception_info())) + { + } +} + +//////////////////////////////////////////////////////////////////////////////// +// +// ___CxxCallUnwindDelDtor - Calls a delete during unwind. For COM+, the dtor +// call needs to be wrapped inside a __try/__except to +// get correct terminate() behavior when an exception +// occurs during the dtor call. +// +_CRT_RELIABILITY_CONTRACT +_CRT_ASSERT_UNMANAGED_CODE_ATTRIBUTE +_CRT_SECURITYCRITICAL_ATTRIBUTE +extern "C" void __clrcall ___CxxCallUnwindDelDtor( + void (__clrcall * pDtor)(void*), + void *pThis +) +{ + __try + { + (*pDtor)(pThis); + } + __except(__FrameUnwindFilter(exception_info())) + { + ; // Deliberately do nothing + } +} + +////////////////////////////////////////////////////////////////////////////////// +// ___CxxCallUnwindVecDtor - Calls a vector destructor during vector unwind. +// For COM+, the dtor call needs to be wrapped inside +// a __try/__except to get correct terminate() behavior +// when an exception occurs during the dtor call. +// +_CRT_RELIABILITY_CONTRACT +_CRT_ASSERT_UNMANAGED_CODE_ATTRIBUTE +_CRT_SECURITYCRITICAL_ATTRIBUTE +extern "C" void __clrcall ___CxxCallUnwindVecDtor( + void (__clrcall * pVecDtor)(void*, size_t, int, void (__clrcall *)(void*)), + void* ptr, + size_t size, + int count, + void (__clrcall * pDtor)(void*) +) +{ + __try + { + (*pVecDtor)(ptr, size, count, pDtor); + } + __except(__FrameUnwindFilter(exception_info())) + { + } +} diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/matherr.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/matherr.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c3656a036553abd138344cb85e4e06a283a14304 --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/matherr.cpp @@ -0,0 +1,23 @@ +// +// matherr.cpp +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// This object provides a default definition of the _matherr function. This +// definition may be substituted by the client by redefining it. The flag +// __scrt_default_matherr has a value of 1 if this object is used (it has a +// value of 0 otherwise, via an alternate definition. +// +#include +#include + + + +extern "C" int __scrt_default_matherr = 1; + + + +extern "C" int __CRTDECL _matherr(_Inout_ _exception*) +{ + return 0; +} diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/matherr_detection.c b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/matherr_detection.c new file mode 100644 index 0000000000000000000000000000000000000000..9130d523640b4002c9468f7686b4cdb745959966 --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/matherr_detection.c @@ -0,0 +1,24 @@ +// +// matherr_detection.c +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// This source file allows us to detect the presence of a user-defined _matherr +// function. If the user does not define a _matherr function, the definition +// of _matherr in matherr.cpp will be linked in, which will also define the +// __scrt_default_matherr flag to a value other than zero. If the user does +// define a _matherr function, then matherr.cpp will not be linked in, so that +// other definition of __scrt_default_matherr will not be present, and the local +// definition will be used instead. This has a value of zero. +// +// This relies on a feature of the C compiler known as "communal variables." +// This does not work in C++, and the linker's alternatename features is not +// sufficient here. +// +#pragma warning(disable: 4132) // const object should be initialized +int const __scrt_default_matherr; + +int __scrt_is_user_matherr_present() +{ + return __scrt_default_matherr == 0; +} diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/mbsearch.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/mbsearch.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c34c2ea7682eb416aa80f7d301d6e8411f8e2d3c --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/mbsearch.cpp @@ -0,0 +1,23 @@ +/*** +*mbsearch.cpp - do a binary search +* +* Copyright (c) Microsoft Corporation. All rights reserved. +* +*Purpose: +* defines bsearch() - do a binary search an an array +* +*******************************************************************************/ +#ifndef _M_CEE + #error This file should only be compiled as managed code. +#endif + +#undef MRTDLL + +#include "bsearch.cpp" + +#ifdef __USE_CONTEXT + #error __USE_CONTEXT should be undefined +#endif + +#define __USE_CONTEXT +#include "bsearch.cpp" diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/mcrtexe.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/mcrtexe.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dc8c1ad086dc42a9c9a7a82be9fcbf0cb4ac9b16 --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/mcrtexe.cpp @@ -0,0 +1,491 @@ +/*** +*crtexe.c - Initialization for console EXE using CRT DLL +* +* Copyright (c) Microsoft Corporation. All rights reserved. +* +*Purpose: +* This is the actual startup routine for apps linking to the CRT DLL. +* It calls the user's main routine [w]main() or [w]WinMain after +* performing C Run-Time Library initialization. +* +* With ifdefs, this source file also provides the source code for: +* wcrtexe.c the startup routine for console apps with wide chars +* crtexew.c the startup routine for Windows apps +* wcrtexew.c the startup routine for Windows apps with wide chars +* +*******************************************************************************/ + +#ifdef MRTDLL + +/* + * SPECIAL BUILD MACROS! Note that crtexe.c (and crtexew.c) is linked in with + * the client's code. It does not go into crtdll.dll! Therefore, it must be + * built under the _DLL switch (like user code) and MRTDLL must be undefined. + * The symbol SPECIAL_CRTEXE is turned on to suppress the normal CRT DLL + * definition of _fmode and _commode using __declspec(dllexport). Otherwise + * this module would not be able to refer to both the local and DLL versions + * of these two variables. + */ + +#undef MRTDLL +#ifndef _DLL +#define _DLL +#endif /* _DLL */ + +#define SPECIAL_CRTEXE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#pragma warning(disable:4439) // C4439: function with a managed parameter must have a __clrcall calling convention + +#if defined (_M_CEE_MIXED) + +#pragma managed(push, off) + +static int __cdecl _mixed_pre_c_init(void); + +#pragma section(".CRT$XIAA", long, read) +_CRTALLOC(".CRT$XIAA") static _PIFV mixed_pcinit = _mixed_pre_c_init; + +#pragma managed(pop) + +#endif /* defined (_M_CEE_MIXED) */ + +#define SPACECHAR _T(' ') +#define DQUOTECHAR _T('\"') + +#if !defined (_MANAGED_MAIN) + #if defined (UNICODE) + extern "C" int __CxxPureMSILEntry(int, wchar_t **, wchar_t **); + #define __tinit_cmdline __winit_cmdline + #else /* defined (UNICODE) */ + extern "C" int __CxxPureMSILEntry(int, char **, char **); + #define __tinit_cmdline __init_cmdline + #endif /* defined (UNICODE) */ + using System::String; + using System::Int32; + static int __clrcall __tinit_cmdline(cli::array ^arguments); +#else /* !defined (_MANAGED_MAIN) */ + using System::String; + using System::Int32; + int __clrcall main(cli::array^); + static void __clrcall __set_managed_app_type(void); +#endif /* !defined (_MANAGED_MAIN) */ +static void __CLRCALL_OR_CDECL _common_init(); + +#if defined (WPRFLAG) +#define _IMP___WCMDLN (__p__wcmdln()) +#else /* defined (WPRFLAG) */ +#define _IMP___ACMDLN (__p__acmdln()) +#endif /* defined (WPRFLAG) */ + +/* + * Declare/define communal that serves as indicator the default matherr + * routine is being used. + */ +extern "C" +{ + extern int __scrt_default_matherr; +} + +#if defined (_M_CEE_MIXED) + +#pragma managed(push, off) + +/*** +*_mixed_pre_c_init(void) +* +*Purpose: +* The code in mainCRTStartup that was executed before executing C +* initializers was shifted in this function. Also this function is the +* first thing that is executed in c init section. +* +*Entry: +* +*Exit: +* +*******************************************************************************/ + +#pragma warning(disable : 4792) +static int __cdecl _mixed_pre_c_init(void) +{ + /* + * Mark this module as an EXE file so that atexit/_onexit + * will do the right thing when called, including for C++ + * d-tors. + */ + if (!__scrt_initialize_onexit_tables(__scrt_module_type::exe)) + { + __scrt_fastfail(FAST_FAIL_FATAL_APP_EXIT); + } + + if ( !__scrt_default_matherr ) + __setusermatherr(_matherr); + + /* + * Run the RTC initialization code + */ +#ifdef _RTC + _RTC_Initialize(); +#endif /* _RTC */ + + _common_init(); + + return 0; +} + +#pragma managed(pop) + +#endif /* defined (_M_CEE_MIXED) */ + +/*** +*mainCRTStartup(void) +*wmainCRTStartup(void) +*WinMainCRTStartup(void) +*wWinMainCRTStartup(void) +* +*Purpose: +* These routines do the C runtime initialization, call the appropriate +* user entry function, and handle termination cleanup. For a managed +* app, they then return the exit code back to the calling routine, which +* is the managed startup code. For an unmanaged app, they call exit and +* never return. +* +* Function: User entry called: +* mainCRTStartup main +* wmainCRTStartup wmain +* WinMainCRTStartup WinMain +* wWinMainCRTStartup wWinMain +* +*Entry: +* +*Exit: +* Managed app: return value from main() et al, or the exception code if +* execution was terminated by the __except guarding the call +* to main(). +* Unmanaged app: never return. +* +*******************************************************************************/ + +#if !defined (_MANAGED_MAIN) +#ifdef _WINMAIN_ +#ifdef WPRFLAG + #define _mainCRTStartup wWinMainCRTStartup +#else /* WPRFLAG */ + #define _mainCRTStartup WinMainCRTStartup +#endif /* WPRFLAG */ +#else /* _WINMAIN_ */ +#ifdef WPRFLAG + #define _mainCRTStartup wmainCRTStartup +#else /* WPRFLAG */ + #define _mainCRTStartup mainCRTStartup +#endif /* WPRFLAG */ +#endif /* _WINMAIN_ */ +#else /* !defined (_MANAGED_MAIN) */ + #define _mainCRTStartup __clrcall mainCRTStartupStrArray +#endif /* !defined (_MANAGED_MAIN) */ + +#if !defined (_MANAGED_MAIN) && defined (_WINMAIN_) +int _mainCRTStartup(void) +#else /* !defined (_MANAGED_MAIN) && defined (_WINMAIN_) */ +int _mainCRTStartup(array^ arguments) +#endif /* !defined (_MANAGED_MAIN) && defined (_WINMAIN_) */ +{ + _TCHAR **envp; + + int mainret; + +#ifdef _WINMAIN_ + _TCHAR *lpszCommandLine; +#endif /* _WINMAIN_ */ + + /* + * Guard the initialization code and the call to user's main, or + * WinMain, function in a __try/__except statement. + */ + + __try { + +#if defined (_M_CEE_PURE) + _common_init(); +#endif /* defined (_M_CEE_PURE) */ + +#ifdef WPRFLAG + _configure_wide_argv(_get_startup_argv_mode()); +#else /* WPRFLAG */ + _configure_narrow_argv(_get_startup_argv_mode()); +#endif /* WPRFLAG */ + + _set_new_mode(_get_startup_new_mode()); + +#if !defined (_MANAGED_MAIN) && !defined (_WINMAIN_) + /* init the cmdline (_acmdln or _wcmdln) with the array */ + /* no need to do this if we use managed main or WinMain */ + int const argret = __tinit_cmdline(arguments); + if (argret < 0) + { + abort(); + } +#endif /* !defined (_MANAGED_MAIN) && !defined (_WINMAIN_) */ + +#ifdef WPRFLAG + envp = _get_initial_wide_environment(); +#else /* WPRFLAG */ + envp = _get_initial_narrow_environment(); +#endif /* WPRFLAG */ + +#if defined (_MANAGED_MAIN) + mainret = main(arguments); +#else /* defined (_MANAGED_MAIN) */ + +#ifdef _WINMAIN_ + /* + * Skip past program name (first token in command line). + * Check for and handle quoted program name. + */ +#ifdef WPRFLAG + lpszCommandLine = _get_wide_winmain_command_line(); +#else /* WPRFLAG */ + lpszCommandLine = _get_narrow_winmain_command_line(); +#endif /* WPRFLAG */ + + mainret = _tWinMain( + NULL, + NULL, + lpszCommandLine, + __scrt_get_show_window_mode() + ); +#else /* _WINMAIN_ */ +#ifdef WPRFLAG + mainret = __CxxPureMSILEntry(__argc, __wargv, envp); +#else + mainret = __CxxPureMSILEntry(__argc, __argv, envp); +#endif + +#endif /* _WINMAIN_ */ + +#endif /* defined (_MANAGED_MAIN) */ + + } + __except ( _seh_filter_exe(GetExceptionCode(), GetExceptionInformation()) ) + { + /* + * Should never reach here + */ + mainret = GetExceptionCode(); + } /* end of try - except */ + + return mainret; +} + +#if !defined (_MANAGED_MAIN) && !defined (_WINMAIN_) +_CRT_SECURITYCRITICAL_ATTRIBUTE +static int __clrcall __tinit_cmdline(array ^arguments) +{ + ::System::Text::StringBuilder sb; + const ::System::Char SPACE_SCHAR = ' '; + const ::System::Char DQUOTE_SCHAR = '\"'; + const ::System::Char SLASH_SCHAR = '\\'; + const _TCHAR DQUOTE_TCHAR = _T('\"'); +#ifndef WPRFLAG + const _TCHAR QUESTIONMARK_TCHAR = _T('?'); +#endif + + /* To add the arguments to the cmdline, we use the same rules used to parse the cmdline, + from parse_cmdline, in stdargv.c. The rules are: + + 2N backslashes + " ==> N backslashes and begin/end quote + 2N+1 backslashes + " ==> N backslashes + literal " + N backslashes ==> N backslashes + + so here we use the reverse: + + always surround each argument with doublequotes + a literal " in the argument becomes 1 backslash + literal " + N backslashes + literal " become 2N+1 backslashes + literal " + N backslashes at the end of the argument become 2N backslashes (because we have the closing doublequote) + */ + for each (String ^arg in arguments) + { + sb.Append(SPACE_SCHAR); /* insert a space between the args */ + sb.Append(DQUOTE_SCHAR); /* begin with a double quote */ + for (int i = 0; i < arg->Length; ++i) + { + if (arg[i] == DQUOTE_SCHAR) + { + sb.Append(SLASH_SCHAR); + sb.Append(DQUOTE_SCHAR); + } + else if (arg[i] == SLASH_SCHAR) + { + int numSlash = 0; + while (i < arg->Length && arg[i] == SLASH_SCHAR) + { + ++numSlash; + ++i; + } + if (i < arg->Length) + { + if (arg[i] == DQUOTE_SCHAR) + { + /* we have a 'literal' double quote preceeded by numSlash backslashes: + we will need to append 2 * numSlash backslashes + 1 backslash + 1 double quote */ + sb.Append(SLASH_SCHAR, (2 * numSlash) + 1); + sb.Append(DQUOTE_SCHAR); + } + else + { + /* we have a non double quote char (arg[i]) preceeded by numSlash backslashes: + we will simply need to append numSlash backslashes + arg[i] */ + sb.Append(SLASH_SCHAR, numSlash); + sb.Append(arg[i]); + } + } + else + { + /* the string ends with numSlash backslashes: we need to append 2 * numSlash backslashes + and then add the final double quote (below) */ + sb.Append(SLASH_SCHAR, 2 * numSlash); + break; + } + } + else + { + /* normal char (not a double quote nor a backslash) */ + sb.Append(arg[i]); + } + } + sb.Append(DQUOTE_SCHAR); /* end with a double quote */ + } + + size_t cchArguments = sb.Length; +#ifndef WPRFLAG + cchArguments *= MB_CUR_MAX; /* for multibyte chars, assume that every char will use the maximum space (for this locale) */ +#endif /* WPRFLAG */ + size_t cmdlineSize = + 1 + /* begin double quote for argv[0] */ + MAX_PATH + /* argv[0] */ + 1 + /* end double quote for argv[0] */ + cchArguments + /* argv[1..(argc - 1)] (contains initial space) */ + 1; /* terminating null */ + + _TCHAR *tcmdline = (_TCHAR *)_malloc_crt(cmdlineSize * sizeof(_TCHAR)); + if (tcmdline == NULL) + { + return -1; + } + + _TCHAR *p = tcmdline; + + *p++ = DQUOTE_TCHAR; + int cch = GetModuleFileName(NULL, p, MAX_PATH); + p += cch; + *p++ = DQUOTE_TCHAR; + +#ifndef WPRFLAG + int bytesWritten = -1; + errno_t saveErrno = errno; +#endif /* WPRFLAG */ + for (int i = 0; i < sb.Length; ++i) + { + wchar_t wc = sb[i]; +#ifdef WPRFLAG + *p++ = wc; +#else /* WPRFLAG */ + wctomb_s(&bytesWritten, p, cmdlineSize - (p - tcmdline), wc); + if (bytesWritten == -1) + { + *p++ = QUESTIONMARK_TCHAR; + } + else + { + p += bytesWritten; + } +#endif /* WPRFLAG */ + } + *p = 0; +#ifndef WPRFLAG + errno = saveErrno; +#endif /* WPRFLAG */ + +#ifdef WPRFLAG + _wcmdln = tcmdline; +#else /* WPRFLAG */ + _acmdln = tcmdline; +#endif /* WPRFLAG */ + + return 0; +} + +#endif /* !defined (_MANAGED_MAIN) && !defined (_WINMAIN_) */ + +#if defined (_MANAGED_MAIN) + +static void __clrcall __set_managed_app_type(void) +{ + PIMAGE_DOS_HEADER pDOSHeader; + PIMAGE_NT_HEADERS pPEHeader; + PIMAGE_OPTIONAL_HEADER pNTHeader; + + pDOSHeader = (PIMAGE_DOS_HEADER)GetModuleHandleW(NULL); + if ( pDOSHeader->e_magic != IMAGE_DOS_SIGNATURE ) + return; + + pPEHeader = (PIMAGE_NT_HEADERS)((char *)pDOSHeader + + pDOSHeader->e_lfanew); + if ( pPEHeader->Signature != IMAGE_NT_SIGNATURE ) + return; + + pNTHeader = (PIMAGE_OPTIONAL_HEADER)&pPEHeader->OptionalHeader; + if ( pNTHeader->Magic != IMAGE_NT_OPTIONAL_HDR_MAGIC ) + return; + + switch (pNTHeader->Subsystem) { + case IMAGE_SUBSYSTEM_WINDOWS_CUI: + _set_app_type(_crt_console_app); + break; + default: + _set_app_type(_crt_gui_app); + } +} + +#endif /* defined (_MANAGED_MAIN) */ + +/* + * This function is the shared initialization between MIXED and PURE. In Mixed, this function + * is called during _mixed_pre_c_init(), but in PURE, this function is called during + * mainCRTStartup. + */ +_CRT_SECURITYCRITICAL_ATTRIBUTE +static void __CLRCALL_OR_CDECL _common_init() +{ + /* + * Set __acrt_app_type properly + */ +#if defined (_MANAGED_MAIN) + __set_managed_app_type(); +#elif defined (_WINMAIN_) + _set_app_type(_crt_gui_app); +#else /* defined (_WINMAIN_) */ + _set_app_type(_crt_console_app); +#endif /* defined (_WINMAIN_) */ + + /* + * Propagate the _fmode and _commode variables to the DLL + */ + _set_fmode(_get_startup_file_mode()); + _commode = _get_startup_commit_mode(); + + /* Enable per-thread locale if user asked for it */ + _configthreadlocale(_get_startup_thread_locale_mode()); +} +#endif /* MRTDLL */ diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/mcrtexew.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/mcrtexew.cpp new file mode 100644 index 0000000000000000000000000000000000000000..aae2b5cd27beb62c43213a468f532c1acd14d36a --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/mcrtexew.cpp @@ -0,0 +1,18 @@ +/*** +*wcrtexew.c - Initialization for Windows EXE using CRT DLL, wchar_t version +* +* Copyright (c) Microsoft Corporation. All rights reserved. +* +*Purpose: +* This is the actual startup routine for Windows apps using wide +* characters. It calls the user's main routine wWinMain() after +* performing C Run-Time Library initialization. +* +*******************************************************************************/ + +#ifdef MRTDLL + +#define _WINMAIN_ +#include "mcrtexe.cpp" + +#endif /* MRTDLL */ diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/memchr.c b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/memchr.c new file mode 100644 index 0000000000000000000000000000000000000000..ac0a512c996180fe7f03af3ae682208e6e3b1b4d --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/memchr.c @@ -0,0 +1,48 @@ +/*** +*memchr.c - search block of memory for a given character +* +* Copyright (c) Microsoft Corporation. All rights reserved. +* +*Purpose: +* defines memchr() - search memory until a character is +* found or a limit is reached. +* +*******************************************************************************/ + +#include + +#pragma function(memchr) + +/*** +*char *memchr(buf, chr, cnt) - search memory for given character. +* +*Purpose: +* Searches at buf for the given character, stopping when chr is +* first found or cnt bytes have been searched through. +* +*Entry: +* void *buf - memory buffer to be searched +* int chr - character to search for +* size_t cnt - max number of bytes to search +* +*Exit: +* returns pointer to first occurrence of chr in buf +* returns NULL if chr not found in the first cnt bytes +* +*Exceptions: +* +*******************************************************************************/ + +void * __cdecl memchr ( + const void * buf, + int chr, + size_t cnt + ) +{ + while ( cnt && (*(unsigned char *)buf != (unsigned char)chr) ) { + buf = (unsigned char *)buf + 1; + cnt--; + } + + return(cnt ? (void *)buf : NULL); +} diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/mgdframe.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/mgdframe.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a0be954a9fd47ff3df86897e291c96c4c70af8f8 --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/mgdframe.cpp @@ -0,0 +1,334 @@ +/*** +* mgdframe.cpp - Managed exception frame support. +* +* Copyright (c) Microsoft Corporation. All rights reserved. +* +*Purpose: +* These routines are called by managed code during exception propagation. +* +****/ + +#include // User-visible routines for eh +#include // This project's versions of standard assert macros +#include // Declarations of all types used for EH +#include +#include // Declarations of hook variables and callbacks +#include // Routines to handle transfer of control (trnsctrl.asm) +#include +#include +#include "ehhelpers.h" + + +//////////////////////////////////////////////////////////////////////////////// +// Model of C++ eh in COM+ +// +// void func() +// { +// try { +// TryBody(); +// } catch (cpp_object o) +// { +// CatchOBody(); +// } catch (...) +// { +// CatchAllBody(); +// } +// } +// +// Turns into this: +// +// +// void func() +// { +// int rethrow; +// // One per try block +// int isCxxException; +// // One per catch(...) +// __try { +// TryBody(); +// } +// __except(__CxxExceptionFilter(exception, +// typeinfo(cpp_object), +// flags, +// &o)) +// // This is how it's done already +// { +// // Begin catch(object) prefix +// char *storage = _alloca(__CxxQueryExceptionSize()); +// rethrow = false; +// __CxxRegisterExceptionObject(exception, +// storage); +// __try { +// __try { +// // End catch(object) prefix +// CatchOBody(); +// // Begin catch(object) suffix +// } __except(rethrow = __CxxDetectRethrow(exception), +// EXCEPTION_CONTINUE_SEARCH) +// {} +// } +// __finally +// { +// __CxxUnregisterExceptionObject(storage, +// rethrow); +// } +// // End catch(object) suffix +// } +// __except(1) +// { +// // Begin catch(...) prefix +// char *storage = _alloca(__CxxQueryExceptionSize()); +// rethrow = false; +// isCxxException = __CxxRegisterExceptionObject(exception, +// storage); +// __try +// { +// __try +// { +// // End catch(...) prefix +// CatchAllBody(); +// // Begin catch(...) suffix +// } __except(rethrow = __CxxDetectRethrow(exception), +// EXCEPTION_CONTINUE_SEARCH) +// {} +// } __finally +// { +// if (isCxxException) +// __CxxUnregisterExceptionObject(storage, rethrow); +// } +// // End catch(...) suffix +// } +// } +// +//////////////////////////////////////////////////////////////////////////////// + +//////////////////////////////////////////////////////////////////////////////// +// +// __CxxExceptionFilter() - Returns EXCEPTION_EXECUTE_HANDLER when the pType +// matches with the objects we can catch. Returns +// EXCEPTION_CONTINUE_SEARCH when pType is not one of +// the catchable type for the thrown object. This +// function is made for use with COM+ EH, where they +// attempt to do C++ EH as well. +// + + +extern "C" int __cdecl __CxxExceptionFilter( + void *ppExcept, // Information for this (logical) + // exception + void *pType, // Info about the datatype. + int adjectives, // Extra Info about the datatype. + void *pBuildObj // Pointer to datatype. + ) +{ +#if _EH_RELATIVE_TYPEINFO + __int32 const *ppCatchable; +#elif defined(_WIN64) + CatchableType * UNALIGNED const *ppCatchable; +#else + CatchableType * const *ppCatchable; +#endif + CatchableType *pCatchable; + int catchables; + EHExceptionRecord *pExcept; + + if (!ppExcept) { + return EXCEPTION_CONTINUE_SEARCH; + } + pExcept = *(EHExceptionRecord **)ppExcept; + // If catch all, always return EXCEPTION_EXECUTE_HANDLER + // Note that if the adjective has HT_IsStdDotDot flag on, we comply Std + // C++ eh behaviour, i.e. only catching C++ objects. + if ( TD_IS_TYPE_ELLIPSIS((TypeDescriptor *)pType) && + (pExcept->ExceptionCode == MANAGED_EXCEPTION_CODE || + pExcept->ExceptionCode == MANAGED_EXCEPTION_CODE_V4 || + !(adjectives & HT_IsStdDotDot))) + { + if (PER_IS_MSVC_EH(pExcept)) + { + if ( PER_PTHROW(pExcept) == nullptr) + { + if ( _pCurrentException == nullptr) { + return EXCEPTION_CONTINUE_SEARCH; + } + } + } + __ProcessingThrow++; + return EXCEPTION_EXECUTE_HANDLER; + } + + int retVal = EXCEPTION_CONTINUE_SEARCH; + + if (PER_IS_MSVC_EH(pExcept)) + { + if ( PER_PTHROW(pExcept) == nullptr) { + if (_pCurrentException == nullptr) + return EXCEPTION_CONTINUE_SEARCH; + pExcept = _pCurrentException; + } + + /* + * Note that we will only be using pType or dispType + * and adjective field of pCatch. + */ + struct _s_HandlerType pCatch; +#if _EH_RELATIVE_TYPEINFO + _SetThrowImageBase((ptrdiff_t)pExcept->params.pThrowImageBase); +#endif +#if _EH_RELATIVE_FUNCINFO + ptrdiff_t ImageBaseBak = _GetImageBase(); + __try //Try finally for restoring _ImageBase; +#endif + { + +#if _EH_RELATIVE_FUNCINFO + void *CatchImageBase = nullptr; + // Set the image base using Rtl API. + if (pType) { + CatchImageBase = RtlPcToFileHeader(pType, &CatchImageBase); + } + _SetImageBase((ptrdiff_t)CatchImageBase); + + pCatch.dispType = (__int32)( + (ptrdiff_t)pType - (ptrdiff_t)CatchImageBase); +#else + pCatch.pType = (TypeDescriptor *)pType; +#endif + pCatch.adjectives = adjectives | HT_IsComplusEh; + + // Scan all types that thrown object can be converted to: + ppCatchable = THROW_CTLIST(*PER_PTHROW(pExcept)); + for (catchables = THROW_COUNT(*PER_PTHROW(pExcept)); + catchables > 0; catchables--, ppCatchable++) { + +#if _EH_RELATIVE_TYPEINFO + pCatchable = (CatchableType *)(_GetThrowImageBase() + *ppCatchable); +#else + pCatchable = *ppCatchable; +#endif + + if (__TypeMatch(&pCatch, pCatchable, PER_PTHROW(pExcept))) { + // Successful. Now build the object. + __ProcessingThrow++; + if (pBuildObj) + __BuildCatchObject(pExcept, pBuildObj, &pCatch, pCatchable); +#if _EH_RELATIVE_FUNCINFO + retVal = EXCEPTION_EXECUTE_HANDLER; + __leave; +#else // _EH_RELATIVE_FUNCINFO + return EXCEPTION_EXECUTE_HANDLER; +#endif // _EH_RELATIVE_FUNCINFO + } + } // Scan possible conversions + } +#if _EH_RELATIVE_FUNCINFO + __finally { + _SetImageBase(ImageBaseBak); + } +#endif + } + return retVal; +} + +//////////////////////////////////////////////////////////////////////////////// +// +// __CxxRegisterExceptionObject() - Registers an Exception object for managed +// C++ exception handling. +// +extern "C" int __cdecl __CxxRegisterExceptionObject( + void *ppExcept, + void *pStorage +) +{ + // This function is only called for C++ EH. + EHExceptionRecord *pExcept = nullptr; + FRAMEINFO *pFrameInfo = (FRAMEINFO *)pStorage; + EHExceptionRecord **ppSaveException; + CONTEXT **ppSaveExContext; + ppSaveException = (EHExceptionRecord **)(&pFrameInfo[1]); + ppSaveExContext = (CONTEXT **)(&ppSaveException[1]); + if (ppExcept && (*(void **)ppExcept)) { + pExcept = *(EHExceptionRecord **)ppExcept; + if (PER_IS_MSVC_EH(pExcept)) { + if ( PER_PTHROW(pExcept) == nullptr) { + // was a rethrow + pExcept = _pCurrentException; + } + } + pFrameInfo = _CreateFrameInfo(pFrameInfo, PER_PEXCEPTOBJ(pExcept)); + *ppSaveException = _pCurrentException; + *ppSaveExContext = _pCurrentExContext; + _pCurrentException = pExcept; + } else { + *ppSaveException = (EHExceptionRecord *)-1; + *ppSaveExContext = (CONTEXT *)-1; + } + __ProcessingThrow--; + if ( __ProcessingThrow < 0) + __ProcessingThrow = 0; + return 1; +} + +//////////////////////////////////////////////////////////////////////////////// +// +// __CxxDetectRethrow() - Looks at the Exception and returns true if rethrow, +// false if not a rethrow. This is then used for +// destructing the exception object in +// __CxxUnregisterExceptionObject(). +// +extern "C" int __cdecl __CxxDetectRethrow( + void *ppExcept +) +{ + EHExceptionRecord *pExcept; + if (!ppExcept) + return EXCEPTION_CONTINUE_SEARCH; + pExcept = *(EHExceptionRecord **)ppExcept; + if (PER_IS_MSVC_EH(pExcept) && PER_PTHROW(pExcept) == nullptr) { + __ProcessingThrow++; + return EXCEPTION_EXECUTE_HANDLER; + } + return EXCEPTION_CONTINUE_SEARCH; +} + +//////////////////////////////////////////////////////////////////////////////// +// +// __CxxUnregisterExceptionObject - Destructs Exception Objects if rethrow == +// true. Also set __pCurrentException and +// __pCurrentExContext() to current value. +// +extern "C" void __cdecl __CxxUnregisterExceptionObject( + void *pStorage, + int rethrow +) +{ + FRAMEINFO *pFrameInfo = (FRAMEINFO *)pStorage; + EHExceptionRecord **ppSaveException; + CONTEXT **ppSaveExContext; + ppSaveException = (EHExceptionRecord **)(&pFrameInfo[1]); + ppSaveExContext = (CONTEXT **)(&ppSaveException[1]); + if (*ppSaveException != (void *)-1) { + _FindAndUnlinkFrame(pFrameInfo); + if ( !rethrow && PER_IS_MSVC_EH(_pCurrentException) && + _IsExceptionObjectToBeDestroyed(PER_PEXCEPTOBJ(_pCurrentException)) + ) { + __DestructExceptionObject(_pCurrentException, TRUE); + } + if (PER_IS_MSVC_EH(_pCurrentException) && rethrow) + __ProcessingThrow--; + _pCurrentException = *ppSaveException; + _pCurrentExContext = *ppSaveExContext; + } +} + +//////////////////////////////////////////////////////////////////////////////// +// +// __CxxQueryExceptionSize - returns the value of Storage needed to save +// FrameInfo + two pointers. +// +extern "C" int __cdecl __CxxQueryExceptionSize( + void +) +{ + return sizeof(FRAMEINFO) + sizeof(void *) + sizeof(void *); +} diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/minternal.h b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/minternal.h new file mode 100644 index 0000000000000000000000000000000000000000..1e67e5e6f12e93728faf1f0fdf85806167d237f4 --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/minternal.h @@ -0,0 +1,478 @@ +/*** +*minternal.h - contains declarations of managed internal routines and variables +* +* Copyright (c) Microsoft Corporation. All rights reserved. +* +*Purpose: +* Declares routines and variables used internally by the C run-time. +* +* [Internal] +* +****/ + +// +// _CPP_MSTARTUP indicates that the file is included from mstartup.cpp +// _PARTIAL_TRUST_OBJ indicates that ptrust*.obj is being built +// !_CPP_MSTARTUP building msvcm* +// + +#pragma once + +#include +#include +// Don't pull have IID defns in the obj for mscoree.h +#ifdef EXTERN_GUID +#undef EXTERN_GUID +#endif /* EXTERN_GUID */ +#define EXTERN_GUID(itf,l1,s1,s2,c1,c2,c3,c4,c5,c6,c7,c8) EXTERN_C const IID itf +#include + +// #using is not used in the Windows build. +#if !defined _CRT_WINDOWS && defined _DEBUG + #using +#endif + +#define _INC_MINTERNAL + +#pragma warning(disable:4439) // C4439: function with a managed parameter must have a __clrcall calling convention +#pragma warning(disable:4483) // disable warning/error about __identifier() + +#ifdef _M_CEE + typedef void const* (__clrcall* _PVFVM)(void); + typedef int (__clrcall* _PIFVM)(void); + typedef void (__clrcall* _CPVFV)(void); +#endif + +namespace __identifier("") +{ + using System::AppDomain; + using System::Object; + using System::String; + using System::EventHandler; + using System::EventArgs; + using System::Threading::Interlocked; + using System::SerializableAttribute; +#ifndef _CLR_NETCORE + using System::CrossAppDomainDelegate; +#endif + using System::Collections::Stack; + using System::Threading::Interlocked; + using System::Runtime::Serialization::SerializationInfo; + using System::Runtime::Serialization::StreamingContext; + +#ifdef _CPP_MSTARTUP +#if defined (_M_CEE_MIXED) + typedef HRESULT (__stdcall* MixedFunctionType)(void*); + void __cdecl DoCallBackInDefaultDomain(MixedFunctionType function, void* cookie); +#endif /* defined (_M_CEE_MIXED) */ + void RegisterModuleUninitializer(EventHandler^ handler); + void ThrowModuleLoadException(String^ errorMessage); + void ThrowModuleLoadException(String^ errorMessage, System::Exception^ innerException); + void ThrowNestedModuleLoadException(System::Exception^ innerException, System::Exception^ nestedException); +#else /* _CPP_MSTARTUP */ + typedef HRESULT (__stdcall* MixedFunctionType)(void*); +#endif /* _CPP_MSTARTUP */ + +#if defined (_DEBUG) + #define MANAGED_ASSERT( test, message) System::Diagnostics::Debug::Assert(test, message) +#else /* defined (_DEBUG) */ + #define MANAGED_ASSERT( test, message ) +#endif /* defined (_DEBUG) */ + +} // namespace __identifier("") + +/////////////////////////////////////////////////////////////////////////////// +// +// building msvcm or ptrust*.obj +// + +namespace __identifier("") +{ + +/////////////////////////////////////////////////////////////////////////////// +// +// Exception +// + +// This is the base class for all managed exceptions thrown by the CRT +[System::SerializableAttribute] +ref class Exception : public System::Exception +{ +public: + Exception(System::String^ message) + : System::Exception(message) + { + } + + Exception(System::String^ message, System::Exception^ innerException) + : System::Exception(message, innerException) + { + } +protected: + Exception(SerializationInfo^ info, StreamingContext context) + : System::Exception(info, context) + { + } +}; + +// This is thrown by the CRT during module construction (errors thrown +// by the cctor) +[System::SerializableAttribute] +ref class ModuleLoadException : public System::Exception +{ +public: + ModuleLoadException(System::String^ message) + : Exception(message) + { + } + + ModuleLoadException(System::String^ message, System::Exception^ innerException) + : Exception(message, innerException) + { + } + + literal System::String^ Nested = "A nested exception occurred after the primary exception that caused the C++ module to fail to load.\n"; + +protected: + ModuleLoadException(SerializationInfo^ info, StreamingContext context) + : Exception(info, context) + { + } +}; + +// This is thrown when an exception occurs in the cleanup code executed while handling +// an exception thrown by the module constructor. +[System::SerializableAttribute] +ref class ModuleLoadExceptionHandlerException : public ModuleLoadException +{ +private: + typedef ModuleLoadException base; + literal System::String^ formatString = "\n{0}: {1}\n--- Start of primary exception ---\n{2}\n--- End of primary exception ---\n\n--- Start of nested exception ---\n{3}\n--- End of nested exception ---\n"; + +public: + + ModuleLoadExceptionHandlerException(System::String^ message, System::Exception^ innerException, System::Exception^ nestedException) + : base(message, innerException) + { + NestedException = nestedException; + } + + property System::Exception^ NestedException; + + virtual System::String^ ToString() override + { + System::String^ inner = InnerException ? InnerException->ToString() : System::String::Empty; + System::String^ nested = NestedException ? NestedException->ToString() : System::String::Empty; + System::String^ result = System::String::Format( + formatString, + this->GetType(), + Message ? Message : System::String::Empty, + inner ? inner : System::String::Empty, + nested ? nested : System::String::Empty + ); + return result; + } + + _CRT_SECURITYCRITICAL_ATTRIBUTE + virtual void GetObjectData(SerializationInfo^ info, StreamingContext context) override + { + base::GetObjectData(info, context); + info->AddValue("NestedException", NestedException, System::Exception::typeid); + } + +protected: + ModuleLoadExceptionHandlerException(SerializationInfo^ info, StreamingContext context) + : base(info, context) + { + NestedException = (System::Exception^)info->GetValue("NestedException", System::Exception::typeid); + } + +}; + +inline void ThrowNestedModuleLoadException(System::Exception^ innerException, System::Exception^ nestedException) +{ + throw gcnew ModuleLoadExceptionHandlerException(ModuleLoadException::Nested, innerException, nestedException); +} + +inline void ThrowModuleLoadException(String^ errorMessage) +{ + throw gcnew ModuleLoadException(errorMessage); +} + +inline void ThrowModuleLoadException(String^ errorMessage, System::Exception^ innerException) +{ + throw gcnew ModuleLoadException(errorMessage, innerException); +} + +/////////////////////////////////////////////////////////////////////////////// +// +// UnInitialize +// + +/* +// A single instance of this class is stored in each AppDomain +// It registers a handler for the AppDomain::DomainUnload and AppDomain::ProcessExit events +// and maintains a list of managed C++ modules loaded in that domain. When an unload +// event occurs, it calls back on the event handler registered by each of the modules +// in the reverse order to which they were added to the list. +*/ +ref class ModuleUninitializer : public Stack +{ +private: + static Object^ lock = gcnew Object(); + +internal: + // Static members are AppDomain specific. + // Instance for a new AppDomain is created when msvcm's .cctor tries to add its DomainUnload handler + static ModuleUninitializer^ _ModuleUninitializer = gcnew ModuleUninitializer(); + + // Safe for anyone to use because this class just relays the AppDomain::DomainUnload event + _CRT_SECURITYSAFECRITICAL_ATTRIBUTE + void AddHandler(EventHandler^ handler) + { +#ifndef _PARTIAL_TRUST_OBJ + bool mustReleaseLock = false; + System::Runtime::CompilerServices::RuntimeHelpers::PrepareConstrainedRegions(); + try + { + System::Runtime::CompilerServices::RuntimeHelpers::PrepareConstrainedRegions(); + System::Threading::Monitor::Enter(lock, mustReleaseLock); +#endif /* _PARTIAL_TRUST_OBJ */ + System::Runtime::CompilerServices::RuntimeHelpers::PrepareDelegate(handler); + Push(handler); +#ifndef _PARTIAL_TRUST_OBJ + } + finally + { + if (mustReleaseLock) + { + System::Threading::Monitor::Exit(lock); + } + } +#endif /* _PARTIAL_TRUST_OBJ */ + } + +private: + _CRT_SECURITYCRITICAL_ATTRIBUTE + static ModuleUninitializer(){} + // We've agreed the DomainUnload event is safe to let anyone use + _CRT_SECURITYSAFECRITICAL_ATTRIBUTE + ModuleUninitializer() + { + // Protected by lock in Initialize + // singletonHandler will be Prepared as a CER call when it's added to the DomainUnload event: + // this makes it a CER root + EventHandler^ singletonHandler = gcnew EventHandler(this, &ModuleUninitializer::SingletonDomainUnload); + AppDomain::CurrentDomain->DomainUnload += singletonHandler; + AppDomain::CurrentDomain->ProcessExit += singletonHandler; + } + + [System::Runtime::ConstrainedExecution::PrePrepareMethod] + _CRT_SECURITYCRITICAL_ATTRIBUTE + void SingletonDomainUnload(Object^ source, EventArgs^ arguments) + { +#ifndef _PARTIAL_TRUST_OBJ + bool mustReleaseLock = false; + System::Runtime::CompilerServices::RuntimeHelpers::PrepareConstrainedRegions(); + try + { + System::Runtime::CompilerServices::RuntimeHelpers::PrepareConstrainedRegions(); + System::Threading::Monitor::Enter(lock, mustReleaseLock); +#endif /* _PARTIAL_TRUST_OBJ */ + // Stack iterator starts at top and moves down through stack + for each (EventHandler^ handler in this) + { + handler(source, arguments); + } +#ifndef _PARTIAL_TRUST_OBJ + } + finally + { + if (mustReleaseLock) + { + System::Threading::Monitor::Exit(lock); + } + } +#endif /* _PARTIAL_TRUST_OBJ */ + } +}; + +inline void RegisterModuleUninitializer(EventHandler^ handler) +{ + ModuleUninitializer::_ModuleUninitializer->AddHandler(handler); +} + +// GUIDs are hardly ever a secret, and memory safety should be ensured by the type system +_CRT_SECURITYSAFECRITICAL_ATTRIBUTE +inline +System::Guid FromGUID(GUID const & guid) +{ + return System::Guid( guid.Data1, guid.Data2, guid.Data3, + guid.Data4[ 0 ], guid.Data4[ 1 ], + guid.Data4[ 2 ], guid.Data4[ 3 ], + guid.Data4[ 4 ], guid.Data4[ 5 ], + guid.Data4[ 6 ], guid.Data4[ 7 ] ); +} + +} // namespace __identifier("") + +#if defined (_M_CEE_MIXED) + +_CRT_SECURITYCRITICAL_ATTRIBUTE +inline HRESULT __get_default_appdomain(IUnknown **ppUnk) +{ + using System::Exception; + using System::Runtime::InteropServices::Marshal; + using System::Runtime::InteropServices::RuntimeEnvironment; + + HRESULT hr = S_OK; + ICorRuntimeHost *pHost = NULL; + + try + { + // Throws HR exception on failure. + pHost = reinterpret_cast( + RuntimeEnvironment::GetRuntimeInterfaceAsIntPtr( + __identifier("")::FromGUID(__uuidof(CorRuntimeHost)), + __identifier("")::FromGUID(__uuidof(ICorRuntimeHost))).ToPointer()); + } + catch (Exception^ ex) + { + hr = (HRESULT)Marshal::GetHRForException(ex); + } + + if (SUCCEEDED(hr)) + { + // GetDefaultDomain will not throw. + hr = pHost->GetDefaultDomain(ppUnk); + pHost->Release(); + } + + return hr; +} + +inline void __release_appdomain(IUnknown *ppUnk) +{ + ppUnk->Release(); +} + +namespace __identifier("") +{ + +_CRT_SECURITYCRITICAL_ATTRIBUTE +inline AppDomain^ GetDefaultDomain() +{ + using System::Runtime::InteropServices::Marshal; + IUnknown* pUnk = NULL; + HRESULT hresult = __get_default_appdomain(&pUnk); + + if (SUCCEEDED(hresult)) + { + try + { + Object^ pObject = Marshal::GetObjectForIUnknown(System::IntPtr(pUnk)); + + AppDomain^ pDomain = (AppDomain^)pObject; + + MANAGED_ASSERT(pDomain->IsDefaultAppDomain(), "Expecting default appdomain"); + + return pDomain; + } + finally + { + __release_appdomain(pUnk); + } + } + else + { + Marshal::ThrowExceptionForHR(hresult); + } + + return nullptr; +} + +_CRT_SECURITYCRITICAL_ATTRIBUTE +inline void DoCallBackInDefaultDomain(MixedFunctionType function, void* cookie) +{ + using System::Runtime::InteropServices::Marshal; + using System::Runtime::InteropServices::RuntimeEnvironment; + + HRESULT hr = S_OK; + + // Throws HR exception on failure. + ICLRRuntimeHost* pClrHost = nullptr; + pClrHost = reinterpret_cast( + RuntimeEnvironment::GetRuntimeInterfaceAsIntPtr( + __identifier("")::FromGUID(__uuidof(CLRRuntimeHost)), + __identifier("")::FromGUID(__uuidof(ICLRRuntimeHost))).ToPointer()); + + try + { + AppDomain^ defaultDomain = GetDefaultDomain(); + + hr = pClrHost->ExecuteInAppDomain(defaultDomain->Id, function, cookie); + if (FAILED(hr)) + { + Marshal::ThrowExceptionForHR(hr); + } + } + finally + { + pClrHost->Release(); + } +} + +[System::SerializableAttribute] +ref class OpenMPWithMultipleAppdomainsException + : public System::Exception +{ +public: + OpenMPWithMultipleAppdomainsException() { } +protected: + OpenMPWithMultipleAppdomainsException(SerializationInfo^ info, StreamingContext context) + : System::Exception(info, context) + { + } +}; + +// Returns true if the current application is using OpenMP +inline bool IsUsingOpenMP() +{ + HINSTANCE hMod = GetModuleHandleW(L"vcomp120.dll"); + + if ( hMod ) + { + void * fnp = GetProcAddress(hMod, "_vcomp_fork"); + if ( fnp ) + { + return true; + } + } + + hMod = GetModuleHandleW(L"vcomp120d.dll"); + if ( hMod ) + { + void * fnp = GetProcAddress(hMod, "_vcomp_fork"); + if ( fnp ) + { + return true; + } + } + + return false; +} + +#ifndef _PARTIAL_TRUST_OBJ +[System::Diagnostics::DebuggerStepThroughAttribute] +inline void DoDllLanguageSupportValidation() +{ + if (!AppDomain::CurrentDomain->IsDefaultAppDomain() && IsUsingOpenMP()) + { + throw gcnew OpenMPWithMultipleAppdomainsException(); + } +} +#endif /* _PARTIAL_TRUST_OBJ */ + +} // namespace __identifier("") + +#endif /* defined (_M_CEE_MIXED) */ diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/mlfind.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/mlfind.cpp new file mode 100644 index 0000000000000000000000000000000000000000..425f725be94f52905705d82ce779a8381dbf4cf6 --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/mlfind.cpp @@ -0,0 +1,23 @@ +/*** +*mlfind.cpp - do a binary search +* +* Copyright (c) Microsoft Corporation. All rights reserved. +* +*Purpose: +* defines _lfind() - do a binary search an an array +* +*******************************************************************************/ +#ifndef _M_CEE + #error This file should only be compiled as managed code. +#endif + +#undef MRTDLL + +#include "lfind.cpp" + +#ifdef __USE_CONTEXT + #error __USE_CONTEXT should be undefined +#endif + +#define __USE_CONTEXT +#include "lfind.cpp" diff --git a/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/mlsearch.cpp b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/mlsearch.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a5157ce9c7afe6464caa91c2e714e2686e46b482 --- /dev/null +++ b/miniMSVC/VC/Tools/MSVC/14.42.34433/crt/src/vcruntime/mlsearch.cpp @@ -0,0 +1,23 @@ +/*** +*mlsearch.cpp - do a binary search +* +* Copyright (c) Microsoft Corporation. All rights reserved. +* +*Purpose: +* defines _lsearch() - do a binary search an an array +* +*******************************************************************************/ +#ifndef _M_CEE + #error This file should only be compiled as managed code. +#endif + +#undef MRTDLL + +#include "lsearch.cpp" + +#ifdef __USE_CONTEXT + #error __USE_CONTEXT should be undefined +#endif + +#define __USE_CONTEXT +#include "lsearch.cpp"